problem_statement
stringlengths 147
8.53k
| input
stringlengths 1
771
| output
stringlengths 1
592
⌀ | time_limit
stringclasses 32
values | memory_limit
stringclasses 21
values | tags
stringlengths 6
168
|
---|---|---|---|---|---|
D. Trash Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries: 0 x — remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. 1 x — add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example.InputThe first line of the input contains two integers n and q (1 \le n, q \le 10^5) — the number of piles in the room before all queries and the number of queries, respectively.The second line of the input contains n distinct integers p_1, p_2, \dots, p_n (1 \le p_i \le 10^9), where p_i is the coordinate of the i-th pile.The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 \le t_i \le 1; 1 \le x_i \le 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles.OutputPrint q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries.ExamplesInput
5 6
1 2 6 8 10
1 4
1 9
0 6
0 10
1 100
1 50
Output
5
7
7
5
4
8
49
Input
5 8
5 1 2 4 3
0 1
0 2
0 3
0 4
0 5
1 1000000000
1 1
1 500000000
Output
3
2
1
0
0
0
0
0
499999999
NoteConsider the first example.Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves.After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves.After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move.After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10).After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8.After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too. | 5 6
1 2 6 8 10
1 4
1 9
0 6
0 10
1 100
1 50
| 5 7 7 5 4 8 49 | 3 seconds | 256 megabytes | ['data structures', 'implementation', '*2100'] |
C. Mortal Kombat Towertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are n bosses in this tower, numbered from 1 to n. The type of the i-th boss is a_i. If the i-th boss is easy then its type is a_i = 0, otherwise this boss is hard and its type is a_i = 1.During one session, either you or your friend can kill one or two bosses (neither you nor your friend can skip the session, so the minimum number of bosses killed during one session is at least one). After your friend session, your session begins, then again your friend session begins, your session begins, and so on. The first session is your friend's session.Your friend needs to get good because he can't actually kill hard bosses. To kill them, he uses skip points. One skip point can be used to kill one hard boss.Your task is to find the minimum number of skip points your friend needs to use so you and your friend kill all n bosses in the given order.For example: suppose n = 8, a = [1, 0, 1, 1, 0, 1, 1, 1]. Then the best course of action is the following: your friend kills two first bosses, using one skip point for the first boss; you kill the third and the fourth bosses; your friend kills the fifth boss; you kill the sixth and the seventh bosses; your friend kills the last boss, using one skip point, so the tower is completed using two skip points. You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of bosses. The second line of the test case contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 1), where a_i is the type of the i-th boss.It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer: the minimum number of skip points your friend needs to use so you and your friend kill all n bosses in the given order.ExampleInput
6
8
1 0 1 1 0 1 1 1
5
1 1 1 1 0
7
1 1 1 1 0 0 1
6
1 1 1 1 1 1
1
1
1
0
Output
2
2
2
2
1
0
| 6
8
1 0 1 1 0 1 1 1
5
1 1 1 1 0
7
1 1 1 1 0 0 1
6
1 1 1 1 1 1
1
1
1
0
| 2 2 2 2 1 0 | 1 second | 256 megabytes | ['dp', 'graphs', 'greedy', 'shortest paths', '*1500'] |
B. Negative Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a, consisting of n integers.Each position i (1 \le i \le n) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}], the underlined positions are locked. You can obtain the following arrays: [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]; [-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]; [1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]; [1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]; and some others. Let p be a sequence of prefix sums of the array a after the rearrangement. So p_1 = a_1, p_2 = a_1 + a_2, p_3 = a_1 + a_2 + a_3, \dots, p_n = a_1 + a_2 + \dots + a_n.Let k be the maximum j (1 \le j \le n) such that p_j < 0. If there are no j such that p_j < 0, then k = 0.Your goal is to rearrange the values in such a way that k is minimum possible.Output the array a after the rearrangement such that the value k for it is minimum possible. If there are multiple answers then print any of them.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Then t testcases follow.The first line of each testcase contains a single integer n (1 \le n \le 100) — the number of elements in the array a.The second line of each testcase contains n integers a_1, a_2, \dots, a_n (-10^5 \le a_i \le 10^5) — the initial array a.The third line of each testcase contains n integers l_1, l_2, \dots, l_n (0 \le l_i \le 1), where l_i = 0 means that the position i is unlocked and l_i = 1 means that the position i is locked.OutputPrint n integers — the array a after the rearrangement. Value k (the maximum j such that p_j < 0 (or 0 if there are no such j)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones.If there are multiple answers then print any of them.ExampleInput
5
3
1 3 2
0 0 0
4
2 -3 4 -1
1 1 1 1
7
-8 4 -2 -6 4 7 1
1 0 0 0 1 1 0
5
0 1 -4 6 3
0 0 0 1 1
6
-1 7 10 4 -8 -1
1 0 0 0 0 1
Output
1 2 3
2 -3 4 -1
-8 -6 1 4 4 7 -2
-4 0 1 6 3
-1 4 7 -8 10 -1NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in k = 0. For example, for an arrangement [1, 2, 3], p=[1, 3, 6], so there are no j such that p_j < 0. Thus, k = 0.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are p = [-8, -14, -13, -9, -5, 2, 0]. The maximum j is 5, thus k = 5. There are no arrangements such that k < 5.In the fourth testcase p = [-4, -4, -3, 3, 6].In the fifth testcase p = [-1, 3, 10, 2, 12, 11]. | 5
3
1 3 2
0 0 0
4
2 -3 4 -1
1 1 1 1
7
-8 4 -2 -6 4 7 1
1 0 0 0 1 1 0
5
0 1 -4 6 3
0 0 0 1 1
6
-1 7 10 4 -8 -1
1 0 0 0 0 1
| 1 2 3 2 -3 4 -1 -8 -6 1 4 4 7 -2 -4 0 1 6 3 -1 4 7 -8 10 -1 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*1300'] |
A. Buying Torchestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange 1 stick for x sticks (you lose 1 stick and gain x sticks). exchange y sticks for 1 coal (you lose y sticks and gain 1 coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least k torches. The answer always exists under the given constraints.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The only line of the test case contains three integers x, y and k (2 \le x \le 10^9; 1 \le y, k \le 10^9) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively.OutputFor each test case, print the answer: the minimum number of trades you need to craft at least k torches. The answer always exists under the given constraints.ExampleInput
5
2 1 5
42 13 24
12 11 12
1000000000 1000000000 1000000000
2 1000000000 1000000000
Output
14
33
25
2000000003
1000000001999999999
| 5
2 1 5
42 13 24
12 11 12
1000000000 1000000000 1000000000
2 1000000000 1000000000
| 14 33 25 2000000003 1000000001999999999 | 1 second | 256 megabytes | ['math', '*1000'] |
B. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRedDreamer has an array a consisting of n non-negative integers, and an unlucky integer T.Let's denote the misfortune of array b having length m as f(b) — the number of pairs of integers (i, j) such that 1 \le i < j \le m and b_i + b_j = T. RedDreamer has to paint each element of a into one of two colors, white and black (for each element, the color is chosen independently), and then create two arrays c and d so that all white elements belong to c, and all black elements belong to d (it is possible that one of these two arrays becomes empty). RedDreamer wants to paint the elements in such a way that f(c) + f(d) is minimum possible.For example: if n = 6, T = 7 and a = [1, 2, 3, 4, 5, 6], it is possible to paint the 1-st, the 4-th and the 5-th elements white, and all other elements black. So c = [1, 4, 5], d = [2, 3, 6], and f(c) + f(d) = 0 + 0 = 0; if n = 3, T = 6 and a = [3, 3, 3], it is possible to paint the 1-st element white, and all other elements black. So c = [3], d = [3, 3], and f(c) + f(d) = 0 + 1 = 1. Help RedDreamer to paint the array optimally!InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.The first line of each test case contains two integers n and T (1 \le n \le 10^5, 0 \le T \le 10^9) — the number of elements in the array and the unlucky integer, respectively. The second line contains n integers a_1, a_2, ..., a_n (0 \le a_i \le 10^9) — the elements of the array. The sum of n over all test cases does not exceed 10^5.OutputFor each test case print n integers: p_1, p_2, ..., p_n (each p_i is either 0 or 1) denoting the colors. If p_i is 0, then a_i is white and belongs to the array c, otherwise it is black and belongs to the array d.If there are multiple answers that minimize the value of f(c) + f(d), print any of them.ExampleInput
2
6 7
1 2 3 4 5 6
3 6
3 3 3
Output
1 0 0 1 1 0
1 0 0 | 2
6 7
1 2 3 4 5 6
3 6
3 3 3
| 1 0 0 1 1 0 1 0 0 | 1 second | 256 megabytes | ['greedy', 'math', 'sortings', '*1100'] |
A. Copy-pastetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output — Hey folks, how do you like this problem?— That'll do it. BThero is a powerful magician. He has got n piles of candies, the i-th pile initially contains a_i candies. BThero can cast a copy-paste spell as follows: He chooses two piles (i, j) such that 1 \le i, j \le n and i \ne j. All candies from pile i are copied into pile j. Formally, the operation a_j := a_j + a_i is performed. BThero can cast this spell any number of times he wants to — but unfortunately, if some pile contains strictly more than k candies, he loses his magic power. What is the maximum number of times BThero can cast the spell without losing his power?InputThe first line contains one integer T (1 \le T \le 500) — the number of test cases.Each test case consists of two lines: the first line contains two integers n and k (2 \le n \le 1000, 2 \le k \le 10^4); the second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le k). It is guaranteed that the sum of n over all test cases does not exceed 1000, and the sum of k over all test cases does not exceed 10^4.OutputFor each test case, print one integer — the maximum number of times BThero can cast the spell without losing his magic power.ExampleInput
3
2 2
1 1
3 5
1 2 3
3 7
3 2 2
Output
1
5
4
NoteIn the first test case we get either a = [1, 2] or a = [2, 1] after casting the spell for the first time, and it is impossible to cast it again. | 3
2 2
1 1
3 5
1 2 3
3 7
3 2 2
| 1 5 4 | 1 second | 256 megabytes | ['greedy', 'math', '*800'] |
F. Showing Offtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnother dull quarantine day was going by when BThero decided to start researching matrices of size n \times m. The rows are numerated 1 through n from top to bottom, and the columns are numerated 1 through m from left to right. The cell in the i-th row and j-th column is denoted as (i, j).For each cell (i, j) BThero had two values: The cost of the cell, which is a single positive integer. The direction of the cell, which is one of characters L, R, D, U. Those characters correspond to transitions to adjacent cells (i, j - 1), (i, j + 1), (i + 1, j) or (i - 1, j), respectively. No transition pointed outside of the matrix. Let us call a cell (i_2, j_2) reachable from (i_1, j_1), if, starting from (i_1, j_1) and repeatedly moving to the adjacent cell according to our current direction, we will, sooner or later, visit (i_2, j_2). BThero decided to create another matrix from the existing two. For a cell (i, j), let us denote S_{i, j} as a set of all reachable cells from it (including (i, j) itself). Then, the value at the cell (i, j) in the new matrix will be equal to the sum of costs of all cells in S_{i, j}. After quickly computing the new matrix, BThero immediately sent it to his friends. However, he did not save any of the initial matrices! Help him to restore any two valid matrices, which produce the current one.InputThe first line of input file contains a single integer T (1 \le T \le 100) denoting the number of test cases. The description of T test cases follows.First line of a test case contains two integers n and m (1 \le n \cdot m \le 10^5).Each of the following n lines contain exactly m integers — the elements of the produced matrix. Each element belongs to the segment [2, 10^9].It is guaranteed that \sum{(n \cdot m)} over all test cases does not exceed 10^5.OutputFor each test case, if an answer does not exist, print a single word NO. Otherwise, print YES and both matrices in the same format as in the input. The first matrix should be the cost matrix and the second matrix should be the direction matrix. All integers in the cost matrix should be positive. All characters in the direction matrix should be valid. No direction should point outside of the matrix. ExampleInput
2
3 4
7 6 7 8
5 5 4 4
5 7 4 4
1 1
5
Output
YES
1 1 1 1
2 1 1 1
3 2 1 1
R D L L
D R D L
U L R U
NO
| 2
3 4
7 6 7 8
5 5 4 4
5 7 4 4
1 1
5
| YES 1 1 1 1 2 1 1 1 3 2 1 1 R D L L D R D L U L R U NO | 6 seconds | 256 megabytes | ['flows', 'graph matchings', 'greedy', 'implementation', '*3300'] |
E. Splittime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, BThero decided to play around with arrays and came up with the following problem:You are given an array a, which consists of n positive integers. The array is numerated 1 through n. You execute the following procedure exactly once: You create a new array b which consists of 2n positive integers, where for each 1 \le i \le n the condition b_{2i-1}+b_{2i} = a_i holds. For example, for the array a = [6, 8, 2] you can create b = [2, 4, 4, 4, 1, 1]. You merge consecutive equal numbers in b. For example, b = [2, 4, 4, 4, 1, 1] becomes b = [2, 4, 1]. Find and print the minimum possible value of |b| (size of b) which can be achieved at the end of the procedure. It can be shown that under the given constraints there is at least one way to construct b.InputThe first line of the input file contains a single integer T (1 \le T \le 5 \cdot 10^5) denoting the number of test cases. The description of T test cases follows.The first line of each test contains a single integer n (1 \le n \le 5 \cdot 10^5).The second line contains n space-separated integers a_1, a_2, ..., a_n (2 \le a_i \le 10^9).It is guaranteed that \sum{n} over all test cases does not exceed 5 \cdot 10^5.OutputFor each test case, print a single line containing one integer — the minimum possible value of |b|.ExampleInput
3
3
6 8 2
1
4
3
5 6 6
Output
3
1
2
| 3
3
6 8 2
1
4
3
5 6 6
| 3 1 2 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dp', 'greedy', '*3200'] |
D. Graph and Queriestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph consisting of n vertices and m edges. Initially there is a single integer written on every vertex: the vertex i has p_i written on it. All p_i are distinct integers from 1 to n.You have to process q queries of two types: 1 v — among all vertices reachable from the vertex v using the edges of the graph (including the vertex v itself), find a vertex u with the largest number p_u written on it, print p_u and replace p_u with 0; 2 i — delete the i-th edge from the graph. Note that, in a query of the first type, it is possible that all vertices reachable from v have 0 written on them. In this case, u is not explicitly defined, but since the selection of u does not affect anything, you can choose any vertex reachable from v and print its value (which is 0). InputThe first line contains three integers n, m and q (1 \le n \le 2 \cdot 10^5; 1 \le m \le 3 \cdot 10^5; 1 \le q \le 5 \cdot 10^5).The second line contains n distinct integers p_1, p_2, ..., p_n, where p_i is the number initially written on vertex i (1 \le p_i \le n).Then m lines follow, the i-th of them contains two integers a_i and b_i (1 \le a_i, b_i \le n, a_i \ne b_i) and means that the i-th edge connects vertices a_i and b_i. It is guaranteed that the graph does not contain multi-edges.Then q lines follow, which describe the queries. Each line is given by one of the following formats: 1 v — denotes a query of the first type with a vertex v (1 \le v \le n). 2 i — denotes a query of the second type with an edge i (1 \le i \le m). For each query of the second type, it is guaranteed that the corresponding edge is not deleted from the graph yet. OutputFor every query of the first type, print the value of p_u written on the chosen vertex u.ExampleInput
5 4 6
1 2 5 4 3
1 2
2 3
1 3
4 5
1 1
2 1
2 3
1 1
1 2
1 2
Output
5
1
2
0
| 5 4 6
1 2 5 4 3
1 2
2 3
1 3
4 5
1 1
2 1
2 3
1 1
1 2
1 2
| 5 1 2 0 | 1.5 seconds | 256 megabytes | ['data structures', 'dsu', 'graphs', 'implementation', 'trees', '*2600'] |
C. XOR Inversetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i \oplus x (\oplus denotes the operation bitwise XOR).An inversion in the b array is a pair of integers i and j such that 1 \le i < j \le n and b_i > b_j.You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.InputFirst line contains a single integer n (1 \le n \le 3 \cdot 10^5) — the number of elements in a.Second line contains n space-separated integers a_1, a_2, ..., a_n (0 \le a_i \le 10^9), where a_i is the i-th element of a.OutputOutput two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.ExamplesInput
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
NoteIn the first sample it is optimal to leave the array as it is by choosing x = 0.In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions: i = 2, j = 3; i = 2, j = 4; i = 3, j = 4; i = 8, j = 9. In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions. | 4
0 1 3 2
| 1 0 | 2 seconds | 512 megabytes | ['bitmasks', 'data structures', 'divide and conquer', 'dp', 'greedy', 'math', 'sortings', 'strings', 'trees', '*2000'] |
B. Make Them Equaltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: choose three integers i, j and x (1 \le i, j \le n; 0 \le x \le 10^9); assign a_i := a_i - x \cdot i, a_j := a_j + x \cdot i. After each operation, all elements of the array should be non-negative.Can you find a sequence of no more than 3n operations after which all elements of the array are equal?InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of each test case contains one integer n (1 \le n \le 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^5) — the elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 10^4.OutputFor each test case print the answer to it as follows: if there is no suitable sequence of operations, print -1; otherwise, print one integer k (0 \le k \le 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 \le i, j \le n; 0 \le x \le 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k.ExampleInput
3
4
2 16 4 18
6
1 2 3 4 5 6
5
11 19 1 1 3
Output
2
4 1 2
2 3 3
-1
4
1 2 4
2 4 5
2 3 3
4 5 1
| 3
4
2 16 4 18
6
1 2 3 4 5 6
5
11 19 1 1 3
| 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*2000'] |
A. k-Amazing Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers numbered from 1 to n.Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there is no integer occuring in all subsegments of length k for some value of k, then the k-amazing number is -1.For each k from 1 to n calculate the k-amazing number of the array a.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.The first line of each test case contains one integer n (1 \le n \le 3 \cdot 10^5) — the number of elements in the array. The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case print n integers, where the i-th integer is equal to the i-amazing number of the array.ExampleInput
3
5
1 2 3 4 5
5
4 4 4 4 2
6
1 3 1 5 3 1
Output
-1 -1 3 2 1
-1 4 4 4 2
-1 -1 1 1 1 1
| 3
5
1 2 3 4 5
5
4 4 4 4 2
6
1 3 1 5 3 1
| -1 -1 3 2 1 -1 4 4 4 2 -1 -1 1 1 1 1 | 1 second | 256 megabytes | ['binary search', 'data structures', 'implementation', 'two pointers', '*1500'] |
F. Cakes for Clonestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou live on a number line. You are initially (at time moment t = 0) located at point x = 0. There are n events of the following type: at time t_i a small cake appears at coordinate x_i. To collect this cake, you have to be at this coordinate at this point, otherwise the cake spoils immediately. No two cakes appear at the same time and no two cakes appear at the same coordinate.You can move with the speed of 1 length unit per one time unit. Also, at any moment you can create a clone of yourself at the same point where you are located. The clone can't move, but it will collect the cakes appearing at this position for you. The clone disappears when you create another clone. If the new clone is created at time moment t, the old clone can collect the cakes that appear before or at the time moment t, and the new clone can collect the cakes that appear at or after time moment t.Can you collect all the cakes (by yourself or with the help of clones)?InputThe first line contains a single integer n (1 \le n \le 5000) — the number of cakes.Each of the next n lines contains two integers t_i and x_i (1 \le t_i \le 10^9, -10^9 \le x_i \le 10^9) — the time and coordinate of a cake's appearance.All times are distinct and are given in increasing order, all the coordinates are distinct.OutputPrint "YES" if you can collect all cakes, otherwise print "NO".ExamplesInput
3
2 2
5 5
6 1
Output
YES
Input
3
1 0
5 5
6 2
Output
YES
Input
3
2 1
5 5
6 0
Output
NO
NoteIn the first example you should start moving towards 5 right away, leaving a clone at position 1 at time moment 1, and collecting the cake at position 2 at time moment 2. At time moment 5 you are at the position 5 and collect a cake there, your clone collects the last cake at time moment 6.In the second example you have to leave a clone at position 0 and start moving towards position 5. At time moment 1 the clone collects a cake. At time moment 2 you should create a new clone at the current position 2, it will collect the last cake in future. You will collect the second cake at position 5.In the third example there is no way to collect all cakes. | 3
2 2
5 5
6 1
| YES | 3 seconds | 256 megabytes | ['dp', '*2900'] |
E. New Game Plus!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWabbit is playing a game with n bosses numbered from 1 to n. The bosses can be fought in any order. Each boss needs to be defeated exactly once. There is a parameter called boss bonus which is initially 0.When the i-th boss is defeated, the current boss bonus is added to Wabbit's score, and then the value of the boss bonus increases by the point increment c_i. Note that c_i can be negative, which means that other bosses now give fewer points.However, Wabbit has found a glitch in the game. At any point in time, he can reset the playthrough and start a New Game Plus playthrough. This will set the current boss bonus to 0, while all defeated bosses remain defeated. The current score is also saved and does not reset to zero after this operation. This glitch can be used at most k times. He can reset after defeating any number of bosses (including before or after defeating all of them), and he also can reset the game several times in a row without defeating any boss.Help Wabbit determine the maximum score he can obtain if he has to defeat all n bosses.InputThe first line of input contains two spaced integers n and k (1 \leq n \leq 5 \cdot 10^5, 0 \leq k \leq 5 \cdot 10^5), representing the number of bosses and the number of resets allowed.The next line of input contains n spaced integers c_1,c_2,\ldots,c_n (-10^6 \leq c_i \leq 10^6), the point increments of the n bosses.OutputOutput a single integer, the maximum score Wabbit can obtain by defeating all n bosses (this value may be negative).ExamplesInput
3 0
1 1 1
Output
3
Input
5 1
-1 -2 -3 -4 5
Output
11
Input
13 2
3 1 4 1 5 -9 -2 -6 -5 -3 -5 -8 -9
Output
71
NoteIn the first test case, no resets are allowed. An optimal sequence of fights would be Fight the first boss (+0). Boss bonus becomes equal to 1. Fight the second boss (+1). Boss bonus becomes equal to 2. Fight the third boss (+2). Boss bonus becomes equal to 3. Thus the answer for the first test case is 0+1+2=3.In the second test case, it can be shown that one possible optimal sequence of fights is Fight the fifth boss (+0). Boss bonus becomes equal to 5. Fight the first boss (+5). Boss bonus becomes equal to 4. Fight the second boss (+4). Boss bonus becomes equal to 2. Fight the third boss (+2). Boss bonus becomes equal to -1. Reset. Boss bonus becomes equal to 0. Fight the fourth boss (+0). Boss bonus becomes equal to -4. Hence the answer for the second test case is 0+5+4+2+0=11. | 3 0
1 1 1
| 3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*2200'] |
D. XOR-guntime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady owns a non-decreasing array a_1, a_2, \ldots, a_n. You are jealous of its beauty and want to destroy this property. You have a so-called XOR-gun that you can use one or more times.In one step you can select two consecutive elements of the array, let's say x and y, remove them from the array and insert the integer x \oplus y on their place, where \oplus denotes the bitwise XOR operation. Note that the length of the array decreases by one after the operation. You can't perform this operation when the length of the array reaches one.For example, if the array is [2, 5, 6, 8], you can select 5 and 6 and replace them with 5 \oplus 6 = 3. The array becomes [2, 3, 8].You want the array no longer be non-decreasing. What is the minimum number of steps needed? If the array stays non-decreasing no matter what you do, print -1.InputThe first line contains a single integer n (2 \le n \le 10^5) — the initial length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the elements of the array. It is guaranteed that a_i \le a_{i + 1} for all 1 \le i < n.OutputPrint a single integer — the minimum number of steps needed. If there is no solution, print -1.ExamplesInput
4
2 5 6 8
Output
1
Input
3
1 2 3
Output
-1
Input
5
1 2 4 6 20
Output
2
NoteIn the first example you can select 2 and 5 and the array becomes [7, 6, 8].In the second example you can only obtain arrays [1, 1], [3, 3] and [0] which are all non-decreasing.In the third example you can select 1 and 2 and the array becomes [3, 4, 6, 20]. Then you can, for example, select 3 and 4 and the array becomes [7, 6, 20], which is no longer non-decreasing. | 4
2 5 6 8
| 1 | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', 'constructive algorithms', '*2000'] |
C. Bouncing Balltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from 1, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell p, then bounces off it, then bounces off a platform in the cell (p + k), then a platform in the cell (p + 2k), and so on every k-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these p and k.You already have some level pattern a_1, a_2, a_3, ..., a_n, where a_i = 0 means there is no platform in the cell i, and a_i = 1 means there is one. You want to modify it so that the level can be passed with given p and k. In x seconds you can add a platform in some empty cell. In y seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than p. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given p and k?InputThe first line contains the number of test cases t (1 \le t \le 100). Description of test cases follows.The first line of each test case contains three integers n, p, and k (1 \le p \le n \le 10^5, 1 \le k \le n) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required.The second line of each test case contains a string a_1 a_2 a_3 \ldots a_n (a_i = 0 or a_i = 1) — the initial pattern written without spaces.The last line of each test case contains two integers x and y (1 \le x, y \le 10^4) — the time required to add a platform and to remove the first cell correspondingly.The sum of n over test cases does not exceed 10^5.OutputFor each test case output a single integer — the minimum number of seconds you need to modify the level accordingly.It can be shown that it is always possible to make the level passable.ExampleInput
3
10 3 2
0101010101
2 2
5 4 1
00000
2 10
11 2 3
10110011000
4 3
Output
2
4
10
NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is y = 2.In the second test case it's best to add a platform to both cells 4 and 5: 00000 \to 00011. The time required is x \cdot 2 = 4.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially 10-th: 10110011000 \to 10110011010. The time required is y \cdot 2 + x = 10. | 3
10 3 2
0101010101
2 2
5 4 1
00000
2 10
11 2 3
10110011000
4 3
| 2 4 10 | 1 second | 256 megabytes | ['brute force', 'dp', 'implementation', '*1400'] |
B. Repainting Streettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a street with n houses in a line, numbered from 1 to n. The house i is initially painted in color c_i. The street is considered beautiful if all houses are painted in the same color. Tom, the painter, is in charge of making the street beautiful. Tom's painting capacity is defined by an integer, let's call it k.On one day, Tom can do the following repainting process that consists of two steps: He chooses two integers l and r such that 1 \le l \le r \le n and r - l + 1 = k . For each house i such that l \le i \le r, he can either repaint it with any color he wants, or ignore it and let it keep its current color. Note that in the same day Tom can use different colors to repaint different houses.Tom wants to know the minimum number of days needed to repaint the street so that it becomes beautiful.InputThe first line of input contains a single integer t ( 1 \le t \le 10^4), the number of test cases. Description of test cases follows.In the first line of a test case description there are two integers n and k (1 \le k \le n \le 10^5).The second line contains n space-separated integers. The i-th of these integers represents c_i (1 \le c_i \le 100), the color which house i is initially painted in.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputPrint t lines, each with one integer: the minimum number of days Tom needs to make the street beautiful for each test case. ExampleInput
3
10 2
1 1 2 2 1 1 2 2 2 1
7 1
1 2 3 4 5 6 7
10 3
1 3 3 3 3 1 2 1 3 3
Output
3
6
2
NoteIn the first test case Tom should paint houses 1 and 2 in the first day in color 2, houses 5 and 6 in the second day in color 2, and the last house in color 2 on the third day.In the second test case Tom can, for example, spend 6 days to paint houses 1, 2, 4, 5, 6, 7 in color 3.In the third test case Tom can paint the first house in the first day and houses 6, 7, and 8 in the second day in color 3. | 3
10 2
1 1 2 2 1 1 2 2 2 1
7 1
1 2 3 4 5 6 7
10 3
1 3 3 3 3 1 2 1 3 3
| 3 6 2 | 1 second | 256 megabytes | ['brute force', 'brute force', 'greedy', '*1100'] |
A. Prison Breaktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a prison that can be represented as a rectangular matrix with n rows and m columns. Therefore, there are n \cdot m prison cells. There are also n \cdot m prisoners, one in each prison cell. Let's denote the cell in the i-th row and the j-th column as (i, j).There's a secret tunnel in the cell (r, c), that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell (i, j) can move to cells ( i - 1 , j ) , ( i + 1 , j ) , ( i , j - 1 ) , or ( i , j + 1 ), as long as the target cell is inside the prison. They can also choose to stay in cell (i, j).The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell ( r , c ) if they move optimally. Note that there can be any number of prisoners in the same cell at the same time. InputThe first line contains an integer t (1 \le t \le 10^4), the number of test cases.Each of the next t lines contains four space-separated integers n, m, r, c (1 \le r \le n \le 10^9, 1 \le c \le m \le 10^9).OutputPrint t lines, the answers for each test case.ExampleInput
3
10 10 1 1
3 5 2 4
10 2 5 1
Output
18
4
6
| 3
10 10 1 1
3 5 2 4
10 2 5 1
| 18 4 6 | 1 second | 256 megabytes | ['brute force', 'math', '*800'] |
F. Roads and Ramentime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn the Land of Fire there are n villages and n-1 bidirectional road, and there is a path between any pair of villages by roads. There are only two types of roads: stone ones and sand ones. Since the Land of Fire is constantly renovating, every morning workers choose a single road and flip its type (so it becomes a stone road if it was a sand road and vice versa). Also everyone here loves ramen, that's why every morning a ramen pavilion is set in the middle of every stone road, and at the end of each day all the pavilions are removed.For each of the following m days, after another road is flipped, Naruto and Jiraiya choose a simple path — that is, a route which starts in a village and ends in a (possibly, the same) village, and doesn't contain any road twice. Since Naruto and Jiraiya also love ramen very much, they buy a single cup of ramen on each stone road and one of them eats it. Since they don't want to offend each other, they only choose routes where they can eat equal number of ramen cups. Since they both like traveling, they choose any longest possible path. After every renovation find the maximal possible length of a path (that is, the number of roads in it) they can follow.InputThe first line contains the only positive integer n (2 \leq n \leq 500\,000) standing for the number of villages in the Land of Fire.Each of the following (n-1) lines contains a description of another road, represented as three positive integers u, v and t (1 \leq u, v \leq n, t \in \{0,1\}). The first two numbers denote the villages connected by the road, and the third denotes the initial type of the road: 0 for the sand one and 1 for the stone one. Roads are numbered from 1 to (n-1) in the order from the input.The following line contains a positive integer m (1 \leq m \leq 500\,000) standing for the number of days Naruto and Jiraiya travel for.Each of the following m lines contains the single integer id (1 \leq id \leq n-1) standing for the index of the road whose type is flipped on the morning of corresponding day.It is guaranteed that there is a road path between any pair of villages.OutputOutput m lines. In the i-th of them print the only integer denoting the maximal possible length of any valid path on the i-th day.ExampleInput
5
1 2 0
1 3 0
3 5 0
3 4 0
5
3
4
1
3
4
Output
3
2
3
3
2
NoteAfter the renovation of the 3-rd road the longest path consists of the roads 1, 2 and 4.After the renovation of the 4-th road one of the longest paths consists of the roads 1 and 2.After the renovation of the 1-st road one of the longest paths consists of the roads 1, 2 and 3.After the renovation of the 3-rd road the longest path consists of the roads 1, 2 and 4.After the renovation of the 4-rd road one of the longest paths consists of the roads 2 and 4. | 5
1 2 0
1 3 0
3 5 0
3 4 0
5
3
4
1
3
4
| 3 2 3 3 2 | 5 seconds | 512 megabytes | ['data structures', 'trees', '*2800'] |
E. Solo mid Oracletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMeka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k\cdot b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?InputThe first line contains an integer t (1\leq t\leq 10^5) standing for the number of testcases.Each test case is described with one line containing four numbers a, b, c and d (1\leq a, b, c, d\leq 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.OutputFor each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.ExampleInput
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
NoteIn the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.In the fourth test case of the example the enemy gets: 4 damage (1-st spell cast) at time 0; 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health); 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health); and so on. One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.In the seventh test case the answer does not fit into a 32-bit integer type. | 7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
| 1 2 1 5 534 -1 500000500000 | 1 second | 256 megabytes | ['greedy', 'math', 'ternary search', '*2100'] |
D. Shurikenstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.Tenten keeps a record for all events, and she ends up with a list of the following types of records: + means that she placed another shuriken on the showcase; - x means that the shuriken of price x was bought. Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!InputThe first line contains the only integer n (1\leq n\leq 10^5) standing for the number of shurikens. The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.OutputIf the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.ExamplesInput
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
NoteIn the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there. | 4
+
+
- 2
+
- 3
+
- 1
- 4
| YES 4 2 3 1 | 1 second | 256 megabytes | ['data structures', 'greedy', 'implementation', '*1700'] |
C. Perform Easilytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has 6 strings and an infinite number of frets numbered from 1. Fretting the fret number j on the i-th string produces the note a_{i} + j.Tayuya wants to play a melody of n notes. Each note can be played on different string-fret combination. The easiness of performance depends on the difference between the maximal and the minimal indices of used frets. The less this difference is, the easier it is to perform the technique. Please determine the minimal possible difference.For example, if a = [1, 1, 2, 2, 3, 3], and the sequence of notes is 4, 11, 11, 12, 12, 13, 13 (corresponding to the second example), we can play the first note on the first string, and all the other notes on the sixth string. Then the maximal fret will be 10, the minimal one will be 3, and the answer is 10 - 3 = 7, as shown on the picture. InputThe first line contains 6 space-separated numbers a_{1}, a_{2}, ..., a_{6} (1 \leq a_{i} \leq 10^{9}) which describe the Tayuya's strings.The second line contains the only integer n (1 \leq n \leq 100\,000) standing for the number of notes in the melody.The third line consists of n integers b_{1}, b_{2}, ..., b_{n} (1 \leq b_{i} \leq 10^{9}), separated by space. They describe the notes to be played. It's guaranteed that b_i > a_j for all 1\leq i\leq n and 1\leq j\leq 6, in other words, you can play each note on any string.OutputPrint the minimal possible difference of the maximal and the minimal indices of used frets.ExamplesInput
1 4 100 10 30 5
6
101 104 105 110 130 200
Output
0
Input
1 1 2 2 3 3
7
13 4 11 12 11 13 12
Output
7
NoteIn the first sample test it is optimal to play the first note on the first string, the second note on the second string, the third note on the sixth string, the fourth note on the fourth string, the fifth note on the fifth string, and the sixth note on the third string. In this case the 100-th fret is used each time, so the difference is 100 - 100 = 0. In the second test it's optimal, for example, to play the second note on the first string, and all the other notes on the sixth string. Then the maximal fret will be 10, the minimal one will be 3, and the answer is 10 - 3 = 7. | 1 4 100 10 30 5
6
101 104 105 110 130 200
| 0 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'dp', 'implementation', 'sortings', 'two pointers', '*1900'] |
B. A New Techniquetime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputAll techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of n\cdot m different seals, denoted by distinct numbers. All of them were written in an n\times m table.The table is lost now. Naruto managed to remember elements of each row from left to right, and elements of each column from top to bottom, but he doesn't remember the order of rows and columns. Please restore the table consistent with this data so that Naruto will be able to learn the new technique.InputThe first line of the input contains the only integer t (1\leq t\leq 100\,000) denoting the number of test cases. Their descriptions follow.The first line of each test case description consists of two space-separated integers n and m (1 \leq n, m \leq 500) standing for the number of rows and columns in the table, respectively. All hand seals are encoded by the positive integers from 1 to n\cdot m.The following n lines contain m space separated integers each, denoting elements of an arbitrary row in the table left to right.The following m lines contain n space separated integers each, denoting elements of an arbitrary column in the table top to bottom.Sum of nm over all test cases does not exceed 250\,000. It is guaranteed that each row occurs in the input exactly once, as well as each column. It is also guaranteed that each number from 1 to nm occurs exactly once in all rows, as well as in all columns. Finally, it is guaranteed that a table consistent with the input exists.OutputFor each test case, output n lines with m space-separated integers each, denoting the restored table. One can show that the answer is always unique.ExampleInput
2
2 3
6 5 4
1 2 3
1 6
2 5
3 4
3 1
2
3
1
3 1 2
Output
1 2 3
6 5 4
3
1
2
NoteConsider the first test case. The matrix is 2 \times 3. You are given the rows and columns in arbitrary order.One of the rows is [6, 5, 4]. One of the rows is [1, 2, 3].One of the columns is [1, 6]. One of the columns is [2, 5]. One of the columns is [3, 4].You are to reconstruct the matrix. The answer is given in the output. | 2
2 3
6 5 4
1 2 3
1 6
2 5
3 4
3 1
2
3
1
3 1 2
| 1 2 3 6 5 4 3 1 2 | 1 second | 512 megabytes | ['implementation', '*1100'] |
A. Finding Sasuketime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNaruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are T rooms there. Every room has a door into it, each door can be described by the number n of seals on it and their integer energies a_1, a_2, ..., a_n. All energies a_i are nonzero and do not exceed 100 by absolute value. Also, n is even.In order to open a door, Naruto must find such n seals with integer energies b_1, b_2, ..., b_n that the following equality holds: a_{1} \cdot b_{1} + a_{2} \cdot b_{2} + ... + a_{n} \cdot b_{n} = 0. All b_i must be nonzero as well as a_i are, and also must not exceed 100 by absolute value. Please find required seals for every room there.InputThe first line contains the only integer T (1 \leq T \leq 1000) standing for the number of rooms in the Orochimaru's lair. The other lines contain descriptions of the doors.Each description starts with the line containing the only even integer n (2 \leq n \leq 100) denoting the number of seals.The following line contains the space separated sequence of nonzero integers a_1, a_2, ..., a_n (|a_{i}| \leq 100, a_{i} \neq 0) denoting the energies of seals.OutputFor each door print a space separated sequence of nonzero integers b_1, b_2, ..., b_n (|b_{i}| \leq 100, b_{i} \neq 0) denoting the seals that can open the door. If there are multiple valid answers, print any. It can be proven that at least one answer always exists.ExampleInput
2
2
1 100
4
1 2 3 6
Output
-100 1
1 1 1 -1
NoteFor the first door Naruto can use energies [-100, 1]. The required equality does indeed hold: 1 \cdot (-100) + 100 \cdot 1 = 0.For the second door Naruto can use, for example, energies [1, 1, 1, -1]. The required equality also holds: 1 \cdot 1 + 2 \cdot 1 + 3 \cdot 1 + 6 \cdot (-1) = 0. | 2
2
1 100
4
1 2 3 6
| -100 1 1 1 1 -1 | 1 second | 256 megabytes | ['constructive algorithms', 'math', '*800'] |
G. No Game No Lifetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's consider the following game of Alice and Bob on a directed acyclic graph. Each vertex may contain an arbitrary number of chips. Alice and Bob make turns alternating. Alice goes first. In one turn player can move exactly one chip along any edge outgoing from the vertex that contains this chip to the end of this edge. The one who cannot make a turn loses. Both players play optimally.Consider the following process that takes place every second on a given graph with n vertices: An integer v is chosen equiprobably from [1, n + 1]. If v \leq n, we add a chip to the v-th vertex and go back to step 1. If v = n + 1, Alice and Bob play the game with the current arrangement of chips and the winner is determined. After that, the process is terminated. Find the probability that Alice will win the game. It can be shown that the answer can be represented as \frac{P}{Q}, where P and Q are coprime integers and Q \not\equiv 0 \pmod{998\,244\,353}. Print the value of P \cdot Q^{-1} \bmod 998\,244\,353.InputThe first line contains two integers n and m — the number of vertices and edges of the graph (1 \leq n \leq 10^5, 0 \leq m \leq 10^5).The following m lines contain edges description. The i-th of them contains two integers u_i and v_i — the beginning and the end vertices of the i-th edge (1 \leq u_i, v_i \leq n). It's guaranteed that the graph is acyclic.OutputOutput a single integer — the probability of Alice victory modulo 998\,244\,353.ExamplesInput
1 0
Output
0
Input
2 1
1 2
Output
332748118
Input
5 5
1 4
5 2
4 3
1 5
5 4
Output
931694730
| 1 0
| 0 | 2 seconds | 256 megabytes | ['bitmasks', 'games', 'math', 'matrices', '*2700'] |
F. The Thorny Pathtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAccording to a legend the Hanoi Temple holds a permutation of integers from 1 to n. There are n stones of distinct colors lying in one line in front of the temple. Monks can perform the following operation on stones: choose a position i (1 \le i \le n) and cyclically shift stones at positions i, p[i], p[p[i]], .... That is, a stone from position i will move to position p[i], a stone from position p[i] will move to position p[p[i]], and so on, a stone from position j, such that p[j] = i, will move to position i.Each day the monks must obtain a new arrangement of stones using an arbitrary number of these operations. When all possible arrangements will have been obtained, the world will end. You are wondering, what if some elements of the permutation could be swapped just before the beginning? How many days would the world last?You want to get a permutation that will allow the world to last as long as possible, using the minimum number of exchanges of two elements of the permutation.Two arrangements of stones are considered different if there exists a position i such that the colors of the stones on that position are different in these arrangements.InputEach test consists of multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^3). Description of the test cases follows.The first line of each test case contains n (3 \leq n \leq 10^6). The next line contains n integers p_1, \dots, p_n (1 \le p_i \le n). It is guaranteed that p is a permutation.It is guaranteed that the sum of n over all test cases does not exceed 10^6. OutputFor each of the t test cases, print two integers on a new line: the largest possible number of days the world can last, modulo 10^9 + 7, and the minimum number of exchanges required for that.ExamplesInput
3
3
2 3 1
3
2 1 3
3
1 2 3
Output
3 0
3 1
3 2
Input
5
4
2 3 4 1
4
2 3 1 4
4
2 1 4 3
4
2 1 3 4
4
1 2 3 4
Output
4 0
4 1
4 0
4 1
4 2
NoteLet's label the colors of the stones with letters. Explanations for the first two test cases of the first example: Using the permutation [2, 3, 1], we can additionally obtain the arrangements CAB and BCA from ABC. This is already the maximum possible result. Using the permutation [2, 1, 3], the only BAC can be obtained from ABC. As we saw in the previous case, two arrangements are not the maximum possible number of distinct arrangements for n = 3. To get an optimal permutation, for example, we can swap 1 and 3, so we will get the permutation [2, 3, 1]. | 3
3
2 3 1
3
2 1 3
3
1 2 3
| 3 0 3 1 3 2 | 2 seconds | 256 megabytes | ['greedy', 'math', '*3000'] |
E. Poman Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a string S consisting of n lowercase English letters from your friend. It turned out that this is a number written in poman numerals. The poman numeral system is long forgotten. All that's left is the algorithm to transform number from poman numerals to the numeral system familiar to us. Characters of S are numbered from 1 to n from left to right. Let's denote the value of S as f(S), it is defined as follows: If |S| > 1, an arbitrary integer m (1 \le m < |S|) is chosen, and it is defined that f(S) = -f(S[1, m]) + f(S[m + 1, |S|]), where S[l, r] denotes the substring of S from the l-th to the r-th position, inclusively. Otherwise S = c, where c is some English letter. Then f(S) = 2^{pos(c)}, where pos(c) is the position of letter c in the alphabet (pos(a) = 0, pos(z) = 25). Note that m is chosen independently on each step.Your friend thinks it is possible to get f(S) = T by choosing the right m on every step. Is he right?InputThe first line contains two integers n and T (2 \leq n \leq 10^5, -10^{15} \leq T \leq 10^{15}).The second line contains a string S consisting of n lowercase English letters.OutputPrint "Yes" if it is possible to get the desired value. Otherwise, print "No".You can print each letter in any case (upper or lower).ExamplesInput
2 -1
ba
Output
Yes
Input
3 -7
abc
Output
No
Input
7 -475391
qohshra
Output
Yes
NoteIn the second example, you cannot get -7. But you can get 1, for example, as follows: First choose m = 1, then f(abc) = -f(a) + f(bc) f(a) = 2^0 = 1 f(bc) = -f(b) + f(c) = -2^1 + 2^2 = 2 In the end f(abc) = -1 + 2 = 1 | 2 -1
ba
| Yes | 1 second | 256 megabytes | ['bitmasks', 'greedy', 'math', 'strings', '*2300'] |
D. Grime Zootime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCurrently, XXOC's rap is a string consisting of zeroes, ones, and question marks. Unfortunately, haters gonna hate. They will write x angry comments for every occurrence of subsequence 01 and y angry comments for every occurrence of subsequence 10. You should replace all the question marks with 0 or 1 in such a way that the number of angry comments would be as small as possible.String b is a subsequence of string a, if it can be obtained by removing some characters from a. Two occurrences of a subsequence are considered distinct if sets of positions of remaining characters are distinct.InputThe first line contains string s — XXOC's rap (1 \le |s| \leq 10^5). The second line contains two integers x and y — the number of angry comments XXOC will recieve for every occurrence of 01 and 10 accordingly (0 \leq x, y \leq 10^6).OutputOutput a single integer — the minimum number of angry comments.ExamplesInput
0?1
2 3
Output
4
Input
?????
13 37
Output
0
Input
?10?
239 7
Output
28
Input
01101001
5 7
Output
96
NoteIn the first example one of the optimum ways to replace is 001. Then there will be 2 subsequences 01 and 0 subsequences 10. Total number of angry comments will be equal to 2 \cdot 2 + 0 \cdot 3 = 4.In the second example one of the optimum ways to replace is 11111. Then there will be 0 subsequences 01 and 0 subsequences 10. Total number of angry comments will be equal to 0 \cdot 13 + 0 \cdot 37 = 0.In the third example one of the optimum ways to replace is 1100. Then there will be 0 subsequences 01 and 4 subsequences 10. Total number of angry comments will be equal to 0 \cdot 239 + 4 \cdot 7 = 28.In the fourth example one of the optimum ways to replace is 01101001. Then there will be 8 subsequences 01 and 8 subsequences 10. Total number of angry comments will be equal to 8 \cdot 5 + 8 \cdot 7 = 96. | 0?1
2 3
| 4 | 1 second | 256 megabytes | ['brute force', 'greedy', 'implementation', 'strings', '*2100'] |
C. Peaceful Rookstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a n \times n chessboard. Rows and columns of the board are numbered from 1 to n. Cell (x, y) lies on the intersection of column number x and row number y.Rook is a chess piece, that can in one turn move any number of cells vertically or horizontally. There are m rooks (m < n) placed on the chessboard in such a way that no pair of rooks attack each other. I.e. there are no pair of rooks that share a row or a column.In one turn you can move one of the rooks any number of cells vertically or horizontally. Additionally, it shouldn't be attacked by any other rook after movement. What is the minimum number of moves required to place all the rooks on the main diagonal?The main diagonal of the chessboard is all the cells (i, i), where 1 \le i \le n.InputThe first line contains the number of test cases t (1 \leq t \leq 10^3). Description of the t test cases follows.The first line of each test case contains two integers n and m — size of the chessboard and the number of rooks (2 \leq n \leq 10^5, 1 \leq m < n). Each of the next m lines contains two integers x_i and y_i — positions of rooks, i-th rook is placed in the cell (x_i, y_i) (1 \leq x_i, y_i \leq n). It's guaranteed that no two rooks attack each other in the initial placement.The sum of n over all test cases does not exceed 10^5.OutputFor each of t test cases print a single integer — the minimum number of moves required to place all the rooks on the main diagonal.It can be proved that this is always possible.ExampleInput
4
3 1
2 3
3 2
2 1
1 2
5 3
2 3
3 1
1 2
5 4
4 5
5 1
2 2
3 3
Output
1
3
4
2
NotePossible moves for the first three test cases: (2, 3) \to (2, 2) (2, 1) \to (2, 3), (1, 2) \to (1, 1), (2, 3) \to (2, 2) (2, 3) \to (2, 4), (2, 4) \to (4, 4), (3, 1) \to (3, 3), (1, 2) \to (1, 1) | 4
3 1
2 3
3 2
2 1
1 2
5 3
2 3
3 1
1 2
5 4
4 5
5 1
2 2
3 3
| 1 3 4 2 | 1 second | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', '*1700'] |
B. Fair Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe call a positive integer number fair if it is divisible by each of its nonzero digits. For example, 102 is fair (because it is divisible by 1 and 2), but 282 is not, because it isn't divisible by 8. Given a positive integer n. Find the minimum integer x, such that n \leq x and x is fair.InputThe first line contains number of test cases t (1 \leq t \leq 10^3). Each of the next t lines contains an integer n (1 \leq n \leq 10^{18}).OutputFor each of t test cases print a single integer — the least fair number, which is not less than n.ExampleInput
4
1
282
1234567890
1000000000000000000
Output
1
288
1234568040
1000000000000000000
NoteExplanations for some test cases: In the first test case number 1 is fair itself. In the second test case number 288 is fair (it's divisible by both 2 and 8). None of the numbers from [282, 287] is fair, because, for example, none of them is divisible by 8. | 4
1
282
1234567890
1000000000000000000
| 1 288 1234568040 1000000000000000000 | 2 seconds | 256 megabytes | ['brute force', 'number theory', '*1000'] |
A. In-game Chattime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have been assigned to develop a filter for bad messages in the in-game chat. A message is a string S of length n, consisting of lowercase English letters and characters ')'. The message is bad if the number of characters ')' at the end of the string strictly greater than the number of remaining characters. For example, the string ")bc)))" has three parentheses at the end, three remaining characters, and is not considered bad.InputThe first line contains the number of test cases t (1 \leq t \leq 100). Description of the t test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 100). The second line of each test case contains a string S of length n, consisting of lowercase English letters and characters ')'.OutputFor each of t test cases, print "Yes" if the string is bad. Otherwise, print "No".You can print each letter in any case (upper or lower).ExampleInput
5
2
))
12
gl))hf))))))
9
gege)))))
14
)aa))b))))))))
1
)
Output
Yes
No
Yes
Yes
Yes
| 5
2
))
12
gl))hf))))))
9
gege)))))
14
)aa))b))))))))
1
)
| Yes No Yes Yes Yes | 1 second | 256 megabytes | ['implementation', '*800'] |
F. Subsequences of Length Twotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t consisting of lowercase Latin letters. The length of t is 2 (i.e. this string consists only of two characters).In one move, you can choose any character of s and replace it with any lowercase Latin letter. More formally, you choose some i and replace s_i (the character at the position i) with some character from 'a' to 'z'.You want to do no more than k replacements in such a way that maximizes the number of occurrences of t in s as a subsequence.Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements.InputThe first line of the input contains two integers n and k (2 \le n \le 200; 0 \le k \le n) — the length of s and the maximum number of moves you can make. The second line of the input contains the string s consisting of n lowercase Latin letters. The third line of the input contains the string t consisting of two lowercase Latin letters.OutputPrint one integer — the maximum possible number of occurrences of t in s as a subsequence if you replace no more than k characters in s optimally.ExamplesInput
4 2
bbaa
ab
Output
3
Input
7 3
asddsaf
sd
Output
10
Input
15 6
qwertyhgfdsazxc
qa
Output
16
Input
7 2
abacaba
aa
Output
15
NoteIn the first example, you can obtain the string "abab" replacing s_1 with 'a' and s_4 with 'b'. Then the answer is 3.In the second example, you can obtain the string "ssddsdd" and get the answer 10.In the fourth example, you can obtain the string "aaacaaa" and get the answer 15. | 4 2
bbaa
ab
| 3 | 2 seconds | 256 megabytes | ['dp', 'strings', '*2100'] |
E. Two Platformstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n points on a plane. The i-th point has coordinates (x_i, y_i). You have two horizontal platforms, both of length k. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same y-coordinate) and have integer borders. If the left border of the platform is (x, y) then the right border is (x + k, y) and all points between borders (including borders) belong to the platform.Note that platforms can share common points (overlap) and it is not necessary to place both platforms on the same y-coordinate.When you place both platforms on a plane, all points start falling down decreasing their y-coordinate. If a point collides with some platform at some moment, the point stops and is saved. Points which never collide with any platform are lost.Your task is to find the maximum number of points you can save if you place both platforms optimally.You have to answer t independent test cases.For better understanding, please read the Note section below to see a picture for the first test case.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains two integers n and k (1 \le n \le 2 \cdot 10^5; 1 \le k \le 10^9) — the number of points and the length of each platform, respectively. The second line of the test case contains n integers x_1, x_2, \dots, x_n (1 \le x_i \le 10^9), where x_i is x-coordinate of the i-th point. The third line of the input contains n integers y_1, y_2, \dots, y_n (1 \le y_i \le 10^9), where y_i is y-coordinate of the i-th point. All points are distinct (there is no pair 1 \le i < j \le n such that x_i = x_j and y_i = y_j).It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer: the maximum number of points you can save if you place both platforms optimally.ExampleInput
4
7 1
1 5 2 3 1 5 4
1 3 6 7 2 5 4
1 1
1000000000
1000000000
5 10
10 7 5 15 8
20 199 192 219 1904
10 10
15 19 8 17 20 10 9 2 10 19
12 13 6 17 1 14 7 9 19 3
Output
6
1
5
10
NoteThe picture corresponding to the first test case of the example:Blue dots represent the points, red segments represent the platforms. One of the possible ways is to place the first platform between points (1, -1) and (2, -1) and the second one between points (4, 3) and (5, 3). Vectors represent how the points will fall down. As you can see, the only point we can't save is the point (3, 7) so it falls down infinitely and will be lost. It can be proven that we can't achieve better answer here. Also note that the point (5, 3) doesn't fall at all because it is already on the platform. | 4
7 1
1 5 2 3 1 5 4
1 3 6 7 2 5 4
1 1
1000000000
1000000000
5 10
10 7 5 15 8
20 199 192 219 1904
10 10
15 19 8 17 20 10 9 2 10 19
12 13 6 17 1 14 7 9 19 3
| 6 1 5 10 | 2 seconds | 256 megabytes | ['binary search', 'dp', 'sortings', 'two pointers', '*1800'] |
D. Decrease the Sum of Digitstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The only line of the test case contains two integers n and s (1 \le n \le 10^{18}; 1 \le s \le 162).OutputFor each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.ExampleInput
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
| 5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
| 8 0 500 2128012501878 899999999999999999 | 2 seconds | 256 megabytes | ['greedy', 'math', '*1500'] |
C. Yet Another Array Restorationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array: The array consists of n distinct positive (greater than 0) integers. The array contains two elements x and y (these elements are known for you) such that x < y. If you sort the array in increasing order (such that a_1 < a_2 < \ldots < a_n), differences between all adjacent (consecutive) elements are equal (i.e. a_2 - a_1 = a_3 - a_2 = \ldots = a_n - a_{n-1}). It can be proven that such an array always exists under the constraints given below.Among all possible arrays that satisfy the given conditions, we ask you to restore one which has the minimum possible maximum element. In other words, you have to minimize \max(a_1, a_2, \dots, a_n).You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.The only line of the test case contains three integers n, x and y (2 \le n \le 50; 1 \le x < y \le 50) — the length of the array and two elements that are present in the array, respectively.OutputFor each test case, print the answer: n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the i-th element of the required array. If there are several answers, you can print any (it also means that the order of elements doesn't matter).It can be proven that such an array always exists under the given constraints.ExampleInput
5
2 1 49
5 20 50
6 20 50
5 3 8
9 13 22
Output
1 49
20 40 30 50 10
26 32 20 38 44 50
8 23 18 13 3
1 10 13 4 19 22 25 16 7 | 5
2 1 49
5 20 50
6 20 50
5 3 8
9 13 22
| 1 49 20 40 30 50 10 26 32 20 38 44 50 8 23 18 13 3 1 10 13 4 19 22 25 16 7 | 1 second | 256 megabytes | ['brute force', 'math', 'number theory', '*1200'] |
B. Minimum Producttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given four integers a, b, x and y. Initially, a \ge x and b \ge y. You can do the following operation no more than n times: Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y. Your task is to find the minimum possible product of a and b (a \cdot b) you can achieve by applying the given operation no more than n times.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The only line of the test case contains five integers a, b, x, y and n (1 \le a, b, x, y, n \le 10^9). Additional constraint on the input: a \ge x and b \ge y always holds.OutputFor each test case, print one integer: the minimum possible product of a and b (a \cdot b) you can achieve by applying the given operation no more than n times.ExampleInput
7
10 10 8 5 3
12 8 8 7 2
12343 43 4543 39 123212
1000000000 1000000000 1 1 1
1000000000 1000000000 1 1 1000000000
10 11 2 1 5
10 11 9 1 10
Output
70
77
177177
999999999000000000
999999999
55
10
NoteIn the first test case of the example, you need to decrease b three times and obtain 10 \cdot 7 = 70.In the second test case of the example, you need to decrease a one time, b one time and obtain 11 \cdot 7 = 77.In the sixth test case of the example, you need to decrease a five times and obtain 5 \cdot 11 = 55.In the seventh test case of the example, you need to decrease b ten times and obtain 10 \cdot 1 = 10. | 7
10 10 8 5 3
12 8 8 7 2
12343 43 4543 39 123212
1000000000 1000000000 1 1 1
1000000000 1000000000 1 1 1000000000
10 11 2 1 5
10 11 9 1 10
| 70 77 177177 999999999000000000 999999999 55 10 | 1 second | 256 megabytes | ['brute force', 'greedy', 'math', '*1100'] |
A. Yet Another Two Integers Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers a and b.In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k \in [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.Your task is to find the minimum number of moves required to obtain b from a.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The only line of the test case contains two integers a and b (1 \le a, b \le 10^9).OutputFor each test case, print the answer: the minimum number of moves required to obtain b from a.ExampleInput
6
5 5
13 42
18 4
1337 420
123456789 1000000000
100500 9000
Output
0
3
2
92
87654322
9150
NoteIn the first test case of the example, you don't need to do anything.In the second test case of the example, the following sequence of moves can be applied: 13 \rightarrow 23 \rightarrow 32 \rightarrow 42 (add 10, add 9, add 10).In the third test case of the example, the following sequence of moves can be applied: 18 \rightarrow 10 \rightarrow 4 (subtract 8, subtract 6). | 6
5 5
13 42
18 4
1337 420
123456789 1000000000
100500 9000
| 0 3 2 92 87654322 9150 | 1 second | 256 megabytes | ['greedy', 'math', '*800'] |
I. Bitwise Magictime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer k and an array a_1, a_2, \ldots, a_n of non-negative distinct integers not smaller than k and not greater than 2^c-1.In each of the next k seconds, one element is chosen randomly equiprobably out of all n elements and decreased by 1.For each integer x, 0 \leq x \leq 2^c - 1, you need to find the probability that in the end the bitwise XOR of all elements of the array is equal to x. Each of these values can be represented as an irreducible fraction \frac{p}{q}, and you need to find the value of p \cdot q^{-1} modulo 998\,244\,353. InputThe first line of input contains three integers n, k, c (1 \leq n \leq (2^c - k), 1 \leq k \leq 16, 1 \leq c \leq 16).The second line contains n distinct integers a_1, a_2, \ldots, a_n (k \leq a_i \leq 2^c-1).OutputPrint 2^c integers: the probability that the bitwise XOR is equal to x in the end for x in \{0, 1, \ldots, 2^c-1\} modulo 998\,244\,353.ExampleInput
4 1 3
1 2 3 4
Output
0 0 0 748683265 0 499122177 0 748683265
| 4 1 3
1 2 3 4
| 0 0 0 748683265 0 499122177 0 748683265 | 6 seconds | 256 megabytes | ['dp', 'math', '*3200'] |
H. Rainbow Triplestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a_1, a_2, \ldots, a_n of non-negative integers.You need to find the largest number m of triples (i_1, j_1, k_1), (i_2, j_2, k_2), ..., (i_m, j_m, k_m) such that: 1 \leq i_p < j_p < k_p \leq n for each p in 1, 2, \ldots, m; a_{i_p} = a_{k_p} = 0, a_{j_p} \neq 0; all a_{j_1}, a_{j_2}, \ldots, a_{j_m} are different; all i_1, j_1, k_1, i_2, j_2, k_2, \ldots, i_m, j_m, k_m are different.InputThe first line of input contains one integer t (1 \leq t \leq 500\,000): the number of test cases.The first line of each test case contains one integer n (1 \leq n \leq 500\,000).The second line contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq n).The total sum of n is at most 500\,000.OutputFor each test case, print one integer m: the largest number of proper triples that you can find.ExampleInput
8
1
1
2
0 0
3
0 1 0
6
0 0 1 2 0 0
6
0 1 0 0 1 0
6
0 1 3 2 0 0
6
0 0 0 0 5 0
12
0 1 0 2 2 2 0 0 3 3 4 0
Output
0
0
1
2
1
1
1
2
NoteIn the first two test cases, there are not enough elements even for a single triple, so the answer is 0.In the third test case we can select one triple (1, 2, 3).In the fourth test case we can select two triples (1, 3, 5) and (2, 4, 6).In the fifth test case we can select one triple (1, 2, 3). We can't select two triples (1, 2, 3) and (4, 5, 6), because a_2 = a_5. | 8
1
1
2
0 0
3
0 1 0
6
0 0 1 2 0 0
6
0 1 0 0 1 0
6
0 1 3 2 0 0
6
0 0 0 0 5 0
12
0 1 0 2 2 2 0 0 3 3 4 0
| 0 0 1 2 1 1 1 2 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'flows', 'greedy', '*3300'] |
G. Clusterization Countingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n computers in the company network. They are numbered from 1 to n.For each pair of two computers 1 \leq i < j \leq n you know the value a_{i,j}: the difficulty of sending data between computers i and j. All values a_{i,j} for i<j are different.You want to separate all computers into k sets A_1, A_2, \ldots, A_k, such that the following conditions are satisfied: for each computer 1 \leq i \leq n there is exactly one set A_j, such that i \in A_j; for each two pairs of computers (s, f) and (x, y) (s \neq f, x \neq y), such that s, f, x are from the same set but x and y are from different sets, a_{s,f} < a_{x,y}. For each 1 \leq k \leq n find the number of ways to divide computers into k groups, such that all required conditions are satisfied. These values can be large, so you need to find them by modulo 998\,244\,353.InputThe first line contains a single integer n (1 \leq n \leq 1500): the number of computers.The i-th of the next n lines contains n integers a_{i,1}, a_{i,2}, \ldots, a_{i,n}(0 \leq a_{i,j} \leq \frac{n (n-1)}{2}).It is guaranteed that: for all 1 \leq i \leq n a_{i,i} = 0; for all 1 \leq i < j \leq n a_{i,j} > 0; for all 1 \leq i < j \leq n a_{i,j} = a_{j,i}; all a_{i,j} for i <j are different. OutputPrint n integers: the k-th of them should be equal to the number of possible ways to divide computers into k groups, such that all required conditions are satisfied, modulo 998\,244\,353.ExamplesInput
4
0 3 4 6
3 0 2 1
4 2 0 5
6 1 5 0
Output
1 0 1 1
Input
7
0 1 18 15 19 12 21
1 0 16 13 17 20 14
18 16 0 2 7 10 9
15 13 2 0 6 8 11
19 17 7 6 0 4 5
12 20 10 8 4 0 3
21 14 9 11 5 3 0
Output
1 1 2 3 4 3 1
NoteHere are all possible ways to separate all computers into 4 groups in the second example: \{1, 2\}, \{3, 4\}, \{5\}, \{6, 7\}; \{1\}, \{2\}, \{3, 4\}, \{5, 6, 7\}; \{1, 2\}, \{3\}, \{4\}, \{5, 6, 7\}. | 4
0 3 4 6
3 0 2 1
4 2 0 5
6 1 5 0
| 1 0 1 1 | 3 seconds | 256 megabytes | ['combinatorics', 'dp', 'dsu', 'fft', 'graphs', 'trees', '*2700'] |
F. Two Differenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n.You should find a list of pairs (x_1, y_1), (x_2, y_2), ..., (x_q, y_q) (1 \leq x_i, y_i \leq n) satisfying the following condition.Let's consider some function f: \mathbb{N} \times \mathbb{N} \to \mathbb{N} (we define \mathbb{N} as the set of positive integers). In other words, f is a function that returns a positive integer for a pair of positive integers.Let's make an array a_1, a_2, \ldots, a_n, where a_i = i initially.You will perform q operations, in i-th of them you will: assign t = f(a_{x_i}, a_{y_i}) (t is a temporary variable, it is used only for the next two assignments); assign a_{x_i} = t; assign a_{y_i} = t. In other words, you need to simultaneously change a_{x_i} and a_{y_i} to f(a_{x_i}, a_{y_i}). Note that during this process f(p, q) is always the same for a fixed pair of p and q.In the end, there should be at most two different numbers in the array a.It should be true for any function f.Find any possible list of pairs. The number of pairs should not exceed 5 \cdot 10^5.InputThe single line contains a single integer n (1 \leq n \leq 15\,000).OutputIn the first line print q (0 \leq q \leq 5 \cdot 10^5) — the number of pairs.In each of the next q lines print two integers. In the i-th line print x_i, y_i (1 \leq x_i, y_i \leq n).The condition described in the statement should be satisfied.If there exists multiple answers you can print any of them.ExamplesInput
3
Output
1
1 2
Input
4
Output
2
1 2
3 4
NoteIn the first example, after performing the only operation the array a will be [f(a_1, a_2), f(a_1, a_2), a_3]. It will always have at most two different numbers.In the second example, after performing two operations the array a will be [f(a_1, a_2), f(a_1, a_2), f(a_3, a_4), f(a_3, a_4)]. It will always have at most two different numbers. | 3
| 1 1 2 | 3 seconds | 256 megabytes | ['constructive algorithms', 'divide and conquer', '*2300'] |
E. Avoid Rainbow Cyclestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given m sets of integers A_1, A_2, \ldots, A_m; elements of these sets are integers between 1 and n, inclusive.There are two arrays of positive integers a_1, a_2, \ldots, a_m and b_1, b_2, \ldots, b_n. In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.You can make several (maybe none) operations (some sets can become empty).After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y \in A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.You call a cycle i_1 \to e_1 \to i_2 \to e_2 \to \ldots \to i_k \to e_k \to i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.Find the minimum number of coins you should pay to get a graph without rainbow cycles.InputThe first line contains two integers m and n (1 \leq m, n \leq 10^5), the number of sets and the number of vertices in the graph.The second line contains m integers a_1, a_2, \ldots, a_m (1 \leq a_i \leq 10^9).The third line contains n integers b_1, b_2, \ldots, b_n (1 \leq b_i \leq 10^9).In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 \leq s_i \leq n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.It is guaranteed that the sum of s_i for all 1 \leq i \leq m does not exceed 2 \cdot 10^5.OutputPrint one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.ExamplesInput
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
NoteIn the first test, you can make such operations: Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that. Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that. You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.So, the graph will consist of one edge (1, 2) of color 3.In the second test, you can make such operations: Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that. Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that. Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that. Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that. Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that. You pay 66 coins in total.After these operations, the sets will be: \{2, 3\}; \{1\}; \{1, 3\}; \{3\}; \{3, 4, 5, 6, 7\}; \{5\}; \{8\}. We will get the graph:There are no rainbow cycles in it. | 3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
| 11 | 1 second | 256 megabytes | ['data structures', 'dsu', 'graphs', 'greedy', 'sortings', 'trees', '*2400'] |
D. Searchlightstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points.Searchlight j can see a robber i if a_i \leq c_j and b_i \leq d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i).What is the minimum number of moves you need to perform to reach a safe configuration?InputThe first line of input contains two integers n and m (1 \leq n, m \leq 2000): the number of robbers and the number of searchlight.Each of the next n lines contains two integers a_i, b_i (0 \leq a_i, b_i \leq 10^6), coordinates of robbers.Each of the next m lines contains two integers c_i, d_i (0 \leq c_i, d_i \leq 10^6), coordinates of searchlights.OutputPrint one integer: the minimum number of moves you need to perform to reach a safe configuration.ExamplesInput
1 1
0 0
2 3
Output
3
Input
2 3
1 6
6 1
10 1
1 10
7 7
Output
4
Input
1 2
0 0
0 0
0 0
Output
1
Input
7 3
0 8
3 8
2 7
0 10
5 5
7 0
3 5
6 6
3 11
11 5
Output
6
NoteIn the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0).The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2.In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3).It's easy the see that the configuration of the robbers is safe.It can be proved that you can't reach a safe configuration using no more than 3 moves. | 1 1
0 0
2 3
| 3 | 1 second | 256 megabytes | ['binary search', 'brute force', 'data structures', 'dp', 'implementation', 'sortings', 'two pointers', '*2000'] |
C. Discrete Accelerationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a road with length l meters. The start of the road has coordinate 0, the end of the road has coordinate l.There are two cars, the first standing at the start of the road and the second standing at the end of the road. They will start driving simultaneously. The first car will drive from the start to the end and the second car will drive from the end to the start.Initially, they will drive with a speed of 1 meter per second. There are n flags at different coordinates a_1, a_2, \ldots, a_n. Each time when any of two cars drives through a flag, the speed of that car increases by 1 meter per second.Find how long will it take for cars to meet (to reach the same coordinate). InputThe first line contains one integer t (1 \leq t \leq 10^4): the number of test cases.The first line of each test case contains two integers n, l (1 \leq n \leq 10^5, 1 \leq l \leq 10^9): the number of flags and the length of the road.The second line contains n integers a_1, a_2, \ldots, a_n in the increasing order (1 \leq a_1 < a_2 < \ldots < a_n < l).It is guaranteed that the sum of n among all test cases does not exceed 10^5.OutputFor each test case print a single real number: the time required for cars to meet.Your answer will be considered correct, if its absolute or relative error does not exceed 10^{-6}. More formally, if your answer is a and jury's answer is b, your answer will be considered correct if \frac{|a-b|}{\max{(1, b)}} \leq 10^{-6}.ExampleInput
5
2 10
1 9
1 10
1
5 7
1 2 3 4 6
2 1000000000
413470354 982876160
9 478
1 10 25 33 239 445 453 468 477
Output
3.000000000000000
3.666666666666667
2.047619047619048
329737645.750000000000000
53.700000000000000
NoteIn the first test case cars will meet in the coordinate 5.The first car will be in the coordinate 1 in 1 second and after that its speed will increase by 1 and will be equal to 2 meters per second. After 2 more seconds it will be in the coordinate 5. So, it will be in the coordinate 5 in 3 seconds.The second car will be in the coordinate 9 in 1 second and after that its speed will increase by 1 and will be equal to 2 meters per second. After 2 more seconds it will be in the coordinate 5. So, it will be in the coordinate 5 in 3 seconds.In the second test case after 1 second the first car will be in the coordinate 1 and will have the speed equal to 2 meters per second, the second car will be in the coordinate 9 and will have the speed equal to 1 meter per second. So, they will meet after \frac{9-1}{2+1} = \frac{8}{3} seconds. So, the answer is equal to 1 + \frac{8}{3} = \frac{11}{3}. | 5
2 10
1 9
1 10
1
5 7
1 2 3 4 6
2 1000000000
413470354 982876160
9 478
1 10 25 33 239 445 453 468 477
| 3.000000000000000 3.666666666666667 2.047619047619048 329737645.750000000000000 53.700000000000000 | 3 seconds | 256 megabytes | ['binary search', 'dp', 'implementation', 'math', 'two pointers', '*1500'] |
B. Arrays Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a non-decreasing array of non-negative integers a_1, a_2, \ldots, a_n. Also you are given a positive integer k.You want to find m non-decreasing arrays of non-negative integers b_1, b_2, \ldots, b_m, such that: The size of b_i is equal to n for all 1 \leq i \leq m. For all 1 \leq j \leq n, a_j = b_{1, j} + b_{2, j} + \ldots + b_{m, j}. In the other word, array a is the sum of arrays b_i. The number of different elements in the array b_i is at most k for all 1 \leq i \leq m. Find the minimum possible value of m, or report that there is no possible m.InputThe first line contains one integer t (1 \leq t \leq 100): the number of test cases.The first line of each test case contains two integers n, k (1 \leq n \leq 100, 1 \leq k \leq n).The second line contains n integers a_1, a_2, \ldots, a_n (0 \leq a_1 \leq a_2 \leq \ldots \leq a_n \leq 100, a_n > 0).OutputFor each test case print a single integer: the minimum possible value of m. If there is no such m, print -1.ExampleInput
6
4 1
0 0 0 1
3 1
3 3 3
11 3
0 1 2 2 3 3 3 4 4 4 4
5 3
1 2 3 4 5
9 4
2 2 3 5 7 11 13 13 17
10 7
0 1 1 2 3 3 4 5 5 6
Output
-1
1
2
2
2
1
NoteIn the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros.In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m.In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. | 6
4 1
0 0 0 1
3 1
3 3 3
11 3
0 1 2 2 3 3 3 4 4 4 4
5 3
1 2 3 4 5
9 4
2 2 3 5 7 11 13 13 17
10 7
0 1 1 2 3 3 4 5 5 6
| -1 1 2 2 2 1 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*1400'] |
A. Circle Coloringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three sequences: a_1, a_2, \ldots, a_n; b_1, b_2, \ldots, b_n; c_1, c_2, \ldots, c_n.For each i, a_i \neq b_i, a_i \neq c_i, b_i \neq c_i.Find a sequence p_1, p_2, \ldots, p_n, that satisfy the following conditions: p_i \in \{a_i, b_i, c_i\} p_i \neq p_{(i \mod n) + 1}.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements i,i+1 adjacent for i<n and also elements 1 and n) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.InputThe first line of input contains one integer t (1 \leq t \leq 100): the number of test cases.The first line of each test case contains one integer n (3 \leq n \leq 100): the number of elements in the given sequences.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 100).The third line contains n integers b_1, b_2, \ldots, b_n (1 \leq b_i \leq 100).The fourth line contains n integers c_1, c_2, \ldots, c_n (1 \leq c_i \leq 100).It is guaranteed that a_i \neq b_i, a_i \neq c_i, b_i \neq c_i for all i.OutputFor each test case, print n integers: p_1, p_2, \ldots, p_n (p_i \in \{a_i, b_i, c_i\}, p_i \neq p_{i \mod n + 1}).If there are several solutions, you can print any.ExampleInput
5
3
1 1 1
2 2 2
3 3 3
4
1 2 1 2
2 1 2 1
3 4 3 4
7
1 3 3 1 1 1 1
2 4 4 3 2 2 4
4 2 2 2 4 4 2
3
1 2 1
2 3 3
3 1 2
10
1 1 1 2 2 2 3 3 3 1
2 2 2 3 3 3 1 1 1 2
3 3 3 1 1 1 2 2 2 3
Output
1 2 3
1 2 1 2
1 3 4 3 2 4 2
1 3 2
1 2 3 1 2 3 1 2 3 2
NoteIn the first test case p = [1, 2, 3].It is a correct answer, because: p_1 = 1 = a_1, p_2 = 2 = b_2, p_3 = 3 = c_3 p_1 \neq p_2 , p_2 \neq p_3 , p_3 \neq p_1 All possible correct answers to this test case are: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1].In the second test case p = [1, 2, 1, 2].In this sequence p_1 = a_1, p_2 = a_2, p_3 = a_3, p_4 = a_4. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case p = [1, 3, 4, 3, 2, 4, 2].In this sequence p_1 = a_1, p_2 = a_2, p_3 = b_3, p_4 = b_4, p_5 = b_5, p_6 = c_6, p_7 = c_7. Also we can see, that no two adjacent elements of the sequence are equal. | 5
3
1 1 1
2 2 2
3 3 3
4
1 2 1 2
2 1 2 1
3 4 3 4
7
1 3 3 1 1 1 1
2 4 4 3 2 2 4
4 2 2 2 4 4 2
3
1 2 1
2 3 3
3 1 2
10
1 1 1 2 2 2 3 3 3 1
2 2 2 3 3 3 1 1 1 2
3 3 3 1 1 1 2 2 2 3
| 1 2 3 1 2 1 2 1 3 4 3 2 4 2 1 3 2 1 2 3 1 2 3 1 2 3 2 | 1 second | 256 megabytes | ['constructive algorithms', '*800'] |
E. Egor in the Republic of Dagestantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEgor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan.There are n cities in the republic, some of them are connected by m directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary directed graph. Egor will arrive to the city 1, travel to the city n by roads along some path, give a concert and fly away.As any famous artist, Egor has lots of haters and too annoying fans, so he can travel only by safe roads. There are two types of the roads in Dagestan, black and white: black roads are safe at night only, and white roads — in the morning. Before the trip Egor's manager's going to make a schedule: for each city he'll specify it's color, black or white, and then if during the trip they visit some city, the only time they can leave it is determined by the city's color: night, if it's black, and morning, if it's white. After creating the schedule Egor chooses an available path from 1 to n, and for security reasons it has to be the shortest possible.Egor's manager likes Dagestan very much and wants to stay here as long as possible, so he asks you to make such schedule that there would be no path from 1 to n or the shortest path's length would be greatest possible.A path is one city or a sequence of roads such that for every road (excluding the first one) the city this road goes from is equal to the city previous road goes into. Egor can move only along paths consisting of safe roads only. The path length is equal to the number of roads in it. The shortest path in a graph is a path with smallest length.InputThe first line contains two integers n, m (1 \leq n \leq 500000, 0 \leq m \leq 500000) — the number of cities and the number of roads.The i-th of next m lines contains three integers — u_i, v_i and t_i (1 \leq u_i, v_i \leq n, t_i \in \{0, 1\}) — numbers of cities connected by road and its type, respectively (0 — night road, 1 — morning road).OutputIn the first line output the length of the desired path (or -1, if it's possible to choose such schedule that there's no path from 1 to n).In the second line output the desired schedule — a string of n digits, where i-th digit is 0, if the i-th city is a night one, and 1 if it's a morning one.If there are multiple answers, print any.ExamplesInput
3 4
1 2 0
1 3 1
2 3 0
2 3 1
Output
2
011Input
4 8
1 1 0
1 3 0
1 3 1
3 2 0
2 1 0
3 4 1
2 4 0
2 4 1
Output
3
1101Input
5 10
1 2 0
1 3 1
1 4 0
2 3 0
2 3 1
2 5 0
3 4 0
3 4 1
4 2 1
4 5 0
Output
-1
11111NoteFor the first sample, if we paint city 1 white, the shortest path is 1 \rightarrow 3. Otherwise, it's 1 \rightarrow 2 \rightarrow 3 regardless of other cities' colors.For the second sample, we should paint city 3 black, and there are both black and white roads going from 2 to 4. Note that there can be a road connecting a city with itself. | 3 4
1 2 0
1 3 1
2 3 0
2 3 1
| 2 011 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'dp', 'graphs', 'greedy', 'shortest paths', '*2500'] |
D. Discrete Centrifugal Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n beautiful skyscrapers in New York, the height of the i-th one is h_i. Today some villains have set on fire first n - 1 of them, and now the only safety building is n-th skyscraper.Let's call a jump from i-th skyscraper to j-th (i < j) discrete, if all skyscrapers between are strictly lower or higher than both of them. Formally, jump is discrete, if i < j and one of the following conditions satisfied: i + 1 = j \max(h_{i + 1}, \ldots, h_{j - 1}) < \min(h_i, h_j) \max(h_i, h_j) < \min(h_{i + 1}, \ldots, h_{j - 1}). At the moment, Vasya is staying on the first skyscraper and wants to live a little longer, so his goal is to reach n-th skyscraper with minimal count of discrete jumps. Help him with calcualting this number.InputThe first line contains a single integer n (2 \le n \le 3 \cdot 10^5) — total amount of skyscrapers.The second line contains n integers h_1, h_2, \ldots, h_n (1 \le h_i \le 10^9) — heights of skyscrapers.OutputPrint single number k — minimal amount of discrete jumps. We can show that an answer always exists.ExamplesInput
5
1 3 1 4 5
Output
3Input
4
4 2 2 4
Output
1Input
2
1 1
Output
1Input
5
100 1 100 1 100
Output
2NoteIn the first testcase, Vasya can jump in the following way: 1 \rightarrow 2 \rightarrow 4 \rightarrow 5.In the second and third testcases, we can reach last skyscraper in one jump.Sequence of jumps in the fourth testcase: 1 \rightarrow 3 \rightarrow 5. | 5
1 3 1 4 5
| 3 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'graphs', '*2200'] |
C. Chocolate Bunnytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.We hid from you a permutation p of length n, consisting of the elements from 1 to n. You want to guess it. To do that, you can give us 2 different indices i and j, and we will reply with p_{i} \bmod p_{j} (remainder of division p_{i} by p_{j}).We have enough patience to answer at most 2 \cdot n queries, so you should fit in this constraint. Can you do it?As a reminder, a permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).InputThe only line of the input contains a single integer n (1 \le n \le 10^4) — length of the permutation.InteractionThe interaction starts with reading n. Then you are allowed to make at most 2 \cdot n queries in the following way: "? x y" (1 \le x, y \le n, x \ne y). After each one, you should read an integer k, that equals p_x \bmod p_y. When you have guessed the permutation, print a single line "! " (without quotes), followed by array p and quit.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.Exit immediately after receiving "-1" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.Hack formatIn the first line output n (1 \le n \le 10^4). In the second line print the permutation of n integers p_1, p_2, \ldots, p_n.ExampleInput
3
1
2
1
0Output
? 1 2
? 3 2
? 1 3
? 2 1
! 1 3 2 | 3
1
2
1
0 | ? 1 2 ? 3 2 ? 1 3 ? 2 1 ! 1 3 2 | 1 second | 256 megabytes | ['constructive algorithms', 'interactive', 'math', 'two pointers', '*1600'] |
B. Big Vovatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years.You're given n positive integers a_1, a_2, \dots, a_n. Using each of them exactly at once, you're to make such sequence b_1, b_2, \dots, b_n that sequence c_1, c_2, \dots, c_n is lexicographically maximal, where c_i=GCD(b_1,\dots,b_i) - the greatest common divisor of the first i elements of b. Alexander is really afraid of the conditions of this simple task, so he asks you to solve it.A sequence a is lexicographically smaller than a sequence b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the sequence a has a smaller element than the corresponding element in b.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^3). Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^3) — the length of the sequence a.The second line of each test case contains n integers a_1,\dots,a_n (1 \le a_i \le 10^3) — the sequence a.It is guaranteed that the sum of n over all test cases does not exceed 10^3.OutputFor each test case output the answer in a single line — the desired sequence b. If there are multiple answers, print any.ExampleInput
7
2
2 5
4
1 8 2 3
3
3 8 9
5
64 25 75 100 50
1
42
6
96 128 88 80 52 7
5
2 4 8 16 17
Output
5 2
8 2 1 3
9 3 8
100 50 25 75 64
42
128 96 80 88 52 7
17 2 4 8 16
NoteIn the first test case of the example, there are only two possible permutations b — [2, 5] and [5, 2]: for the first one c=[2, 1], for the second one c=[5, 1].In the third test case of the example, number 9 should be the first in b, and GCD(9, 3)=3, GCD(9, 8)=1, so the second number of b should be 3.In the seventh test case of the example, first four numbers pairwise have a common divisor (a power of two), but none of them can be the first in the optimal permutation b. | 7
2
2 5
4
1 8 2 3
3
3 8 9
5
64 25 75 100 50
1
42
6
96 128 88 80 52 7
5
2 4 8 16 17
| 5 2 8 2 1 3 9 3 8 100 50 25 75 64 42 128 96 80 88 52 7 17 2 4 8 16 | 1 second | 256 megabytes | ['brute force', 'greedy', 'math', 'number theory', '*1300'] |
A. Ahahahahahahahahatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlexandra has an even-length array a, consisting of 0s and 1s. The elements of the array are enumerated from 1 to n. She wants to remove at most \frac{n}{2} elements (where n — length of array) in the way that alternating sum of the array will be equal 0 (i.e. a_1 - a_2 + a_3 - a_4 + \dotsc = 0). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has a = [1, 0, 1, 0, 0, 0] and she removes 2nd and 4th elements, a will become equal [1, 1, 0, 0] and its alternating sum is 1 - 1 + 0 - 0 = 0.Help her!InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^3). Description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 10^3, n is even) — length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 1) — elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 10^3.OutputFor each test case, firstly, print k (\frac{n}{2} \leq k \leq n) — number of elements that will remain after removing in the order they appear in a. Then, print this k numbers. Note that you should print the numbers themselves, not their indices.We can show that an answer always exists. If there are several answers, you can output any of them. ExampleInput
4
2
1 0
2
0 0
4
0 1 1 1
4
1 1 0 0
Output
1
0
1
0
2
1 1
4
1 1 0 0
NoteIn the first and second cases, alternating sum of the array, obviously, equals 0.In the third case, alternating sum of the array equals 1 - 1 = 0.In the fourth case, alternating sum already equals 1 - 1 + 0 - 0 = 0, so we don't have to remove anything. | 4
2
1 0
2
0 0
4
0 1 1 1
4
1 1 0 0
| 1 0 1 0 2 1 1 4 1 1 0 0 | 1 second | 256 megabytes | ['constructive algorithms', 'math', '*1100'] |
E. Deleting Numberstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.There is an unknown integer x (1\le x\le n). You want to find x.At first, you have a set of integers \{1, 2, \ldots, n\}. You can perform the following operations no more than 10000 times: A a: find how many numbers are multiples of a in the current set. B a: find how many numbers are multiples of a in this set, and then delete all multiples of a, but x will never be deleted (even if it is a multiple of a). In this operation, a must be greater than 1. C a: it means that you know that x=a. This operation can be only performed once. Remember that in the operation of type B a>1 must hold.Write a program, that will find the value of x.InputThe first line contains one integer n (1\le n\le 10^5). The remaining parts of the input will be given throughout the interaction process.InteractionIn each round, your program needs to print a line containing one uppercase letter A, B or C and an integer a (1\le a\le n for operations A and C, 2\le a\le n for operation B). This line desribes operation you make.If your operation has type C your program should terminate immediately.Else your program should read one line containing a single integer, which is the answer to your operation.After outputting each line, don't forget to flush the output. To do it use: fflush(stdout) in C/C++; System.out.flush() in Java; sys.stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages. It is guaranteed, that the number x is fixed and won't change during the interaction process.Hacks:To make a hack, use such input format:The only line should contain two integers n, x (1 \leq x \leq n \leq 10^5).ExampleInput
10
2
4
0Output
B 4
A 2
A 8
C 4
NoteNote that to make the sample more clear, we added extra empty lines. You shouldn't print any extra empty lines during the interaction process.In the first test n=10 and x=4.Initially the set is: \{1,2,3,4,5,6,7,8,9,10\}.In the first operation, you ask how many numbers are multiples of 4 and delete them. The answer is 2 because there are two numbers divisible by 4: \{4,8\}. 8 will be deleted but 4 won't, because the number x will never be deleted. Now the set is \{1,2,3,4,5,6,7,9,10\}.In the second operation, you ask how many numbers are multiples of 2. The answer is 4 because there are four numbers divisible by 2: \{2,4,6,10\}.In the third operation, you ask how many numbers are multiples of 8. The answer is 0 because there isn't any number divisible by 8 in the current set.In the fourth operation, you know that x=4, which is the right answer. | 10
2
4
0 | B 4 A 2 A 8 C 4 | 1 second | 512 megabytes | ['interactive', 'math', 'number theory', '*2600'] |
D. Three Sequencestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a sequence of n integers a_1, a_2, \ldots, a_n.You have to construct two sequences of integers b and c with length n that satisfy: for every i (1\leq i\leq n) b_i+c_i=a_i b is non-decreasing, which means that for every 1<i\leq n, b_i\geq b_{i-1} must hold c is non-increasing, which means that for every 1<i\leq n, c_i\leq c_{i-1} must hold You have to minimize \max(b_i,c_i). In other words, you have to minimize the maximum number in sequences b and c.Also there will be q changes, the i-th change is described by three integers l,r,x. You should add x to a_l,a_{l+1}, \ldots, a_r. You have to find the minimum possible value of \max(b_i,c_i) for the initial sequence and for sequence after each change.InputThe first line contains an integer n (1\leq n\leq 10^5).The secound line contains n integers a_1,a_2,\ldots,a_n (1\leq i\leq n, -10^9\leq a_i\leq 10^9).The third line contains an integer q (1\leq q\leq 10^5).Each of the next q lines contains three integers l,r,x (1\leq l\leq r\leq n,-10^9\leq x\leq 10^9), desribing the next change. OutputPrint q+1 lines.On the i-th (1 \leq i \leq q+1) line, print the answer to the problem for the sequence after i-1 changes.ExamplesInput
4
2 -1 7 3
2
2 4 -3
3 4 2
Output
5
5
6
Input
6
-9 -10 -9 -6 -5 4
3
2 6 -9
1 2 -10
4 6 -3
Output
3
3
3
1
Input
1
0
2
1 1 -1
1 1 -1
Output
0
0
-1
NoteIn the first test: The initial sequence a = (2, -1, 7, 3). Two sequences b=(-3,-3,5,5),c=(5,2,2,-2) is a possible choice. After the first change a = (2, -4, 4, 0). Two sequences b=(-3,-3,5,5),c=(5,-1,-1,-5) is a possible choice. After the second change a = (2, -4, 6, 2). Two sequences b=(-4,-4,6,6),c=(6,0,0,-4) is a possible choice. | 4
2 -1 7 3
2
2 4 -3
3 4 2
| 5 5 6 | 2 seconds | 512 megabytes | ['constructive algorithms', 'data structures', 'greedy', 'math', '*2200'] |
C. Link Cut Centroidstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputFishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles.A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible.For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. However, in some trees, there might be more than one centroid, for example: Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them.Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut.He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists.InputThe input consists of multiple test cases. The first line contains an integer t (1\leq t\leq 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (3\leq n\leq 10^5) — the number of vertices.Each of the next n-1 lines contains two integers x, y (1\leq x,y\leq n). It means, that there exists an edge connecting vertices x and y.It's guaranteed that the given graph is a tree.It's guaranteed that the sum of n for all test cases does not exceed 10^5.OutputFor each test case, print two lines.In the first line print two integers x_1, y_1 (1 \leq x_1, y_1 \leq n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1.In the second line print two integers x_2, y_2 (1 \leq x_2, y_2 \leq n), which means you add the edge between vertices x_2 and y_2.The graph after these two operations should be a tree.If there are multiple solutions you can print any.ExampleInput
2
5
1 2
1 3
2 4
2 5
6
1 2
1 3
1 4
2 5
2 6
Output
1 2
1 2
1 3
2 3NoteNote that you can add the same edge that you cut.In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid.In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3. | 2
5
1 2
1 3
2 4
2 5
6
1 2
1 3
1 4
2 5
2 6
| 1 2 1 2 1 3 2 3 | 1 second | 512 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', 'trees', '*1700'] |
B. Maximum Producttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array of integers a_1,a_2,\ldots,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t).InputThe input consists of multiple test cases. The first line contains an integer t (1\le t\le 2 \cdot 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (5\le n\le 10^5) — the size of the array.The second line of each test case contains n integers a_1,a_2,\ldots,a_n (-3\times 10^3\le a_i\le 3\times 10^3) — given array.It's guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, print one integer — the answer to the problem.ExampleInput
4
5
-1 -2 -3 -4 -5
6
-1 -2 -3 1 2 -1
6
-1 0 0 0 -1 -1
6
-9 -7 -5 -3 -2 1
Output
-120
12
0
945
NoteIn the first test case, choosing a_1,a_2,a_3,a_4,a_5 is a best choice: (-1)\cdot (-2) \cdot (-3)\cdot (-4)\cdot (-5)=-120.In the second test case, choosing a_1,a_2,a_3,a_5,a_6 is a best choice: (-1)\cdot (-2) \cdot (-3)\cdot 2\cdot (-1)=12.In the third test case, choosing a_1,a_2,a_3,a_4,a_5 is a best choice: (-1)\cdot 0\cdot 0\cdot 0\cdot (-1)=0.In the fourth test case, choosing a_1,a_2,a_3,a_4,a_6 is a best choice: (-9)\cdot (-7) \cdot (-5)\cdot (-3)\cdot 1=945. | 4
5
-1 -2 -3 -4 -5
6
-1 -2 -3 1 2 -1
6
-1 0 0 0 -1 -1
6
-9 -7 -5 -3 -2 1
| -120 12 0 945 | 2 seconds | 512 megabytes | ['brute force', 'dp', 'greedy', 'implementation', 'sortings', '*1200'] |
A. Subset Mextime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputGiven a set of integers (it can contain equal elements).You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B).Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example: mex(\{1,4,0,2,2,1\})=3 mex(\{3,3,2,1,3,0,0\})=4 mex(\varnothing)=0 (mex for empty set) The set is splitted into two subsets A and B if for any integer number x the number of occurrences of x into this set is equal to the sum of the number of occurrences of x into A and the number of occurrences of x into B.InputThe input consists of multiple test cases. The first line contains an integer t (1\leq t\leq 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (1\leq n\leq 100) — the size of the set.The second line of each testcase contains n integers a_1,a_2,\dots a_n (0\leq a_i\leq 100) — the numbers in the set.OutputFor each test case, print the maximum value of mex(A)+mex(B).ExampleInput
4
6
0 2 1 5 0 1
3
0 1 2
4
0 2 0 1
6
1 2 3 4 5 6
Output
5
3
4
0
NoteIn the first test case, A=\left\{0,1,2\right\},B=\left\{0,1,5\right\} is a possible choice.In the second test case, A=\left\{0,1,2\right\},B=\varnothing is a possible choice.In the third test case, A=\left\{0,1,2\right\},B=\left\{0\right\} is a possible choice.In the fourth test case, A=\left\{1,3,5\right\},B=\left\{2,4,6\right\} is a possible choice. | 4
6
0 2 1 5 0 1
3
0 1 2
4
0 2 0 1
6
1 2 3 4 5 6
| 5 3 4 0 | 1 second | 512 megabytes | ['greedy', 'implementation', 'math', '*900'] |
B. Array Cancellationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a of n integers, such that a_1 + a_2 + \cdots + a_n = 0.In one operation, you can choose two different indices i and j (1 \le i, j \le n), decrement a_i by one and increment a_j by one. If i < j this operation is free, otherwise it costs one coin.How many coins do you have to spend in order to make all elements equal to 0?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 5000). Description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 10^5) — the number of elements.The next line contains n integers a_1, \ldots, a_n (-10^9 \le a_i \le 10^9). It is given that \sum_{i=1}^n a_i = 0.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print the minimum number of coins we have to spend in order to make all elements equal to 0.ExampleInput
7
4
-3 5 -3 1
2
1 -1
4
-3 2 -3 4
4
-1 1 1 -1
7
-5 7 -6 -4 17 -13 4
6
-1000000000 -1000000000 -1000000000 1000000000 1000000000 1000000000
1
0
Output
3
0
4
1
8
3000000000
0
NotePossible strategy for the first test case: Do (i=2, j=3) three times (free), a = [-3, 2, 0, 1]. Do (i=2, j=1) two times (pay two coins), a = [-1, 0, 0, 1]. Do (i=4, j=1) one time (pay one coin), a = [0, 0, 0, 0]. | 7
4
-3 5 -3 1
2
1 -1
4
-3 2 -3 4
4
-1 1 1 -1
7
-5 7 -6 -4 17 -13 4
6
-1000000000 -1000000000 -1000000000 1000000000 1000000000 1000000000
1
0
| 3 0 4 1 8 3000000000 0 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*1000'] |
A. Permutation Forgerytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA 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).Let p be any permutation of length n. We define the fingerprint F(p) of p as the sorted array of sums of adjacent elements in p. More formally,F(p)=\mathrm{sort}([p_1+p_2,p_2+p_3,\ldots,p_{n-1}+p_n]).For example, if n=4 and p=[1,4,2,3], then the fingerprint is given by F(p)=\mathrm{sort}([1+4,4+2,2+3])=\mathrm{sort}([5,6,5])=[5,5,6].You are given a permutation p of length n. Your task is to find a different permutation p' with the same fingerprint. Two permutations p and p' are considered different if there is some index i such that p_i \ne p'_i.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 668). Description of the test cases follows.The first line of each test case contains a single integer n (2\le n\le 100) — the length of the permutation.The second line of each test case contains n integers p_1,\ldots,p_n (1\le p_i\le n). It is guaranteed that p is a permutation.OutputFor each test case, output n integers p'_1,\ldots, p'_n — a permutation such that p'\ne p and F(p')=F(p).We can prove that for every permutation satisfying the input constraints, a solution exists.If there are multiple solutions, you may output any.ExampleInput
3
2
1 2
6
2 1 6 5 4 3
5
2 4 3 1 5
Output
2 1
1 2 5 6 3 4
3 1 5 2 4
NoteIn the first test case, F(p)=\mathrm{sort}([1+2])=[3].And F(p')=\mathrm{sort}([2+1])=[3].In the second test case, F(p)=\mathrm{sort}([2+1,1+6,6+5,5+4,4+3])=\mathrm{sort}([3,7,11,9,7])=[3,7,7,9,11].And F(p')=\mathrm{sort}([1+2,2+5,5+6,6+3,3+4])=\mathrm{sort}([3,7,11,9,7])=[3,7,7,9,11].In the third test case, F(p)=\mathrm{sort}([2+4,4+3,3+1,1+5])=\mathrm{sort}([6,7,4,6])=[4,6,6,7].And F(p')=\mathrm{sort}([3+1,1+5,5+2,2+4])=\mathrm{sort}([4,6,7,6])=[4,6,6,7]. | 3
2
1 2
6
2 1 6 5 4 3
5
2 4 3 1 5
| 2 1 1 2 5 6 3 4 3 1 5 2 4 | 1 second | 256 megabytes | ['constructive algorithms', '*800'] |
E. Brickstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA brick is defined as a rectangle with integer side lengths with either width 1 or height 1 (or both).There is an n\times m grid, and each cell is colored either black or white. A tiling is a way to place bricks onto the grid such that each black cell is covered by exactly one brick, and each white cell is not covered by any brick. In other words, bricks are placed on black cells only, cover all black cells, and no two bricks overlap. An example tiling of the first test case using 5 bricks. It is possible to do better, using only 4 bricks. What is the minimum number of bricks required to make a valid tiling?InputThe first line contains two integers n, m (1\le n, m\le 200) — the number of rows and columns, respectively.The next n lines describe the grid. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i, column j. A black cell is given by "#", and a white cell is given by ".".It is guaranteed that there is at least one black cell.OutputOutput a single integer, the minimum number of bricks required.ExamplesInput
3 4
#.##
####
##..
Output
4
Input
6 6
######
##....
######
##...#
##...#
######
Output
6
Input
10 8
####..##
#..#.##.
#..#.###
####.#.#
....####
.###.###
###.#..#
########
###..###
.##.###.
Output
18
NoteThe first test case can be tiled with 4 bricks placed vertically.The third test case can be tiled with 18 bricks like this: | 3 4
#.##
####
##..
| 4 | 4 seconds | 256 megabytes | ['flows', 'graph matchings', 'graphs', '*2800'] |
D. Game of Pairstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Consider a fixed positive integer n. Two players, First and Second play a game as follows: First considers the 2n numbers 1, 2, \dots, 2n, and partitions them as he wants into n disjoint pairs. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants). To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of 2n, then Second wins. Otherwise, First wins.You are given the integer n. Your task is to decide which player you wish to play as and win the game.InteractionThe interaction begins by reading the integer n (1 \le n \le 5 \cdot 10^5).After reading, print a single line containing either First or Second, denoting who you want to play as. The interaction then varies depending on who you chose to play as.If you chose to play as First, print a single line containing 2n integers p_1, p_2, \dots, p_{2n}, denoting that the number i belongs to the p_i-th pair for 1\le i \le 2n. Thus, 1 \le p_i \le n, and every number between 1 and n inclusive should appear exactly twice.If you chose to play as Second, the interactor will print 2n integers p_1, p_2, \dots, p_{2n}, denoting that the number i belongs to the p_i-th pair. As a response, print n integers a_1, a_2, \dots, a_n in a single line. These should contain exactly one number from each pair.Regardless of who you chose to play as the interactor will finish by printing a single integer: 0 if your answer for the test case is correct (that is, you are playing as First and it cannot choose adequate numbers from your pairs, or you are playing as Second and your chosen numbers add up to a multiple of 2n), or -1 if it is incorrect. In particular, the interactor will not print the chosen numbers if you choose to play First and lose. In either case, your program should terminate immediately after reading this number.If at any point you make an invalid interaction, the interactor will print -1 and finish the interaction. You will receive a Wrong Answer verdict. Make sure to terminate immediately to avoid getting other verdicts.After printing something 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. Hack FormatTo hack, use the following format:The first line contains an integer n (1 \le n \le 5 \cdot 10^5).The second line contains 2n integers p_1, p_2, \dots, p_{2n}, denoting that the number i belongs to the p_i-th pair if the solution being hacked chooses to play as Second. If the solution being hacked chooses to play as First, those pairs don't matter but the p_1, p_2, \dots, p_{2n} must still form a valid partition of 1, 2, \dots, 2n into n disjoint pairs.ExamplesInput
2
1 1 2 2
0
Output
Second
1 3
Input
2
0Output
First
2 1 2 1
NoteIn the first sample, n = 2, and you decide to play as Second. The judge chooses the pairs (1, 2) and (3, 4), and you reply with the numbers 1 and 3. This is a valid choice since it contains exactly one number from each pair, and the sum 1 + 3 = 4 is divisible by 4.In the second sample, n = 2 again, and you play as First. You choose the pairs (2, 4) and (1, 3). The judge fails to choose a number from each pair such that their sum is divisible by 4, so the answer is correct.Note that the sample tests are just for illustration of the interaction protocol, and don't necessarily correspond to the behavior of the real interactor. | 2
1 1 2 2
0
| Second 1 3 | 4 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'interactive', 'math', 'number theory', '*2800'] |
C. Fixed Point Removaltime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet a_1, \ldots, a_n be an array of n positive integers. In one operation, you can choose an index i such that a_i = i, and remove a_i from the array (after the removal, the remaining parts are concatenated).The weight of a is defined as the maximum number of elements you can remove.You must answer q independent queries (x, y): after replacing the x first elements of a and the y last elements of a by n+1 (making them impossible to remove), what would be the weight of a?InputThe first line contains two integers n and q (1 \le n, q \le 3 \cdot 10^5) — the length of the array and the number of queries.The second line contains n integers a_1, a_2, ..., a_n (1 \leq a_i \leq n) — elements of the array.The i-th of the next q lines contains two integers x and y (x, y \ge 0 and x+y < n).OutputPrint q lines, i-th line should contain a single integer — the answer to the i-th query.ExamplesInput
13 5
2 2 3 9 5 4 6 5 7 8 3 11 13
3 1
0 0
2 4
5 0
0 12
Output
5
11
6
1
0
Input
5 2
1 4 1 2 4
0 0
1 0
Output
2
0
NoteExplanation of the first query:After making first x = 3 and last y = 1 elements impossible to remove, a becomes [\times, \times, \times, 9, 5, 4, 6, 5, 7, 8, 3, 11, \times] (we represent 14 as \times for clarity).Here is a strategy that removes 5 elements (the element removed is colored in red): [\times, \times, \times, 9, \color{red}{5}, 4, 6, 5, 7, 8, 3, 11, \times] [\times, \times, \times, 9, 4, 6, 5, 7, 8, 3, \color{red}{11}, \times] [\times, \times, \times, 9, 4, \color{red}{6}, 5, 7, 8, 3, \times] [\times, \times, \times, 9, 4, 5, 7, \color{red}{8}, 3, \times] [\times, \times, \times, 9, 4, 5, \color{red}{7}, 3, \times] [\times, \times, \times, 9, 4, 5, 3, \times] (final state) It is impossible to remove more than 5 elements, hence the weight is 5. | 13 5
2 2 3 9 5 4 6 5 7 8 3 11 13
3 1
0 0
2 4
5 0
0 12
| 5 11 6 1 0 | 4 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'data structures', 'greedy', 'two pointers', '*2300'] |
B. Tree Tagtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a fun game of tree tag.The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.Determine the winner if both players play optimally.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). Description of the test cases follows.The first line of each test case contains five integers n,a,b,da,db (2\le n\le 10^5, 1\le a,b\le n, a\ne b, 1\le da,db\le n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1\le u, v\le n, u\ne v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.It is guaranteed that the sum of n across all test cases does not exceed 10^5.OutputFor each test case, output a single line containing the winner of the game: "Alice" or "Bob".ExampleInput
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
NoteIn the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. | 4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
| Alice Bob Alice Alice | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'games', 'trees', '*1900'] |
A. Balanced Bitstringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (\frac{k}{2} of each).You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). Description of the test cases follows.The first line of each test case contains two integers n and k (2 \le k \le n \le 3 \cdot 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.ExampleInput
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
NoteFor the first test case, the string is already a 4-balanced bitstring.For the second test case, the string can be transformed into 101.For the fourth test case, the string can be transformed into 0110.For the fifth test case, the string can be transformed into 1100110. | 9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
| YES YES NO YES YES NO NO YES NO | 2 seconds | 256 megabytes | ['implementation', 'strings', '*1500'] |
C. Chess Rushtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe mythic world of Chess Land is a rectangular grid of squares with R rows and C columns, R being greater than or equal to C. Its rows and columns are numbered from 1 to R and 1 to C, respectively. The inhabitants of Chess Land are usually mentioned as pieces in everyday language, and there are 5 specific types of them roaming the land: pawns, rooks, bishops, queens and kings. Contrary to popular belief, chivalry is long dead in Chess Land, so there are no knights to be found.Each piece is unique in the way it moves around from square to square: in one step, a pawn can move one row forward (i.e. from row r to r+1), without changing columns; a rook can move any number of columns left/right without changing rows OR move any number of rows forward/backward without changing columns; a bishop can move to any square of the two diagonals intersecting at its currently occupied square; a queen can move to any square where a rook or a bishop could move to from her position; and a king can move to any of the 8 adjacent squares. In the following figure, we marked by X the squares each piece can move to in a single step (here, the rows are numbered from bottom to top, and the columns from left to right). Recently, Chess Land has become a dangerous place: pieces that are passing through the land can get captured unexpectedly by unknown forces and simply disappear. As a consequence, they would like to reach their destinations as fast (i.e. in as few moves) as possible, and they are also interested in the number of different ways it is possible for them to reach it, using the minimal number of steps – because more paths being available could mean lower chances of getting captured. Two paths are considered different if they differ in at least one visited square.For this problem, let us assume that pieces are entering Chess Land in a given column of row 1, and exit the land in a given column of row R. Your task is to answer Q questions: given the type of a piece, the column it enters row 1 and the column it must reach in row R in order to exit, compute the minimal number of moves it has to make in Chess Land, and the number of different ways it is able to do so.InputThe first line contains three space-separated integers R, C, and Q (1 \leq Q \leq 1000, 2 \leq C \leq 1000 and C \leq R \leq 10^9) – the number of rows and columns of Chess Land, and the number of questions, respectively. Then Q lines follow.Each line consists of a character T, corresponding to the type of the piece in question ('P' for pawn, 'R' for rook, 'B' for bishop, 'Q' for queen and 'K' for king); two integers c_1 and c_R, 1\leq c_1,c_R\leq C, denoting that the piece starts from the c_1-th column of row 1, and has to reach the c_R-th column of row R. OutputYou have to print Q lines, the i-th one containing two space separated integers, the answer to the i-th question: the first one is the minimal number of steps needed, the second is the number of different paths available using this number of steps. Since the answer can be quite large, you have to compute it modulo 10^9+7.If it is impossible to reach the target square, output the line "0 0".Scoring \begin{array}{|c|c|l|} \hline \text{Subtask} & \text{Points} & \text{Constraints} \\ \hline 1 & 0 & \text{samples}\\ \hline 2 & 8 & T\in\{\text{'P','R','Q'}\}\text{, i.e. all pieces are pawns, rooks or queens} \\ \hline 3 & 15 & T=\text{'B' and } \: C,R\leq 100 \\ \hline 4 & 22 & T=\text{'B'} \\ \hline 5 & 5 & T=\text{'K' and }\:C,R\leq 100\:\text{and}\:Q\leq 50 \\ \hline 6 & 8 & T=\text{'K' and }\:C,R\leq 100\\ \hline 7 & 15 & T=\text{'K' and }\:C\leq 100\\ \hline 8 & 20 & T=\text{'K'}\\ \hline 9 & 7 & \text{no additional constraints}\\ \hline \end{array} ExampleInput
8 8 5
P 1 2
R 4 8
Q 2 3
B 3 6
K 5 5
Output
0 0
2 2
2 5
2 2
7 393
NoteYou can download the above example and an additional (bigger) sample input here: https://gofile.io/d/GDzwfC | 8 8 5
P 1 2
R 4 8
Q 2 3
B 3 6
K 5 5
| 0 0 2 2 2 5 2 2 7 393 | 1.5 seconds | 256 megabytes | ['*special problem', 'combinatorics', 'dp', 'implementation', 'math', '*3200'] |
B. Spring cleaningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSpring cleanings are probably the most boring parts of our lives, except this year, when Flóra and her mother found a dusty old tree graph under the carpet.This tree has N nodes (numbered from 1 to N), connected by N-1 edges. The edges gathered too much dust, so Flóra's mom decided to clean them. Cleaning the edges of an arbitrary tree is done by repeating the following process: She chooses 2 different leaves (a node is a leaf if it is connected to exactly one other node by an edge), and cleans every edge lying on the shortest path between them. If this path has d edges, then the cost of cleaning this path is d.She doesn't want to harm the leaves of the tree, so she chooses every one of them at most once. A tree is cleaned when all of its edges are cleaned. The cost of this is the sum of costs for all cleaned paths.Flóra thinks the tree they found is too small and simple, so she imagines Q variations of it. In the i-th variation, she adds a total of D_i extra leaves to the original tree: for each new leaf, she chooses a node from the original tree, and connects that node with the new leaf by an edge. Note that some nodes may stop being leaves during this step.For all these Q variations, we are interested in the minimum cost that is required to clean the tree.InputThe first line contains two space-separated integer, N and Q (3 \leq N \leq 10^{5}, 1 \leq Q \leq 10^{5}) – the number of nodes the tree has and the number of variations. Each of the next N-1 lines contains two space-separated integers u and v denoting that nodes u and v are connected by an edge (1 \leq u, v \leq N). The next Q lines describe the variations. The first integer in the ith line is D_i (1 \leq D_i \leq 10^{5}). Then D_i space-separated integers follow: if the jth number is a_j, it means that Flóra adds a new leaf to node a_j (1 \leq a_j \leq N). We may add more than one leaf to the same node. \sum_{1}^{Q} D_i \leq 10^{5} i.e. the sum of D_i in all varations is at most 10^5.After each variation, Flóra restarts and adds extra leaves to the original tree.OutputYou should print Q lines. In the i-th line, print a single integer: the minimum cost required to clean the i-th variation of the tree. If the tree cannot be cleaned, print -1.Scoring \begin{array}{|c|c|l|} \hline \text{Subtask} & \text{Points} & \text{Constraints} \\ \hline 1 & 0 & \text{samples}\\ \hline 2 & 9 & Q = 1, \text{there is an edge between node} \: 1 \: \text{and} \: i \: \text{for every} \: i \: (2 \leq i \leq N), \\ & & \text{Flóra can't add extra leaf to node} \: 1 \\ \hline 3 & 9 & Q = 1, \text{there is an edge between node} \: i \: \text{and} \: i+1 \: \text{for all} \: (1 \leq i < N), \\ & & \text{Flóra can't add extra leaf to node} \: 1 \: \text{nor node} \: N \\ \hline 4 & 16 & N \leq 20000, Q \leq 300\\ \hline 5 & 19 & \text{the original tree is a perfect binary tree rooted at node 1} \\ & & \text{(i.e. each internal node has exactly 2 children, and every leaf} \\ & & \text{has the same distance from the root)}\\ \hline 6 & 17 & D_i = 1 \: \text{for all} \: i\\ \hline 7 & 30 & \text{no additional constraints}\\ \hline \end{array} ExampleInput
7 3
1 2
2 4
4 5
5 6
5 7
3 4
1 4
2 2 4
1 1
Output
-1
10
8
NoteThe following picture shows the second variation. A possible solution is to clean the path between leaves 1 - 6, A - 7 and B - 3.You can download the above example and an additional (bigger) sample input here: https://gofile.io/d/8QlbsS | 7 3
1 2
2 4
4 5
5 6
5 7
3 4
1 4
2 2 4
1 1
| -1 10 8 | 1 second | 256 megabytes | ['*special problem', 'data structures', 'dfs and similar', 'graphs', 'trees', '*2300'] |
A. The Potion of Great Powertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time, in the Land of the Shamans, everyone lived on the Sky-High Beanstalk. Each shaman had a unique identifying number i between 0 and N-1, and an altitude value H_i, representing how high he lived above ground level. The distance between two altitudes is the absolute value of their difference.All shamans lived together in peace, until one of them stole the formula of the world-famous Potion of Great Power. To cover his/her tracks, the Thief has put a Curse on the land: most inhabitants could no longer trust each other...Despite the very difficult circumstances, the Order of Good Investigators have gained the following information about the Curse: When the Curse first takes effect, everyone stops trusting each other. The Curse is unstable: at the end of each day (exactly at midnight), one pair of shamans will start or stop trusting each other. Unfortunately, each shaman will only ever trust at most D others at any given time. They have also reconstructed a log of who trusted whom: for each night they know which pair of shamans started/stopped trusting each other.They believe the Thief has whispered the formula to an Evil Shaman. To avoid detection, both of them visited the home of one of their (respective) trusted friends. During the visit, the Thief whispered the formula to the Evil Shaman through the window. (Note: this trusted friend did not have to be home at the time. In fact, it's even possible that they visited each other's houses – shamans are weird.)Fortunately, whispers only travel short distances, so the Order knows the two trusted friends visited (by the Thief and the Evil Shaman) must live very close to each other.They ask you to help with their investigation. They would like to test their suspicions: what if the Thief was x, the Evil Shaman was y, and the formula was whispered on day v? What is the smallest distance the whispered formula had to travel? That is, what is the minimum distance between the apartments of some shamans x' and y' (i.e. \min\left(\left|H_{x'} - H_{y'}\right|\right)), such that x' was a trusted friend of x and y' was a trusted friend of y on day v?They will share all their information with you, then ask you a number of questions. You need to answer each question immediately, before receiving the next one.InteractionThe interaction will begin with a line containing N, D, U and Q (2 \leq N \leq 100000, 1 \leq D \leq 500, 0 \leq U \leq 200000, 1 \leq Q \leq 50000) – the number of shamans, the maximum number of trusted friends a shaman can have at any given point, the number of days, and the number of questions.On the next line N space separated integers will follow, the ith (1\leq i \leq N) of which being H_{i-1} (0\leq H_{i-1} \leq 10^9), the altitude of shaman i-1.On the next U lines there will be two integers each, on the ith (1 \leq i \leq U) A_i and B_i (0 \leq A_i, B_i < N and A_i \neq B_i), which represents a pair of shamans who started or stopped trusting each other at the end of day i-1. That is, if A_i and B_i trusted each other on day i-1, they did not trust each other on day i, or vice versa. Read all of these integers.The interactor now will ask you Q question, so the following interaction should happen Q times: Read 3 integers describing the current query: x,y and v (x \neq y, 0 \leq x,y < N and 0 \leq v \leq U), where x is the suspected Thief, y is the suspected Evil Shaman, and v is the suspected day.. Then print the answer to this query on a single line, i.e. you should print the minimum distance the whispered formula had to travel from some trusted friend x' of x to a trusted friend y' of y. In case someone trusted both x and y (i.e. x'=y'), you should print 0. If x or y had no trusted friends, print 10^9. After printing each line 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. Scoring \begin{array}{|c|c|c|} \hline \text{Subtask} & \text{Points} & \text{Constraints} \\ \hline 1 & 0 & \text{samples}\\ \hline 2 & 17 & Q,U \leq 1000 \\ \hline 3 & 14 & v=U \: \text{for all questions} \\ \hline 4 & 18 & H_i \in \left\{0,1\right\} \: \text{for all shamans} \: i \\ \hline 5 & 21 & U,N \leq 10000\\ \hline 6 & 30 & \text{no additional constraints}\\ \hline \end{array} ExampleInput
6 5 11 4
2 42 1000 54 68 234
0 1
2 0
3 4
3 5
3 5
1 3
5 3
0 5
3 0
1 3
3 5
0 3 4
3 0 8
0 5 5
3 0 11Output
26
0
1000000000
14NoteExample queries: Evolution of friendships: | 6 5 11 4
2 42 1000 54 68 234
0 1
2 0
3 4
3 5
3 5
1 3
5 3
0 5
3 0
1 3
3 5
0 3 4
3 0 8
0 5 5
3 0 11 | 26 0 1000000000 14 | 3 seconds | 256 megabytes | ['*special problem', '2-sat', 'binary search', 'data structures', 'graphs', 'interactive', 'sortings', 'two pointers', '*2400'] |
C. Star Trektime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe United Federation of Planets is an alliance of N planets, they are indexed from 1 to N. Some planets are connected by space tunnels. In a space tunnel, a starship can fly both ways really fast. There are exactly N-1 space tunnels, and we can travel from any planet to any other planet in the Federation using these tunnels.It's well known that there are D additional parallel universes. These are exact copies of our universe, they have the same planets and space tunnels. They are indexed from 1 to D (our universe has index 0). We denote the planet x in universe i by P_x^i. We can travel from one universe to another using dimension portals. For every i (0\leq i \leq D-1), we will place exactly one portal that allows us to fly from P_{A_i}^i to P_{B_i}^{i+1}, for some planet indices A_i and B_i (i.e. 1 \leq A_i, B_i \leq N).Once all the portals are placed, Starship Batthyány will embark on its maiden voyage. It is currently orbiting around P_1^0. Captain Ágnes and Lieutenant Gábor have decided to play the following game: they choose alternately a destination (a planet) to fly to. This planet can be in the same universe, if a space tunnel goes there, or it can be in another universe, if a portal goes there. Their aim is to visit places where no one has gone before. That's why, once they have visited a planet P_x^i, they never go back there (but they can visit the planet x in another universe). Captain Ágnes chooses the first destination (then Gábor, then Ágnes etc.). If somebody can't choose a planet where they have not been before in his/her turn, he/she loses.Captain Ágnes and Lieutenant Gábor are both very clever: they know the locations of all tunnels and portals, and they both play optimally. For how many different placements of portals does Captain Ágnes win the game? Two placements are different if there is an index i (0\leq i \leq D-1), where the ith portal connects different pairs of planets in the two placements (i.e A_i or B_i differs).This number can be very big, so we are interested in it modulo 10^9+7.InputThe first line contains two space-separated integers, N (1\leq N \leq 10^{5}) – the number of planets and D (1 \leq D \leq 10^{18}) – the number of additional parallel universes. Each of the next N-1 lines contains two space-separated integers u and v (1 \leq u, v \leq N), denoting that P_u^i and P_v^i are connected by a space tunnel for all i (0 \leq i \leq D).OutputYou should print a single integer, the number of possible placements of portals where Captain Ágnes wins modulo 10^9+7.Scoring \begin{array}{|c|c|c|} \hline \text{Subtask} & \text{Points} & \text{Constraints} \\ \hline 1 & 0 & \text{samples}\\ \hline 2 & 7 & N=2 \\ \hline 3 & 8 & N \leq 100 \: \text{and} \: D = 1 \\ \hline 4 & 15 & N \leq 1000 \: \text{and} \: D = 1\\ \hline 5 & 15 & D=1 \\ \hline 6 & 20 & N \leq 1000 \: \text{and} \: D \leq 10^5\\ \hline 7 & 20 & D \leq 10^5\\ \hline 8 & 15 & \text{no additional constraints}\\ \hline \end{array} ExampleInput
3 1
1 2
2 3
Output
4
NoteThere is only 1 portal and 3 \cdot 3 = 9 different placements. The following 4 placements are when the Captain wins. | 3 1
1 2
2 3
| 4 | 1 second | 256 megabytes | ['*special problem', 'combinatorics', 'dfs and similar', 'dp', 'games', 'graphs', 'matrices', 'trees', '*2600'] |
B. Roadstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe government of Treeland wants to build a new road network. There are 2N cities in Treeland. The unfinished plan of the road network already contains N road segments, each of which connects two cities with a straight line. No two road segments have a common point (including their endpoints). Your task is to determine N-1 additional road segments satisfying the following conditions: Every new road segment must connect two cities with a straight line. If two segments (new or old) have a common point, then this point must be an endpoint of both segments. The road network connects all cities: for each pair of cities there is a path consisting of segments that connects the two cities. InputThe first line of the standard input contains N ({2 \leq N \leq 10^5}) – the number of existing road segments. Each of the following N lines contains four integers: x_1,y_1, x_2, y_2, where (x_1, y_1) and (x_2, y_2) are the coordinates of the endpoints of the segment (-10^7 \leq x_i,y_i\leq 10^7).OutputThe standard output must contain N-1 lines, each of them containing four integers, x_1, y_1, x_2, y_2, where (x_1,y_1) and (x_2, y_2) are the coordinates of the cities that are the endpoints of a new road segment. If there are multiple solutions, your program may output any of them.Scoring \begin{array}{|c|c|l|} \hline \text{Subtask} & \text{Points} & \text{Constraints} \\ \hline 1 & 0 & \text{samples}\\ \hline 2 & 15 & \text{all input segments are vertical.} \\ \hline 3 & 15 & \text{each pair of input segments are parallel.} \\ \hline 4 & 15 & \text{each input segment is either horizontal or vertical.} \\ \hline 5 & 15 & N \le 10\,000 \\ \hline 6 & 40 & \text{no additional constraints}\\ \hline \end{array} ExampleInput
5
1 3 3 6
5 1 5 3
3 3 6 5
2 1 4 1
2 3 4 2
Output
2 1 1 3
2 3 2 1
3 3 2 3
5 1 4 2
Note | 5
1 3 3 6
5 1 5 3
3 3 6 5
2 1 4 1
2 3 4 2
| 2 1 1 3 2 3 2 1 3 3 2 3 5 1 4 2 | 1.5 seconds | 256 megabytes | ['*special problem', 'geometry', 'sortings', '*2900'] |
A. Fancy Fencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverybody knows that Balázs has the fanciest fence in the whole town. It's built up from N fancy sections. The sections are rectangles standing closely next to each other on the ground. The ith section has integer height h_i and integer width w_i. We are looking for fancy rectangles on this fancy fence. A rectangle is fancy if: its sides are either horizontal or vertical and have integer lengths the distance between the rectangle and the ground is integer the distance between the rectangle and the left side of the first section is integer it's lying completely on sections What is the number of fancy rectangles? This number can be very big, so we are interested in it modulo 10^9+7.InputThe first line contains N (1\leq N \leq 10^{5}) – the number of sections. The second line contains N space-separated integers, the ith number is h_i (1 \leq h_i \leq 10^{9}). The third line contains N space-separated integers, the ith number is w_i (1 \leq w_i \leq 10^{9}).OutputYou should print a single integer, the number of fancy rectangles modulo 10^9+7. So the output range is 0,1,2,\ldots, 10^9+6.Scoring \begin{array}{|c|c|c|} \hline \text{Subtask} & \text{Points} & \text{Constraints} \\ \hline 1 & 0 & \text{sample}\\ \hline 2 & 12 & N \leq 50 \: \text{and} \: h_i \leq 50 \: \text{and} \: w_i = 1 \: \text{for all} \: i \\ \hline 3 & 13 & h_i = 1 \: \text{or} \: h_i = 2 \: \text{for all} \: i \\ \hline 4 & 15 & \text{all} \: h_i \: \text{are equal} \\ \hline 5 & 15 & h_i \leq h_{i+1} \: \text{for all} \: i \leq N-1 \\ \hline 6 & 18 & N \leq 1000\\ \hline 7 & 27 & \text{no additional constraints}\\ \hline \end{array} ExampleInput
2
1 2
1 2
Output
12
NoteThe fence looks like this: There are 5 fancy rectangles of shape: There are 3 fancy rectangles of shape: There is 1 fancy rectangle of shape: There are 2 fancy rectangles of shape: There is 1 fancy rectangle of shape: | 2
1 2
1 2
| 12 | 1 second | 256 megabytes | ['*special problem', 'data structures', 'dsu', 'implementation', 'math', 'sortings', '*1800'] |
F. Reverse and Swaptime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length 2^n. You should process q queries on it. Each query has one of the following 4 types: Replace(x, k) — change a_x to k; Reverse(k) — reverse each subarray [(i-1) \cdot 2^k+1, i \cdot 2^k] for all i (i \ge 1); Swap(k) — swap subarrays [(2i-2) \cdot 2^k+1, (2i-1) \cdot 2^k] and [(2i-1) \cdot 2^k+1, 2i \cdot 2^k] for all i (i \ge 1); Sum(l, r) — print the sum of the elements of subarray [l, r]. Write a program that can quickly process given queries.InputThe first line contains two integers n, q (0 \le n \le 18; 1 \le q \le 10^5) — the length of array a and the number of queries.The second line contains 2^n integers a_1, a_2, \ldots, a_{2^n} (0 \le a_i \le 10^9).Next q lines contains queries — one per line. Each query has one of 4 types: "1 x k" (1 \le x \le 2^n; 0 \le k \le 10^9) — Replace(x, k); "2 k" (0 \le k \le n) — Reverse(k); "3 k" (0 \le k < n) — Swap(k); "4 l r" (1 \le l \le r \le 2^n) — Sum(l, r). It is guaranteed that there is at least one Sum query.OutputPrint the answer for each Sum query.ExamplesInput
2 3
7 4 9 9
1 2 8
3 1
4 2 4
Output
24
Input
3 8
7 0 8 8 7 1 5 2
4 3 7
2 1
3 2
4 1 6
2 3
1 5 16
4 8 8
3 0
Output
29
22
1
NoteIn the first sample, initially, the array a is equal to \{7,4,9,9\}.After processing the first query. the array a becomes \{7,8,9,9\}.After processing the second query, the array a_i becomes \{9,9,7,8\}Therefore, the answer to the third query is 9+7+8=24.In the second sample, initially, the array a is equal to \{7,0,8,8,7,1,5,2\}. What happens next is: Sum(3, 7) \to 8 + 8 + 7 + 1 + 5 = 29; Reverse(1) \to \{0,7,8,8,1,7,2,5\}; Swap(2) \to \{1,7,2,5,0,7,8,8\}; Sum(1, 6) \to 1 + 7 + 2 + 5 + 0 + 7 = 22; Reverse(3) \to \{8,8,7,0,5,2,7,1\}; Replace(5, 16) \to \{8,8,7,0,16,2,7,1\}; Sum(8, 8) \to 1; Swap(0) \to \{8,8,0,7,2,16,1,7\}. | 2 3
7 4 9 9
1 2 8
3 1
4 2 4
| 24 | 3 seconds | 256 megabytes | ['binary search', 'bitmasks', 'data structures', '*2400'] |
E. Divide Squaretime limit per test2 secondsmemory limit per test384 megabytesinputstandard inputoutputstandard outputThere is a square of size 10^6 \times 10^6 on the coordinate plane with four points (0, 0), (0, 10^6), (10^6, 0), and (10^6, 10^6) as its vertices.You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.Now you are wondering how many pieces this square divides into after drawing all segments. Write a program calculating the number of pieces of the square.InputThe first line contains two integers n and m (0 \le n, m \le 10^5) — the number of horizontal segments and the number of vertical segments.The next n lines contain descriptions of the horizontal segments. The i-th line contains three integers y_i, lx_i and rx_i (0 < y_i < 10^6; 0 \le lx_i < rx_i \le 10^6), which means the segment connects (lx_i, y_i) and (rx_i, y_i).The next m lines contain descriptions of the vertical segments. The i-th line contains three integers x_i, ly_i and ry_i (0 < x_i < 10^6; 0 \le ly_i < ry_i \le 10^6), which means the segment connects (x_i, ly_i) and (x_i, ry_i).It's guaranteed that there are no two segments on the same line, and each segment intersects with at least one of square's sides.OutputPrint the number of pieces the square is divided into after drawing all the segments.ExampleInput
3 3
2 3 1000000
4 0 4
3 0 1000000
4 0 1
2 0 5
3 1 1000000
Output
7Note The sample is like this: | 3 3
2 3 1000000
4 0 4
3 0 1000000
4 0 1
2 0 5
3 1 1000000
| 7 | 2 seconds | 384 megabytes | ['data structures', 'geometry', 'implementation', 'sortings', '*2400'] |
D. Maximum Distributed Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree that consists of n nodes. You should label each of its n-1 edges with an integer in such way that satisfies the following conditions: each integer must be greater than 0; the product of all n-1 numbers should be equal to k; the number of 1-s among all n-1 integers must be minimum possible. Let's define f(u,v) as the sum of the numbers on the simple path from node u to node v. Also, let \sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j) be a distribution index of the tree.Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo 10^9 + 7.In this problem, since the number k can be large, the result of the prime factorization of k is given instead.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 10^5) — the number of nodes in the tree.Each of the next n-1 lines describes an edge: the i-th line contains two integers u_i and v_i (1 \le u_i, v_i \le n; u_i \ne v_i) — indices of vertices connected by the i-th edge.Next line contains a single integer m (1 \le m \le 6 \cdot 10^4) — the number of prime factors of k.Next line contains m prime numbers p_1, p_2, \ldots, p_m (2 \le p_i < 6 \cdot 10^4) such that k = p_1 \cdot p_2 \cdot \ldots \cdot p_m.It is guaranteed that the sum of n over all test cases doesn't exceed 10^5, the sum of m over all test cases doesn't exceed 6 \cdot 10^4, and the given edges for each test cases form a tree.OutputPrint the maximum distribution index you can get. Since answer can be too large, print it modulo 10^9+7.ExampleInput
3
4
1 2
2 3
3 4
2
2 2
4
3 4
1 3
3 2
2
3 2
7
6 1
2 3
4 6
7 3
5 1
3 6
4
7 5 13 3
Output
17
18
286
Note In the first test case, one of the optimal ways is on the following image: In this case, f(1,2)=1, f(1,3)=3, f(1,4)=5, f(2,3)=2, f(2,4)=4, f(3,4)=2, so the sum of these 6 numbers is 17. In the second test case, one of the optimal ways is on the following image: In this case, f(1,2)=3, f(1,3)=1, f(1,4)=4, f(2,3)=2, f(2,4)=5, f(3,4)=3, so the sum of these 6 numbers is 18. | 3
4
1 2
2 3
3 4
2
2 2
4
3 4
1 3
3 2
2
3 2
7
6 1
2 3
4 6
7 3
5 1
3 6
4
7 5 13 3
| 17 18 286 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'greedy', 'implementation', 'math', 'number theory', 'sortings', 'trees', '*1800'] |
C. Mere Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output You are given an array a_1, a_2, \dots, a_n where all a_i are integers and greater than 0. In one operation, you can choose two different indices i and j (1 \le i, j \le n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y. Now you'd like to make a non-decreasing using the operation any number of times (possibly zero). Determine if you can do this. An array a is non-decreasing if and only if a_1 \le a_2 \le \ldots \le a_n.Input The first line contains one integer t (1 \le t \le 10^4) — the number of test cases. The first line of each test case contains one integer n (1 \le n \le 10^5) — the length of array a. The second line of each test case contains n positive integers a_1, a_2, \ldots a_n (1 \le a_i \le 10^9) — the array itself. It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.Output For each test case, output "YES" if it is possible to make the array a non-decreasing using the described operation, or "NO" if it is impossible to do so.ExampleInput
4
1
8
6
4 3 6 6 2 9
4
4 5 6 7
5
7 5 2 2 4
Output
YES
YES
YES
NO
Note In the first and third sample, the array is already non-decreasing. In the second sample, we can swap a_1 and a_3 first, and swap a_1 and a_5 second to make the array non-decreasing. In the forth sample, we cannot the array non-decreasing using the operation. | 4
1
8
6
4 3 6 6 2 9
4
4 5 6 7
5
7 5 2 2 4
| YES YES YES NO | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', 'number theory', 'sortings', '*1300'] |
B. Ternary Sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two sequences a_1, a_2, \dots, a_n and b_1, b_2, \dots, b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively.You can rearrange the elements in both sequences a and b however you like. After that, let's define a sequence c as follows:c_i = \begin{cases} a_i b_i & \mbox{if }a_i > b_i \\ 0 & \mbox{if }a_i = b_i \\ -a_i b_i & \mbox{if }a_i < b_i \end{cases}You'd like to make \sum_{i=1}^n c_i (the sum of all elements of the sequence c) as large as possible. What is the maximum possible sum?InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of two lines. The first line of each test case contains three integers x_1, y_1, z_1 (0 \le x_1, y_1, z_1 \le 10^8) — the number of 0-s, 1-s and 2-s in the sequence a.The second line of each test case also contains three integers x_2, y_2, z_2 (0 \le x_2, y_2, z_2 \le 10^8; x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0) — the number of 0-s, 1-s and 2-s in the sequence b.OutputFor each test case, print the maximum possible sum of the sequence c.ExampleInput
3
2 3 2
3 3 1
4 0 1
2 3 0
0 0 1
0 0 1
Output
4
2
0
NoteIn the first sample, one of the optimal solutions is:a = \{2, 0, 1, 1, 0, 2, 1\}b = \{1, 0, 1, 0, 2, 1, 0\}c = \{2, 0, 0, 0, 0, 2, 0\}In the second sample, one of the optimal solutions is:a = \{0, 2, 0, 0, 0\}b = \{1, 1, 0, 1, 0\}c = \{0, 2, 0, 0, 0\}In the third sample, the only possible solution is:a = \{2\}b = \{2\}c = \{0\} | 3
2 3 2
3 3 1
4 0 1
2 3 0
0 0 1
0 0 1
| 4 2 0 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*1100'] |
A. Distance and Axistime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. The description of the first test case. Since sometimes it's impossible to find such point B, we can, in one step, increase or decrease the coordinate of A by 1. What is the minimum number of steps we should do to make such point B exist?InputThe first line contains one integer t (1 \le t \le 6000) — the number of test cases.The only line of each test case contains two integers n and k (0 \le n, k \le 10^6) — the initial position of point A and desirable absolute difference.OutputFor each test case, print the minimum number of steps to make point B exist.ExampleInput
6
4 0
5 8
0 1000000
0 0
1 0
1000000 1000000
Output
0
3
1000000
0
1
0
NoteIn the first test case (picture above), if we set the coordinate of B as 2 then the absolute difference will be equal to |(2 - 0) - (4 - 2)| = 0 and we don't have to move A. So the answer is 0.In the second test case, we can increase the coordinate of A by 3 and set the coordinate of B as 0 or 8. The absolute difference will be equal to |8 - 0| = 8, so the answer is 3. | 6
4 0
5 8
0 1000000
0 0
1 0
1000000 1000000
| 0 3 1000000 0 1 0 | 1 second | 256 megabytes | ['constructive algorithms', 'math', '*900'] |
G. Mercenariestime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp plays a (yet another!) strategic computer game. In this game, he leads an army of mercenaries.Polycarp wants to gather his army for a quest. There are n mercenaries for hire, and the army should consist of some subset of them.The i-th mercenary can be chosen if the resulting number of chosen mercenaries is not less than l_i (otherwise he deems the quest to be doomed) and not greater than r_i (he doesn't want to share the trophies with too many other mercenaries). Furthermore, m pairs of mercenaries hate each other and cannot be chosen for the same quest. How many non-empty subsets does Polycarp need to consider? In other words, calculate the number of non-empty subsets of mercenaries such that the size of this subset belongs to [l_i, r_i] for each chosen mercenary, and there are no two mercenaries in the subset that hate each other.The answer may be large, so calculate it modulo 998244353.InputThe first line contains two integers n and m (1 \le n \le 3 \cdot 10^5, 0 \le m \le \min(20, \dfrac{n(n-1)}{2})) — the number of mercenaries and the number of pairs of mercenaries that hate each other.Then n lines follow, the i-th of them contains two integers l_i and r_i (1 \le l_i \le r_i \le n).Then m lines follow, the i-th of them contains two integers a_i and b_i (1 \le a_i < b_i \le n) denoting that the mercenaries a_i and b_i hate each other. There are no two equal pairs in this list.OutputPrint one integer — the number of non-empty subsets meeting the constraints, taken modulo 998244353.ExamplesInput
3 0
1 1
2 3
1 3
Output
3
Input
3 1
1 1
2 3
1 3
2 3
Output
2
| 3 0
1 1
2 3
1 3
| 3 | 7 seconds | 512 megabytes | ['bitmasks', 'brute force', 'combinatorics', 'dp', 'dsu', 'math', 'two pointers', '*2600'] |
F. x-prime Substringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer value x and a string s consisting of digits from 1 to 9 inclusive.A substring of a string is a contiguous subsequence of that string.Let f(l, r) be the sum of digits of a substring s[l..r].Let's call substring s[l_1..r_1] x-prime if f(l_1, r_1) = x; there are no values l_2, r_2 such that l_1 \le l_2 \le r_2 \le r_1; f(l_2, r_2) \neq x; x is divisible by f(l_2, r_2). You are allowed to erase some characters from the string. If you erase a character, the two resulting parts of the string are concatenated without changing their order.What is the minimum number of characters you should erase from the string so that there are no x-prime substrings in it? If there are no x-prime substrings in the given string s, then print 0.InputThe first line contains a string s (1 \le |s| \le 1000). s contains only digits from 1 to 9 inclusive.The second line contains an integer x (1 \le x \le 20).OutputPrint a single integer — the minimum number of characters you should erase from the string so that there are no x-prime substrings in it. If there are no x-prime substrings in the given string s, then print 0.ExamplesInput
116285317
8
Output
2
Input
314159265359
1
Output
2
Input
13
13
Output
0
Input
3434343434
7
Output
5
NoteIn the first example there are two 8-prime substrings "8" and "53". You can erase these characters to get rid of both: "116285317". The resulting string "1162317" contains no 8-prime substrings. Removing these characters is also a valid answer: "116285317".In the second example you just have to erase both ones.In the third example there are no 13-prime substrings. There are no substrings with the sum of digits equal to 13 at all.In the fourth example you can have neither "34", nor "43" in a string. Thus, you have to erase either all threes or all fours. There are 5 of each of them, so it doesn't matter which. | 116285317
8
| 2 | 2 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'dp', 'string suffix structures', 'strings', '*2800'] |
E. Clear the Multisettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a multiset containing several integers. Initially, it contains a_1 elements equal to 1, a_2 elements equal to 2, ..., a_n elements equal to n.You may apply two types of operations: choose two integers l and r (l \le r), then remove one occurrence of l, one occurrence of l + 1, ..., one occurrence of r from the multiset. This operation can be applied only if each number from l to r occurs at least once in the multiset; choose two integers i and x (x \ge 1), then remove x occurrences of i from the multiset. This operation can be applied only if the multiset contains at least x occurrences of i. What is the minimum number of operations required to delete all elements from the multiset?InputThe first line contains one integer n (1 \le n \le 5000).The second line contains n integers a_1, a_2, ..., a_n (0 \le a_i \le 10^9).OutputPrint one integer — the minimum number of operations required to delete all elements from the multiset.ExamplesInput
4
1 4 1 1
Output
2
Input
5
1 0 1 0 1
Output
3
| 4
1 4 1 1
| 2 | 2 seconds | 256 megabytes | ['data structures', 'divide and conquer', 'dp', 'greedy', '*2200'] |
D. Zigzagstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2 \dots a_n. Calculate the number of tuples (i, j, k, l) such that: 1 \le i < j < k < l \le n; a_i = a_k and a_j = a_l; InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains a single integer n (4 \le n \le 3000) — the size 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 n) — the array a.It's guaranteed that the sum of n in one test doesn't exceed 3000.OutputFor each test case, print the number of described tuples.ExampleInput
2
5
2 2 2 2 2
6
1 3 3 1 2 3
Output
5
2
NoteIn the first test case, for any four indices i < j < k < l are valid, so the answer is the number of tuples.In the second test case, there are 2 valid tuples: (1, 2, 4, 6): a_1 = a_4 and a_2 = a_6; (1, 3, 4, 6): a_1 = a_4 and a_3 = a_6. | 2
5
2 2 2 2 2
6
1 3 3 1 2 3
| 5 2 | 2 seconds | 256 megabytes | ['brute force', 'combinatorics', 'data structures', 'math', 'two pointers', '*1900'] |
C. Binary String Reconstructiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider the following process. You have a binary string (a string where each character is either 0 or 1) w of length n and an integer x. You build a new binary string s consisting of n characters. The i-th character of s is chosen as follows: if the character w_{i-x} exists and is equal to 1, then s_i is 1 (formally, if i > x and w_{i-x} = 1, then s_i = 1); if the character w_{i+x} exists and is equal to 1, then s_i is 1 (formally, if i + x \le n and w_{i+x} = 1, then s_i = 1); if both of the aforementioned conditions are false, then s_i is 0. You are given the integer x and the resulting string s. Reconstruct the original string w.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Each test case consists of two lines. The first line contains the resulting string s (2 \le |s| \le 10^5, each character of s is either 0 or 1). The second line contains one integer x (1 \le x \le |s| - 1).The total length of all strings s in the input does not exceed 10^5.OutputFor each test case, print the answer on a separate line as follows: if no string w can produce the string s at the end of the process, print -1; otherwise, print the binary string w consisting of |s| characters. If there are multiple answers, print any of them. ExampleInput
3
101110
2
01
1
110
1
Output
111011
10
-1
| 3
101110
2
01
1
110
1
| 111011 10 -1 | 2 seconds | 256 megabytes | ['2-sat', 'brute force', 'constructive algorithms', 'greedy', '*1500'] |
B. RPG Protagonisttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units.In the blacksmith shop, you found cnt_s swords and cnt_w war axes. Each sword weights s units and each war axe — w units. You don't care what to take, since each of them will melt into one steel ingot.What is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains two integers p and f (1 \le p, f \le 10^9) — yours and your follower's capacities.The second line of each test case contains two integers cnt_s and cnt_w (1 \le cnt_s, cnt_w \le 2 \cdot 10^5) — the number of swords and war axes in the shop.The third line of each test case contains two integers s and w (1 \le s, w \le 10^9) — the weights of each sword and each war axe.It's guaranteed that the total number of swords and the total number of war axes in all test cases don't exceed 2 \cdot 10^5.OutputFor each test case, print the maximum number of weapons (both swords and war axes) you and your follower can carry.ExampleInput
3
33 27
6 10
5 6
100 200
10 10
5 5
1 19
1 3
19 5
Output
11
20
3
NoteIn the first test case: you should take 3 swords and 3 war axes: 3 \cdot 5 + 3 \cdot 6 = 33 \le 33 and your follower — 3 swords and 2 war axes: 3 \cdot 5 + 2 \cdot 6 = 27 \le 27. 3 + 3 + 3 + 2 = 11 weapons in total.In the second test case, you can take all available weapons even without your follower's help, since 5 \cdot 10 + 5 \cdot 10 \le 100.In the third test case, you can't take anything, but your follower can take 3 war axes: 3 \cdot 5 \le 19. | 3
33 27
6 10
5 6
100 200
10 10
5 5
1 19
1 3
19 5
| 11 20 3 | 2 seconds | 256 megabytes | ['brute force', 'greedy', 'math', '*1700'] |
A. String Similaritytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: 10010 and 01111 are similar (they have the same character in position 4); 10010 and 11111 are similar; 111 and 111 are similar; 0110 and 1001 are not similar. You are given an integer n and a binary string s consisting of 2n-1 characters. Let's denote s[l..r] as the contiguous substring of s starting with l-th character and ending with r-th character (in other words, s[l..r] = s_l s_{l + 1} s_{l + 2} \dots s_r).You have to construct a binary string w of length n which is similar to all of the following strings: s[1..n], s[2..n+1], s[3..n+2], ..., s[n..2n-1].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 a single integer n (1 \le n \le 50).The second line of each test case contains the binary string s of length 2n - 1. Each character s_i is either 0 or 1.OutputFor each test case, print the corresponding binary string w of length n. If there are multiple such strings — print any of them. It can be shown that at least one string w meeting the constraints always exists.ExampleInput
4
1
1
3
00000
4
1110000
2
101
Output
1
000
1010
00
NoteThe explanation of the sample case (equal characters in equal positions are bold):The first test case: \mathbf{1} is similar to s[1..1] = \mathbf{1}. The second test case: \mathbf{000} is similar to s[1..3] = \mathbf{000}; \mathbf{000} is similar to s[2..4] = \mathbf{000}; \mathbf{000} is similar to s[3..5] = \mathbf{000}. The third test case: \mathbf{1}0\mathbf{10} is similar to s[1..4] = \mathbf{1}1\mathbf{10}; \mathbf{1}01\mathbf{0} is similar to s[2..5] = \mathbf{1}10\mathbf{0}; \mathbf{10}1\mathbf{0} is similar to s[3..6] = \mathbf{10}0\mathbf{0}; 1\mathbf{0}1\mathbf{0} is similar to s[4..7] = 0\mathbf{0}0\mathbf{0}. The fourth test case: 0\mathbf{0} is similar to s[1..2] = 1\mathbf{0}; \mathbf{0}0 is similar to s[2..3] = \mathbf{0}1. | 4
1
1
3
00000
4
1110000
2
101
| 1 000 1010 00 | 2 seconds | 256 megabytes | ['constructive algorithms', 'strings', '*800'] |
F. Yet Another Segments Subsettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n segments on a coordinate axis OX. The i-th segment has borders [l_i; r_i]. All points x, for which l_i \le x \le r_i holds, belong to the i-th segment.Your task is to choose the maximum by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.Two segments [l_i; r_i] and [l_j; r_j] are non-intersecting if they have no common points. For example, segments [1; 2] and [3; 4], [1; 3] and [5; 5] are non-intersecting, while segments [1; 2] and [2; 3], [1; 2] and [2; 2] are intersecting.The segment [l_i; r_i] lies inside the segment [l_j; r_j] if l_j \le l_i and r_i \le r_j. For example, segments [2; 2], [2, 3], [3; 4] and [2; 4] lie inside the segment [2; 4], while [2; 5] and [1; 4] are not.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 3000) — the number of segments. The next n lines describe segments. The i-th segment is given as two integers l_i and r_i (1 \le l_i \le r_i \le 2 \cdot 10^5), where l_i is the left border of the i-th segment and r_i is the right border of the i-th segment.Additional constraint on the input: there are no duplicates in the list of segments.It is guaranteed that the sum of n does not exceed 3000 (\sum n \le 3000).OutputFor each test case, print the answer: the maximum possible size of the subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.ExampleInput
4
4
1 5
2 4
2 3
3 4
5
1 5
2 3
2 5
3 5
2 2
3
1 3
2 4
2 3
7
1 10
2 8
2 5
3 4
4 4
6 8
7 7
Output
3
4
2
7
| 4
4
1 5
2 4
2 3
3 4
5
1 5
2 3
2 5
3 5
2 2
3
1 3
2 4
2 3
7
1 10
2 8
2 5
3 4
4 4
6 8
7 7
| 3 4 2 7 | 3 seconds | 256 megabytes | ['data structures', 'dp', 'graphs', 'sortings', '*2300'] |
E2. Weights Division (hard version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEasy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left\lfloor\frac{w_i}{2}\right\rfloor).Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins.Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make \sum\limits_{v \in leaves} w(root, v) \le S, where leaves is the list of all leaves.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains two integers n and S (2 \le n \le 10^5; 1 \le S \le 10^{16}) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 \le v_i, u_i \le n; 1 \le w_i \le 10^6; 1 \le c_i \le 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge.It is guaranteed that the sum of n does not exceed 10^5 (\sum n \le 10^5).OutputFor each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S.ExampleInput
4
4 18
2 1 9 2
3 2 4 1
4 1 1 2
3 20
2 1 8 1
3 1 7 2
5 50
1 3 100 1
1 5 10 2
2 3 123 2
5 4 55 1
2 100
1 2 409 2
Output
0
0
11
6
| 4
4 18
2 1 9 2
3 2 4 1
4 1 1 2
3 20
2 1 8 1
3 1 7 2
5 50
1 3 100 1
1 5 10 2
2 3 123 2
5 4 55 1
2 100
1 2 409 2
| 0 0 11 6 | 3 seconds | 256 megabytes | ['binary search', 'dfs and similar', 'greedy', 'sortings', 'trees', 'two pointers', '*2200'] |
E1. Weights Division (easy version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEasy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex 1 is the root of this tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left\lfloor\frac{w_i}{2}\right\rfloor).Your task is to find the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make \sum\limits_{v \in leaves} w(root, v) \le S, where leaves is the list of all leaves.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains two integers n and S (2 \le n \le 10^5; 1 \le S \le 10^{16}) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as three integers v_i, u_i and w_i (1 \le v_i, u_i \le n; 1 \le w_i \le 10^6), where v_i and u_i are vertices the edge i connects and w_i is the weight of this edge.It is guaranteed that the sum of n does not exceed 10^5 (\sum n \le 10^5).OutputFor each test case, print the answer: the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most S.ExampleInput
3
3 20
2 1 8
3 1 7
5 50
1 3 100
1 5 10
2 3 123
5 4 55
2 100
1 2 409
Output
0
8
3
| 3
3 20
2 1 8
3 1 7
5 50
1 3 100
1 5 10
2 3 123
5 4 55
2 100
1 2 409
| 0 8 3 | 3 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'greedy', 'trees', '*2000'] |
D. Binary String To Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string s consisting of n zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer: in the first line print one integer k (1 \le k \le n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, \dots, a_n (1 \le a_i \le k), where a_i is the number of subsequence the i-th character of s belongs to.If there are several answers, you can print any.ExampleInput
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
| 4
4
0011
6
111111
5
10101
8
01010000
| 2 1 2 2 1 6 1 2 3 4 5 6 1 1 1 1 1 1 4 1 1 1 1 1 2 3 4 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'greedy', 'implementation', '*1500'] |
C. Boats Competitiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.So, if there are k teams (a_1, b_1), (a_2, b_2), \dots, (a_k, b_k), where a_i is the weight of the first participant of the i-th team and b_i is the weight of the second participant of the i-th team, then the condition a_1 + b_1 = a_2 + b_2 = \dots = a_k + b_k = s, where s is the total weight of each team, should be satisfied.Your task is to choose such s that the number of teams people can create is the maximum possible. Note that each participant can be in no more than one team.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 50) — the number of participants. The second line of the test case contains n integers w_1, w_2, \dots, w_n (1 \le w_i \le n), where w_i is the weight of the i-th participant.OutputFor each test case, print one integer k: the maximum number of teams people can compose with the total weight s, if you choose s optimally.ExampleInput
5
5
1 2 3 4 5
8
6 6 6 6 6 6 8 8
8
1 2 2 1 2 1 1 2
3
1 3 3
6
1 1 3 4 2 2
Output
2
3
4
1
2
NoteIn the first test case of the example, we can reach the optimal answer for s=6. Then the first boat is used by participants 1 and 5 and the second boat is used by participants 2 and 4 (indices are the same as weights).In the second test case of the example, we can reach the optimal answer for s=12. Then first 6 participants can form 3 pairs.In the third test case of the example, we can reach the optimal answer for s=3. The answer is 4 because we have 4 participants with weight 1 and 4 participants with weight 2.In the fourth test case of the example, we can reach the optimal answer for s=4 or s=6.In the fifth test case of the example, we can reach the optimal answer for s=3. Note that participant with weight 3 can't use the boat because there is no suitable pair for him in the list. | 5
5
1 2 3 4 5
8
6 6 6 6 6 6 8 8
8
1 2 2 1 2 1 1 2
3
1 3 3
6
1 1 3 4 2 2
| 2 3 4 1 2 | 2 seconds | 256 megabytes | ['brute force', 'greedy', 'two pointers', '*1200'] |
B. Gifts Fixingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.During one move, you can choose some gift 1 \le i \le n and do one of the following operations: eat exactly one candy from this gift (decrease a_i by one); eat exactly one orange from this gift (decrease b_i by one); eat exactly one candy and exactly one orange from this gift (decrease both a_i and b_i by one). Of course, you can not eat a candy or orange if it's not present in the gift (so neither a_i nor b_i can become less than zero).As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: a_1 = a_2 = \dots = a_n and b_1 = b_2 = \dots = b_n (and a_i equals b_i is not necessary).Your task is to find the minimum number of moves required to equalize all the given gifts.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 50) — the number of gifts. The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the number of candies in the i-th gift. The third line of the test case contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^9), where b_i is the number of oranges in the i-th gift.OutputFor each test case, print one integer: the minimum number of moves required to equalize all the given gifts.ExampleInput
5
3
3 5 6
3 2 3
5
1 2 3 4 5
5 4 3 2 1
3
1 1 1
2 2 2
6
1 1000000000 1000000000 1000000000 1000000000 1000000000
1 1 1 1 1 1
3
10 12 8
7 5 4
Output
6
16
0
4999999995
7
NoteIn the first test case of the example, we can perform the following sequence of moves: choose the first gift and eat one orange from it, so a = [3, 5, 6] and b = [2, 2, 3]; choose the second gift and eat one candy from it, so a = [3, 4, 6] and b = [2, 2, 3]; choose the second gift and eat one candy from it, so a = [3, 3, 6] and b = [2, 2, 3]; choose the third gift and eat one candy and one orange from it, so a = [3, 3, 5] and b = [2, 2, 2]; choose the third gift and eat one candy from it, so a = [3, 3, 4] and b = [2, 2, 2]; choose the third gift and eat one candy from it, so a = [3, 3, 3] and b = [2, 2, 2]. | 5
3
3 5 6
3 2 3
5
1 2 3 4 5
5 4 3 2 1
3
1 1 1
2 2 2
6
1 1000000000 1000000000 1000000000 1000000000 1000000000
1 1 1 1 1 1
3
10 12 8
7 5 4
| 6 16 0 4999999995 7 | 1 second | 256 megabytes | ['greedy', '*800'] |
A. Remove Smallesttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given the array a consisting of n positive (greater than zero) integers.In one move, you can choose two indices i and j (i \ne j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| \le 1) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 50) — the length of a. The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100), where a_i is the i-th element of a.OutputFor each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.ExampleInput
5
3
1 2 2
4
5 5 5 5
3
1 2 4
4
1 3 4 4
1
100
Output
YES
YES
NO
NO
YES
NoteIn the first test case of the example, we can perform the following sequence of moves: choose i=1 and j=3 and remove a_i (so a becomes [2; 2]); choose i=1 and j=2 and remove a_j (so a becomes [2]). In the second test case of the example, we can choose any possible i and j any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of 2 and 4. | 5
3
1 2 2
4
5 5 5 5
3
1 2 4
4
1 3 4 4
1
100
| YES YES NO NO YES | 1 second | 256 megabytes | ['greedy', 'sortings', '*800'] |
G. Running Competitiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA running competition is going to be held soon. The stadium where the competition will be held can be represented by several segments on the coordinate plane: two horizontal segments: one connecting the points (0, 0) and (x, 0), the other connecting the points (0, y) and (x, y); n + 1 vertical segments, numbered from 0 to n. The i-th segment connects the points (a_i, 0) and (a_i, y); 0 = a_0 < a_1 < a_2 < \dots < a_{n - 1} < a_n = x. For example, here is a picture of the stadium with x = 10, y = 5, n = 3 and a = [0, 3, 5, 10]: A lap is a route that goes along the segments, starts and finishes at the same point, and never intersects itself (the only two points of a lap that coincide are its starting point and ending point). The length of a lap is a total distance travelled around it. For example, the red route in the picture representing the stadium is a lap of length 24.The competition will be held in q stages. The i-th stage has length l_i, and the organizers want to choose a lap for each stage such that the length of the lap is a divisor of l_i. The organizers don't want to choose short laps for the stages, so for each stage, they want to find the maximum possible length of a suitable lap.Help the organizers to calculate the maximum possible lengths of the laps for the stages! In other words, for every l_i, find the maximum possible integer L such that l_i \bmod L = 0, and there exists a lap of length exactly L.If it is impossible to choose such a lap then print -1.InputThe first line contains three integers n, x and y (1 \le n, x, y \le 2 \cdot 10^5, n \le x).The second line contains n + 1 integers a_0, a_1, ..., a_n (0 = a_0 < a_1 < a_2 < \dots < a_{n - 1} < a_n = x).The third line contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of stages.The fourth line contains q even integers l_1, l_2, ..., l_q (4 \le l_i \le 10^6) — the lengths of the stages. OutputPrint q numbers. The i-th number should be equal to the maximum possible length of a suitable lap for the i-th stage, or -1 if it is impossible to choose a lap for that stage.ExampleInput
3 10 5
0 3 5 10
6
24 30 14 16 18 10
Output
24 30 14 16 -1 -1 | 3 10 5
0 3 5 10
6
24 30 14 16 18 10
| 24 30 14 16 -1 -1 | 2 seconds | 512 megabytes | ['bitmasks', 'fft', 'math', 'number theory', '*2600'] |
F. Controversial Roundstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob play a game. The game consists of several sets, and each set consists of several rounds. Each round is won either by Alice or by Bob, and the set ends when one of the players has won x rounds in a row. For example, if Bob won five rounds in a row and x = 2, then two sets ends.You know that Alice and Bob have already played n rounds, and you know the results of some rounds. For each x from 1 to n, calculate the maximum possible number of sets that could have already finished if each set lasts until one of the players wins x rounds in a row. It is possible that the last set is still not finished — in that case, you should not count it in the answer.InputThe first line contains one integer n (1 \le n \le 10^6) — the number of rounds.The second line contains one string s of length n — the descriptions of rounds. If the i-th element of the string is 0, then Alice won the i-th round; if it is 1, then Bob won the i-th round, and if it is ?, then you don't know who won the i-th round.OutputIn the only line print n integers. The i-th integer should be equal to the maximum possible number of sets that could have already finished if each set lasts until one of the players wins i rounds in a row.ExamplesInput
6
11?000
Output
6 3 2 1 0 0
Input
5
01?01
Output
5 1 0 0 0
Input
12
???1??????1?
Output
12 6 4 3 2 2 1 1 1 1 1 1
NoteLet's consider the first test case: if x = 1 and s = 110000 or s = 111000 then there are six finished sets; if x = 2 and s = 110000 then there are three finished sets; if x = 3 and s = 111000 then there are two finished sets; if x = 4 and s = 110000 then there is one finished set; if x = 5 then there are no finished sets; if x = 6 then there are no finished sets. | 6
11?000
| 6 3 2 1 0 0 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dp', 'greedy', 'two pointers', '*2500'] |
E. Two Types of Spellstime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: first, second, third. This order deals 5 + 1 + 2 \cdot 8 = 22 damage; first, third, second. This order deals 5 + 8 + 2 \cdot 1 = 15 damage; second, first, third. This order deals 1 + 2 \cdot 5 + 8 = 19 damage; second, third, first. This order deals 1 + 2 \cdot 8 + 2 \cdot 5 = 27 damage; third, first, second. This order deals 8 + 2 \cdot 5 + 1 = 19 damage; third, second, first. This order deals 8 + 2 \cdot 1 + 2 \cdot 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of changes to the spell set.Each of the next n lines contains two integers tp and d (0 \le tp_i \le 1; -10^9 \le d \le 10^9; d_i \neq 0) — the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).OutputAfter each change, print the maximum damage Polycarp can deal with his current set of spells.ExampleInput
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21
| 6
1 5
0 10
1 -5
0 5
1 11
0 -10
| 5 25 10 15 36 21 | 3.5 seconds | 256 megabytes | ['binary search', 'data structures', 'greedy', 'implementation', 'math', 'sortings', '*2200'] |
D. Colored Rectanglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three multisets of pairs of colored sticks: R pairs of red sticks, the first pair has length r_1, the second pair has length r_2, \dots, the R-th pair has length r_R; G pairs of green sticks, the first pair has length g_1, the second pair has length g_2, \dots, the G-th pair has length g_G; B pairs of blue sticks, the first pair has length b_1, the second pair has length b_2, \dots, the B-th pair has length b_B; You are constructing rectangles from these pairs of sticks with the following process: take a pair of sticks of one color; take a pair of sticks of another color different from the first one; add the area of the resulting rectangle to the total area. Thus, you get such rectangles that their opposite sides are the same color and their adjacent sides are not the same color.Each pair of sticks can be used at most once, some pairs can be left unused. You are not allowed to split a pair into independent sticks.What is the maximum area you can achieve?InputThe first line contains three integers R, G, B (1 \le R, G, B \le 200) — the number of pairs of red sticks, the number of pairs of green sticks and the number of pairs of blue sticks.The second line contains R integers r_1, r_2, \dots, r_R (1 \le r_i \le 2000) — the lengths of sticks in each pair of red sticks.The third line contains G integers g_1, g_2, \dots, g_G (1 \le g_i \le 2000) — the lengths of sticks in each pair of green sticks.The fourth line contains B integers b_1, b_2, \dots, b_B (1 \le b_i \le 2000) — the lengths of sticks in each pair of blue sticks.OutputPrint the maximum possible total area of the constructed rectangles.ExamplesInput
1 1 1
3
5
4
Output
20
Input
2 1 3
9 5
1
2 8 5
Output
99
Input
10 1 1
11 7 20 15 19 14 2 4 13 14
8
11
Output
372
NoteIn the first example you can construct one of these rectangles: red and green with sides 3 and 5, red and blue with sides 3 and 4 and green and blue with sides 5 and 4. The best area of them is 4 \times 5 = 20.In the second example the best rectangles are: red/blue 9 \times 8, red/blue 5 \times 5, green/blue 2 \times 1. So the total area is 72 + 25 + 2 = 99.In the third example the best rectangles are: red/green 19 \times 8 and red/blue 20 \times 11. The total area is 152 + 220 = 372. Note that you can't construct more rectangles because you are not allowed to have both pairs taken to be the same color. | 1 1 1
3
5
4
| 20 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'sortings', '*1800'] |
C. Good Subarraystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (\sum\limits_{i=l}^{r} a_i = r - l + 1).For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 \dots 1} = [1], a_{2 \dots 3} = [2, 0] and a_{1 \dots 3} = [1, 2, 0].Calculate the number of good subarrays of the array a.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains one integer n (1 \le n \le 10^5) — the length of the array a.The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case print one integer — the number of good subarrays of the array a.ExampleInput
3
3
120
5
11011
6
600005
Output
3
6
1
NoteThe first test case is considered in the statement.In the second test case, there are 6 good subarrays: a_{1 \dots 1}, a_{2 \dots 2}, a_{1 \dots 2}, a_{4 \dots 4}, a_{5 \dots 5} and a_{4 \dots 5}. In the third test case there is only one good subarray: a_{2 \dots 6}. | 3
3
120
5
11011
6
600005
| 3 6 1 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'math', '*1600'] |
B. Substring Removal Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on.During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them.For example, if the string is 10110, there are 6 possible moves (deleted characters are bold): \textbf{1}0110 \to 0110; 1\textbf{0}110 \to 1110; 10\textbf{1}10 \to 1010; 101\textbf{1}0 \to 1010; 10\textbf{11}0 \to 100; 1011\textbf{0} \to 1011. After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: 10\textbf{11}0 \to 1\textbf{00} \to 1.The game ends when the string becomes empty, and the score of each player is the number of 1-characters deleted by them.Each player wants to maximize their score. Calculate the resulting score of Alice.InputThe first line contains one integer T (1 \le T \le 500) — the number of test cases.Each test case contains exactly one line containing a binary string s (1 \le |s| \le 100).OutputFor each test case, print one integer — the resulting score of Alice (the number of 1-characters deleted by her).ExampleInput
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
NoteQuestions about the optimal strategy will be ignored. | 5
01111001
0000
111111
101010101
011011110111
| 4 0 6 3 6 | 2 seconds | 256 megabytes | ['games', 'greedy', 'sortings', '*800'] |
A. Bad Triangletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots , a_n, which is sorted in non-decreasing order (a_i \le a_{i + 1}). Find three indices i, j, k such that 1 \le i < j < k \le n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains one integer n (3 \le n \le 5 \cdot 10^4) — 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; a_{i - 1} \le a_i) — the array a.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case print the answer to it in one line.If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them.Otherwise, print -1.ExampleInput
3
7
4 6 11 11 15 18 20
4
10 10 10 11
3
1 1 1000000000
Output
2 3 6
-1
1 2 3
NoteIn the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer.In the second test case you always can construct a non-degenerate triangle. | 3
7
4 6 11 11 15 18 20
4
10 10 10 11
3
1 1 1000000000
| 2 3 6 -1 1 2 3 | 1 second | 256 megabytes | ['geometry', 'math', '*800'] |
B. Power Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 \le i \le n-1 then a_i = c^i.Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to: Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1. Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.InputThe first line contains an integer n (3 \le n \le 10^5).The second line contains n integers a_0, a_1, ..., a_{n-1} (1 \le a_i \le 10^9).OutputPrint the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.ExamplesInput
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
NoteIn the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}. | 3
1 3 2
| 1 | 1 second | 256 megabytes | ['brute force', 'math', 'number theory', 'sortings', '*1500'] |
A. Juggling Letterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n strings s_1, s_2, \ldots, s_n consisting of lowercase Latin letters.In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?InputThe first line contains t (1 \le t \le 10): the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 1000): the number of strings.n lines follow, the i-th line contains s_i (1 \le \lvert s_i \rvert \le 1000).The sum of lengths of all strings in all test cases does not exceed 1000.OutputIf it is possible to make the strings equal, print "YES" (without quotes).Otherwise, print "NO" (without quotes).You can output each character in either lowercase or uppercase.ExampleInput
4
2
caa
cbb
3
cba
cba
cbb
4
ccab
cbac
bca
acbcc
4
acb
caf
c
cbafc
Output
YES
NO
YES
NO
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all n strings equal. | 4
2
caa
cbb
3
cba
cba
cbb
4
ccab
cbac
bca
acbcc
4
acb
caf
c
cbafc
| YES NO YES NO | 1 second | 256 megabytes | ['greedy', 'strings', '*800'] |
E. Distance Matchingtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an integer k and a tree T with n nodes (n is even).Let dist(u, v) be the number of edges on the shortest path from node u to node v in T.Let us define a undirected weighted complete graph G = (V, E) as following: V = \{x \mid 1 \le x \le n \} i.e. the set of integers from 1 to n E = \{(u, v, w) \mid 1 \le u, v \le n, u \neq v, w = dist(u, v) \} i.e. there is an edge between every pair of distinct nodes, the weight being the distance between their respective nodes in T Your task is simple, find a perfect matching in G with total edge weight k (1 \le k \le n^2).InputThe first line of input contains two integers n, k (2 \le n \le 100\,000, n is even, 1 \le k \le n^2): number of nodes and the total edge weight of the perfect matching you need to find.The i-th of the following n - 1 lines contains two integers v_i, u_i (1 \le v_i, u_i \le n) denoting an edge between v_i and u_i in T. It is guaranteed that the given graph is a tree. OutputIf there are no matchings that satisfy the above condition, output "NO" (without quotes) on a single line. Otherwise, you should output "YES" (without quotes) on the first line of output.You should then output \frac{n}{2} lines, the i-th line containing p_i, q_i (1 \le p_i, q_i \le n): the i-th pair of the matching.ExamplesInput
4 2
1 2
2 3
3 4
Output
YES
2 1
3 4
Input
4 4
1 2
2 3
3 4
Output
YES
3 1
2 4
NoteA tree is a connected acyclic undirected graph.A matching is set of pairwise non-adjacent edges, none of which are loops; that is, no two edges share a common vertex. A perfect matching is a matching which matches all vertices of the graph; that is, every vertex of the graph is incident to exactly one edge of the matching. | 4 2
1 2
2 3
3 4
| YES 2 1 3 4 | 2 seconds | 512 megabytes | ['constructive algorithms', 'dfs and similar', 'trees', '*3200'] |
D. Rainbow Rectanglestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputShrimpy Duc is a fat and greedy boy who is always hungry. After a while of searching for food to satisfy his never-ending hunger, Shrimpy Duc finds M&M candies lying unguarded on a L \times L grid. There are n M&M candies on the grid, the i-th M&M is currently located at (x_i + 0.5, y_i + 0.5), and has color c_i out of a total of k colors (the size of M&Ms are insignificant).Shrimpy Duc wants to steal a rectangle of M&Ms, specifically, he wants to select a rectangle with integer coordinates within the grid and steal all candies within the rectangle. Shrimpy Duc doesn't need to steal every single candy, however, he would like to steal at least one candy for each color.In other words, he wants to select a rectangle whose sides are parallel to the coordinate axes and whose left-bottom vertex (X_1, Y_1) and right-top vertex (X_2, Y_2) are points with integer coordinates satisfying 0 \le X_1 < X_2 \le L and 0 \le Y_1 < Y_2 \le L, so that for every color 1 \le c \le k there is at least one M&M with color c that lies within that rectangle.How many such rectangles are there? This number may be large, so you only need to find it modulo 10^9 + 7.InputThe first line contains three positive integers n, k, L (1 \leq k \leq n \leq 2 \cdot 10^3, 1 \leq L \leq 10^9 ) — the number of M&Ms, the number of colors and the length of the grid respectively.The following n points describe the M&Ms. Each line contains three integers x_i, y_i, c_i (0 \leq x_i, y_i < L, 1 \le c_i \le k) — the coordinates and color of the i-th M&M respectively. Different M&Ms have different coordinates (x_i \ne x_j or y_i \ne y_j for every i \ne j), and for every 1 \le c \le k there is at least one M&M with color c.OutputOutput a single integer — the number of rectangles satisfying Shrimpy Duc's conditions, modulo 10^9 + 7.ExamplesInput
4 2 4
3 2 2
3 1 1
1 1 1
1 2 1
Output
20
Input
5 3 10
6 5 3
5 3 1
7 9 1
2 3 2
5 0 2
Output
300
Input
10 4 10
5 4 4
0 0 3
6 0 1
3 9 2
8 7 1
8 1 3
2 1 3
6 3 2
3 5 3
4 3 4
Output
226
NoteGrid for the first sample: | 4 2 4
3 2 2
3 1 1
1 1 1
1 2 1
| 20 | 4 seconds | 512 megabytes | ['data structures', 'sortings', 'two pointers', '*3300'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.