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
|
---|---|---|---|---|---|
C. Save More Micetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are one cat, k mice, and one hole on a coordinate line. The cat is located at the point 0, the hole is located at the point n. All mice are located between the cat and the hole: the i-th mouse is located at the point x_i (0 < x_i < n). At each point, many mice can be located.In one second, the following happens. First, exactly one mouse moves to the right by 1. If the mouse reaches the hole, it hides (i.e. the mouse will not any more move to any point and will not be eaten by the cat). Then (after that the mouse has finished its move) the cat moves to the right by 1. If at the new cat's position, some mice are located, the cat eats them (they will not be able to move after that). The actions are performed until any mouse hasn't been hidden or isn't eaten.In other words, the first move is made by a mouse. If the mouse has reached the hole, it's saved. Then the cat makes a move. The cat eats the mice located at the pointed the cat has reached (if the cat has reached the hole, it eats nobody).Each second, you can select a mouse that will make a move. What is the maximum number of mice that can reach the hole without being eaten?InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.Each test case consists of two lines. The first line contains two integers n and k (2 \le n \le 10^9, 1 \le k \le 4 \cdot 10^5). The second line contains k integers x_1, x_2, \dots x_k (1 \le x_i < n) — the initial coordinates of the mice.It is guaranteed that the sum of all k given in the input doesn't exceed 4 \cdot 10^5.OutputFor each test case output on a separate line an integer m (m \ge 0) — the maximum number of mice that can reach the hole without being eaten.ExampleInput
3
10 6
8 7 5 4 9 4
2 8
1 1 1 1 1 1 1 1
12 11
1 2 3 4 5 6 7 8 9 10 11
Output
3
1
4
| 3
10 6
8 7 5 4 9 4
2 8
1 1 1 1 1 1 1 1
12 11
1 2 3 4 5 6 7 8 9 10 11
| 3 1 4 | 4 seconds | 256 megabytes | ['binary search', 'greedy', 'greedy', '*1000'] |
B. Make it Divisible by 25time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is given a positive integer n. In 1 move, one can select any single digit and remove it (i.e. one selects some position in the number and removes the digit located at this position). The operation cannot be performed if only one digit remains. If the resulting number contains leading zeroes, they are automatically removed.E.g. if one removes from the number 32925 the 3-rd digit, the resulting number will be 3225. If one removes from the number 20099050 the first digit, the resulting number will be 99050 (the 2 zeroes going next to the first digit are automatically removed).What is the minimum number of steps to get a number such that it is divisible by 25 and positive? It is guaranteed that, for each n occurring in the input, the answer exists. It is guaranteed that the number n has no leading zeros.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.Each test case consists of one line containing one integer n (25 \le n \le 10^{18}). It is guaranteed that, for each n occurring in the input, the answer exists. It is guaranteed that the number n has no leading zeros.OutputFor each test case output on a separate line an integer k (k \ge 0) — the minimum number of steps to get a number such that it is divisible by 25 and positive.ExampleInput
5
100
71345
3259
50555
2050047
Output
0
3
1
3
2
NoteIn the first test case, it is already given a number divisible by 25.In the second test case, we can remove the digits 1, 3, and 4 to get the number 75.In the third test case, it's enough to remove the last digit to get the number 325.In the fourth test case, we can remove the three last digits to get the number 50.In the fifth test case, it's enough to remove the digits 4 and 7. | 5
100
71345
3259
50555
2050047
| 0 3 1 3 2 | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'greedy', 'math', 'math', '*900'] |
A. Electionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe elections in which three candidates participated have recently ended. The first candidate received a votes, the second one received b votes, the third one received c votes. For each candidate, solve the following problem: how many votes should be added to this candidate so that he wins the election (i.e. the number of votes for this candidate was strictly greater than the number of votes for any other candidate)?Please note that for each candidate it is necessary to solve this problem independently, i.e. the added votes for any candidate do not affect the calculations when getting the answer for the other two candidates.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.Each test case consists of one line containing three integers a, b, and c (0 \le a,b,c \le 10^9).OutputFor each test case, output in a separate line three integers A, B, and C (A, B, C \ge 0) separated by spaces — the answers to the problem for the first, second, and third candidate, respectively.ExampleInput
5
0 0 0
10 75 15
13 13 17
1000 0 0
0 1000000000 0
Output
1 1 1
66 0 61
5 5 0
0 1001 1001
1000000001 0 1000000001
| 5
0 0 0
10 75 15
13 13 17
1000 0 0
0 1000000000 0
| 1 1 1 66 0 61 5 5 0 0 1001 1001 1000000001 0 1000000001 | 1 second | 256 megabytes | ['math', '*800'] |
F2. Alice and Recoloring 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe difference between the versions is in the costs of operations. Solution for one version won't work for another!Alice has a grid of size n \times m, initially all its cells are colored white. The cell on the intersection of i-th row and j-th column is denoted as (i, j). Alice can do the following operations with this grid:Choose any subrectangle containing cell (1, 1), and flip the colors of all its cells. (Flipping means changing its color from white to black or from black to white). This operation costs 1 coin.Choose any subrectangle containing cell (n, 1), and flip the colors of all its cells. This operation costs 3 coins.Choose any subrectangle containing cell (1, m), and flip the colors of all its cells. This operation costs 4 coins.Choose any subrectangle containing cell (n, m), and flip the colors of all its cells. This operation costs 2 coins. As a reminder, subrectangle is a set of all cells (x, y) with x_1 \le x \le x_2, y_1 \le y \le y_2 for some 1 \le x_1 \le x_2 \le n, 1 \le y_1 \le y_2 \le m.Alice wants to obtain her favorite coloring with these operations. What's the smallest number of coins that she would have to spend? It can be shown that it's always possible to transform the initial grid into any other.InputThe first line of the input contains 2 integers n, m (1 \le n, m \le 500) — the dimensions of the grid.The i-th of the next n lines contains a string s_i of length m, consisting of letters W and B. The j-th character of string s_i is W if the cell (i, j) is colored white in the favorite coloring of Alice, and B if it's colored black.OutputOutput the smallest number of coins Alice would have to spend to achieve her favorite coloring.ExamplesInput
3 3
WWW
WBB
WBB
Output
2
Input
10 15
WWWBBBWBBBBBWWW
BBBBWWWBBWWWBBB
BBBWWBWBBBWWWBB
BBWBWBBWWWBBWBW
BBBBWWWBBBWWWBB
BWBBWWBBBBBBWWW
WBWWBBBBWWBBBWW
WWBWWWWBBWWBWWW
BWBWWBWWWWWWBWB
BBBWBWBWBBBWWBW
Output
68
NoteIn the first sample, it's optimal to just apply the fourth operation once to the rectangle containing cells (2, 2), (2, 3), (3, 2), (3, 3). This would cost 2 coins. | 3 3
WWW
WBB
WBB
| 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'flows', 'graph matchings', 'greedy', '*2800'] |
F1. Alice and Recoloring 1time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe difference between the versions is in the costs of operations. Solution for one version won't work for another!Alice has a grid of size n \times m, initially all its cells are colored white. The cell on the intersection of i-th row and j-th column is denoted as (i, j). Alice can do the following operations with this grid:Choose any subrectangle containing cell (1, 1), and flip the colors of all its cells. (Flipping means changing its color from white to black or from black to white). This operation costs 1 coin.Choose any subrectangle containing cell (n, 1), and flip the colors of all its cells. This operation costs 2 coins.Choose any subrectangle containing cell (1, m), and flip the colors of all its cells. This operation costs 4 coins.Choose any subrectangle containing cell (n, m), and flip the colors of all its cells. This operation costs 3 coins. As a reminder, subrectangle is a set of all cells (x, y) with x_1 \le x \le x_2, y_1 \le y \le y_2 for some 1 \le x_1 \le x_2 \le n, 1 \le y_1 \le y_2 \le m.Alice wants to obtain her favorite coloring with these operations. What's the smallest number of coins that she would have to spend? It can be shown that it's always possible to transform the initial grid into any other.InputThe first line of the input contains 2 integers n, m (1 \le n, m \le 500) — the dimensions of the grid.The i-th of the next n lines contains a string s_i of length m, consisting of letters W and B. The j-th character of string s_i is W if the cell (i, j) is colored white in the favorite coloring of Alice, and B if it's colored black.OutputOutput the smallest number of coins Alice would have to spend to achieve her favorite coloring.ExamplesInput
3 3
WWW
WBB
WBB
Output
3
Input
10 15
WWWBBBWBBBBBWWW
BBBBWWWBBWWWBBB
BBBWWBWBBBWWWBB
BBWBWBBWWWBBWBW
BBBBWWWBBBWWWBB
BWBBWWBBBBBBWWW
WBWWBBBBWWBBBWW
WWBWWWWBBWWBWWW
BWBWWBWWWWWWBWB
BBBWBWBWBBBWWBW
Output
74
NoteIn the first sample, it's optimal to just apply the fourth operation once to the rectangle containing cells (2, 2), (2, 3), (3, 2), (3, 3). This would cost 3 coins. | 3 3
WWW
WBB
WBB
| 3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', '*2600'] |
E. Bored Bakrytime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBakry got bored of solving problems related to xor, so he asked you to solve this problem for him.You are given an array a of n integers [a_1, a_2, \ldots, a_n].Let's call a subarray a_{l}, a_{l+1}, a_{l+2}, \ldots, a_r good if a_l \, \& \, a_{l+1} \, \& \, a_{l+2} \, \ldots \, \& \, a_r > a_l \oplus a_{l+1} \oplus a_{l+2} \ldots \oplus a_r, where \oplus denotes the bitwise XOR operation and \& denotes the bitwise AND operation.Find the length of the longest good subarray of a, or determine that no such subarray exists.InputThe first line contains a single integer n (1 \le n \le 10^6) — the length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^6) — elements of the array.OutputPrint a single integer — the length of the longest good subarray. If there are no good subarrays, print 0.ExamplesInput
2
5 6
Output
2
Input
3
2 4 3
Output
0
Input
6
8 1 3 3 1 2
Output
4
NoteIn the first case, the answer is 2, as the whole array is good: 5 \& 6 = 4 > 5 \oplus 6 = 3.In the third case, the answer is 4, and one of the longest good subarrays is [a_2, a_3, a_4, a_5]: 1\& 3 \& 3 \&1 = 1 > 1\oplus 3 \oplus 3\oplus 1 = 0. | 2
5 6
| 2 | 4 seconds | 256 megabytes | ['bitmasks', 'greedy', 'math', 'two pointers', '*2400'] |
D. Hemose in ICPC ?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem!In the last regional contest Hemose, ZeyadKhattab and YahiaSherif — members of the team Carpe Diem — did not qualify to ICPC because of some unknown reasons. Hemose was very sad and had a bad day after the contest, but ZeyadKhattab is very wise and knows Hemose very well, and does not want to see him sad.Zeyad knows that Hemose loves tree problems, so he gave him a tree problem with a very special device.Hemose has a weighted tree with n nodes and n-1 edges. Unfortunately, Hemose doesn't remember the weights of edges.Let's define Dist(u, v) for u\neq v as the greatest common divisor of the weights of all edges on the path from node u to node v.Hemose has a special device. Hemose can give the device a set of nodes, and the device will return the largest Dist between any two nodes from the set. More formally, if Hemose gives the device a set S of nodes, the device will return the largest value of Dist(u, v) over all pairs (u, v) with u, v \in S and u \neq v.Hemose can use this Device at most 12 times, and wants to find any two distinct nodes a, b, such that Dist(a, b) is maximum possible. Can you help him?InteractionBegin the interaction from reading a single integer n (2 \le n \le 10^3) — the number of nodes in the tree.Next, read n-1 lines. The i-th of the next n-1 lines contains two integers u_i and v_i (1 \leq u_i, v_i \leq n, u_i\neq v_i), which means that there's an edge between nodes u_i and v_i.It's guaranteed that weights of edges were \leq 10^9.It is guaranteed that the given graph is a tree.Now you may begin asking queries. To ask a query about a set of k nodes v_1, v_2, \ldots, v_k (2 \le k \le n, 1 \le v_i \le n, all v_i are distinct), output: ? k v_1 v_2 \ldots v_kYou will then receive an integer x, the largest Dist(v_i, v_j) over 1 \le i, j \le k with i \neq j.When you have found a and b (1 \le a, b \le n), a\neq b) such that Dist(a, b) is the maximum possible, print the answer in the following format: ! a b Outputting answer doesn't count towards the limit of 12 queries.If there are several pairs (a, b) with the same largest Dist(a, b), you can output any.After printing a query do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack a solution, use the following format.The first line should contain a single integer n (2 \leq n \le 10^3) — the number of nodes.The i-th of the next n-1 lines should contain three integers u_i, v_i, w_i (1 \le u_i, v_i \le n, u_i\ne v_i, 1 \le w \le 10^9), which means that there's an edge between nodes u_i and v_i with weight w_i.These n-1 edges must form a tree.ExampleInput
6
1 2
2 3
2 4
1 5
5 6
10
2
10Output
? 6 1 2 3 4 5 6
? 3 3 1 5
? 2 1 2
! 1 2NoteThe tree in the first sample: | 6
1 2
2 3
2 4
1 5
5 6
10
2
10 | ? 6 1 2 3 4 5 6 ? 3 3 1 5 ? 2 1 2 ! 1 2 | 1 second | 256 megabytes | ['binary search', 'dfs and similar', 'implementation', 'interactive', 'math', 'number theory', 'trees', '*2300'] |
C. Bakry and Partitioningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBakry faced a problem, but since he's lazy to solve it, he asks for your help.You are given a tree of n nodes, the i-th node has value a_i assigned to it for each i from 1 to n. As a reminder, a tree on n nodes is a connected graph with n-1 edges.You want to delete at least 1, but at most k-1 edges from the tree, so that the following condition would hold:For every connected component calculate the bitwise XOR of the values of the nodes in it. Then, these values have to be the same for all connected components.Is it possible to achieve this condition?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 5 \cdot 10^4). Description of the test cases follows.The first line of each test case contains two integers n and k (2 \leq k \leq n \leq 10^5).The second line of each test case contains n integers a_1, a_2, ..., a_n (1 \leq a_i \leq 10^9).The i-th of the next n-1 lines contains two integers u_i and v_i (1 \leq u_i, v_i \leq n, u_i\neq v_i), which means that there's an edge between nodes u_i and v_i.It is guaranteed that the given graph is a tree.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, you should output a single string. If you can delete the edges according to the conditions written above, output "YES" (without quotes). Otherwise, output "NO" (without quotes).You can print each letter of "YES" and "NO" in any case (upper or lower).ExampleInput
5
2 2
1 3
1 2
5 5
3 3 3 3 3
1 2
2 3
1 4
4 5
5 2
1 7 2 3 5
1 2
2 3
1 4
4 5
5 3
1 6 4 1 2
1 2
2 3
1 4
4 5
3 3
1 7 4
1 2
2 3
Output
NO
YES
NO
YES
NO
NoteIt can be shown that the objection is not achievable for first, third, and fifth test cases.In the second test case, you can just remove all the edges. There will be 5 connected components, each containing only one node with value 3, so the bitwise XORs will be 3 for all of them.In the fourth test case, this is the tree: .You can remove an edge (4,5)The bitwise XOR of the first component will be, a_1 \oplus a_2 \oplus a_3 \oplus a_4 = 1 \oplus 6 \oplus 4 \oplus 1 = 2 (where \oplus denotes the bitwise XOR). The bitwise XOR of the second component will be, a_5 = 2. | 5
2 2
1 3
1 2
5 5
3 3 3 3 3
1 2
2 3
1 4
4 5
5 2
1 7 2 3 5
1 2
2 3
1 4
4 5
5 3
1 6 4 1 2
1 2
2 3
1 4
4 5
3 3
1 7 4
1 2
2 3
| NO YES NO YES NO | 1 second | 256 megabytes | ['bitmasks', 'constructive algorithms', 'dfs and similar', 'dp', 'graphs', 'trees', '*1700'] |
B. Hemose Shoppingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHemose was shopping with his friends Samez, AhmedZ, AshrafEzz, TheSawan and O_E in Germany. As you know, Hemose and his friends are problem solvers, so they are very clever. Therefore, they will go to all discount markets in Germany.Hemose has an array of n integers. He wants Samez to sort the array in the non-decreasing order. Since it would be a too easy problem for Samez, Hemose allows Samez to use only the following operation:Choose indices i and j such that 1 \le i, j \le n, and \lvert i - j \rvert \geq x. Then, swap elements a_i and a_j.Can you tell Samez if there's a way to sort the array in the non-decreasing order by using the operation written above some finite number of times (possibly 0)?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^5). Description of the test cases follows.The first line of each test case contains two integers n and x (1 \leq x \leq n \leq 10^5).The second line of each test case contains n integers a_1, a_2, ..., a_n (1 \leq a_i \leq 10^9).It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, you should output a single string. If Samez can sort the array in non-decreasing order using the operation written above, output "YES" (without quotes). Otherwise, output "NO" (without quotes).You can print each letter of "YES" and "NO" in any case (upper or lower).ExampleInput
4
3 3
3 2 1
4 3
1 2 3 4
5 2
5 1 2 3 4
5 4
1 2 3 4 4
Output
NO
YES
YES
YES
NoteIn the first test case, you can't do any operations.In the second test case, the array is already sorted.In the third test case, you can do the operations as follows: [5,1,2,3,4], swap(a_1,a_3) [2,1,5,3,4], swap(a_2,a_5) [2,4,5,3,1], swap(a_2,a_4) [2,3,5,4,1], swap(a_1,a_5) [1,3,5,4,2], swap(a_2,a_5) [1,2,5,4,3], swap(a_3,a_5) [1,2,3,4,5] (Here swap(a_i, a_j) refers to swapping elements at positions i, j). | 4
3 3
3 2 1
4 3
1 2 3 4
5 2
5 1 2 3 4
5 4
1 2 3 4 4
| NO YES YES YES | 1 second | 256 megabytes | ['constructive algorithms', 'dsu', 'math', 'sortings', '*1200'] |
A. Gamer Hemosetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, Ahmed_Hossam went to Hemose and said "Let's solve a gym contest!". Hemose didn't want to do that, as he was playing Valorant, so he came up with a problem and told it to Ahmed to distract him. Sadly, Ahmed can't solve it... Could you help him?There is an Agent in Valorant, and he has n weapons. The i-th weapon has a damage value a_i, and the Agent will face an enemy whose health value is H.The Agent will perform one or more moves until the enemy dies.In one move, he will choose a weapon and decrease the enemy's health by its damage value. The enemy will die when his health will become less than or equal to 0. However, not everything is so easy: the Agent can't choose the same weapon for 2 times in a row.What is the minimum number of times that the Agent will need to use the weapons to kill the enemy?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^5). Description of the test cases follows.The first line of each test case contains two integers n and H (2 \leq n \leq 10^3, 1 \leq H \leq 10^9) — the number of available weapons and the initial health value of the enemy.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the damage values of the weapons.It's guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the minimum number of times that the Agent will have to use the weapons to kill the enemy.ExampleInput
3
2 4
3 7
2 6
4 2
3 11
2 1 7
Output
1
2
3
NoteIn the first test case, the Agent can use the second weapon, making health value of the enemy equal to 4-7=-3. -3 \le 0, so the enemy is dead, and using weapon 1 time was enough.In the second test case, the Agent can use the first weapon first, and then the second one. After this, the health of enemy will drop to 6-4-2 = 0, meaning he would be killed after using weapons 2 times.In the third test case, the Agent can use the weapons in order (third, first, third), decreasing the health value of enemy to 11 - 7 - 2 - 7 = -5 after using the weapons 3 times. Note that we can't kill the enemy by using the third weapon twice, as even though 11-7-7<0, it's not allowed to use the same weapon twice in a row. | 3
2 4
3 7
2 6
4 2
3 11
2 1 7
| 1 2 3 | 1 second | 256 megabytes | ['binary search', 'greedy', 'math', 'sortings', '*800'] |
F. Jumping Through the Arraytime limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array of integers a of size n and a permutation p of size n. There are q queries of three types coming to you: For given numbers l and r, calculate the sum in array a on the segment from l to r: \sum\limits_{i=l}^{r} a_i. You are given two numbers v and x. Let's build a directed graph from the permutation p: it has n vertices and n edges i \to p_i. Let C be the set of vertices that are reachable from v in this graph. You should add x to all a_u such that u is in C. You are given indices i and j. You should swap p_i and p_j. The graph corresponding to the permutation [2, 3, 1, 5, 4]. Please, process all queries and print answers to queries of type 1.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the size of the array and permutation.The second line contains n integers a_1, a_2, \ldots, a_n (-10^8 \le a_i \le 10^8).The third line contains n distinct integers p_1, p_2, \ldots, p_n (1 \le p_i \le n).The fourth line contains a single integer q — the number of queries (1 \le q \le 2 \cdot 10^5).Next q lines contain description of queries. The i-th of them starts with an integer t_i (1 \le t_i \le 3) — the query type. If t_i = 1, then the i-th line also contains two integers l, r (1 \le l \le r \le n). If t_i = 2, then the i-th line also contains two integers v, x (1 \le v \le n, -10^8 \le x \le 10^8). If t_i = 3, then the i-th line also contains also two integers i, j (1 \le i, j \le n). OutputFor every first type query, print a single integer — the answer to this query.ExamplesInput
5
6 9 -5 3 0
2 3 1 5 4
6
1 1 5
2 1 1
1 1 5
3 1 5
2 1 -1
1 1 5
Output
13
16
11
Input
8
-15 52 -4 3 5 9 0 5
2 4 6 8 1 3 5 7
10
2 2 2
2 5 -1
1 1 8
1 1 5
1 5 8
3 1 6
2 1 50
1 1 8
2 6 -20
1 1 8
Output
61
45
22
461
301
Input
1
1
1
1
1 1 1
Output
1
NoteIn the first example: The graph corresponding to the initial permutation. There are 6 queries. The sum on the segment from 1 to 5 is a_1 + a_2 + a_3 + a_4 + a_5 = 6 + 9 + (-5) + 3 + 0 = 13. If we start from 1, we can reach \{1, 2, 3\}. After this query a is: [7, 10, -4, 3, 0]. The sum on the segment from 1 to 5 is a_1 + a_2 + a_3 + a_4 + a_5 = 6 + 9 + (-5) + 3 + 0 = 16. After this query p = [4, 3, 1, 5, 2]. The graph corresponding to the new permutation. If we start from 2, we can reach \{1, 2, 3, 4, 5\}. After this query a is: [6, 9, -5, 2, -1]. The sum on the segment from 1 to 5 is a_1 + a_2 + a_3 + a_4 + a_5 = 6 + 9 + (-5) + 2 + (-1) = 11. | 5
6 9 -5 3 0
2 3 1 5 4
6
1 1 5
2 1 1
1 1 5
3 1 5
2 1 -1
1 1 5
| 13 16 11 | 8 seconds | 512 megabytes | ['binary search', 'data structures', 'graphs', 'two pointers', '*3500'] |
I. Omkar and Mosaictime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOmkar is creating a mosaic using colored square tiles, which he places in an n \times n grid. When the mosaic is complete, each cell in the grid will have either a glaucous or sinoper tile. However, currently he has only placed tiles in some cells. A completed mosaic will be a mastapeece if and only if each tile is adjacent to exactly 2 tiles of the same color (2 tiles are adjacent if they share a side.) Omkar wants to fill the rest of the tiles so that the mosaic becomes a mastapeece. Now he is wondering, is the way to do this unique, and if it is, what is it?InputThe first line contains a single integer n (1 \leq n \leq 2000).Then follow n lines with n characters in each line. The i-th character in the j-th line corresponds to the cell in row i and column j of the grid, and will be S if Omkar has placed a sinoper tile in this cell, G if Omkar has placed a glaucous tile, . if it's empty. OutputOn the first line, print UNIQUE if there is a unique way to get a mastapeece, NONE if Omkar cannot create any, and MULTIPLE if there is more than one way to do so. All letters must be uppercase.If you print UNIQUE, then print n additional lines with n characters in each line, such that the i-th character in the j^{\text{th}} line is S if the tile in row i and column j of the mastapeece is sinoper, and G if it is glaucous. ExamplesInput
4
S...
..G.
....
...S
Output
MULTIPLE
Input
6
S.....
....G.
..S...
.....S
....G.
G.....
Output
NONE
Input
10
.S....S...
..........
...SSS....
..........
..........
...GS.....
....G...G.
..........
......G...
..........
Output
UNIQUE
SSSSSSSSSS
SGGGGGGGGS
SGSSSSSSGS
SGSGGGGSGS
SGSGSSGSGS
SGSGSSGSGS
SGSGGGGSGS
SGSSSSSSGS
SGGGGGGGGS
SSSSSSSSSS
Input
1
.
Output
NONE
NoteFor the first test case, Omkar can make the mastapeecesSSSSSGGSSGGSSSSSand SSGGSSGGGGSSGGSS.For the second test case, it can be proven that it is impossible for Omkar to add tiles to create a mastapeece.For the third case, it can be proven that the given mastapeece is the only mastapeece Omkar can create by adding tiles.For the fourth test case, it's clearly impossible for the only tile in any mosaic Omkar creates to be adjacent to two tiles of the same color, as it will be adjacent to 0 tiles total. | 4
S...
..G.
....
...S
| MULTIPLE | 2 seconds | 256 megabytes | ['combinatorics', 'constructive algorithms', 'math', '*3500'] |
G. Poacherstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are two poachers who cut trees in a forest.A forest is a set of zero or more trees. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a node v is the next vertex on the shortest path from v to the root. Children of vertex v are all nodes for which v is the parent. A vertex is a leaf if it has no children.In this problem we define the depth of vertex as number of vertices on the simple path from this vertex to the root. The rank of a tree is the minimum depth among its leaves.Initially there is a forest of rooted trees. Alice and Bob play a game on this forest. They play alternating turns with Alice going first. At the beginning of their turn, the player chooses a tree from the forest. Then the player chooses a positive cutting depth, which should not exceed the rank of the chosen tree. Then the player removes all vertices of that tree whose depth is less that or equal to the cutting depth. All other vertices of the tree form a set of rooted trees with root being the vertex with the smallest depth before the cut. All these trees are included in the game forest and the game continues.A player loses if the forest is empty at the beginning of his move.You are to determine whether Alice wins the game if both players play optimally.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 5 \cdot 10^5). Description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 5 \cdot 10^5) — total number of vertices in the initial forest.The second line contains n integers p_1, p_2, \ldots, p_n (0 \leq p_i \leq n) — description of the forest. If p_i = 0, then the i-th vertex is the root of a tree, otherwise p_i is the parent of the vertex i. It's guaranteed that p defines a correct forest of rooted trees.It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^5.OutputFor each test case, print "YES" (without quotes) if Alice wins, otherwise print "NO" (without quotes). You can print each letter in any case (upper or lower).ExampleInput
4
4
0 1 0 3
7
0 1 2 0 4 5 6
4
0 1 1 2
7
0 1 1 2 2 3 3
Output
NO
YES
NO
YES
NoteIn the first test case Bob has a symmetric strategy, so Alice cannot win.In the second test case Alice can choose the second tree and cutting depth 1 to get a forest on which she has a symmetric strategy.In third test case the rank of the only tree is 2 and both possible moves for Alice result in a loss. Bob either can make the forest with a symmetric strategy for himself, or clear the forest.In the fourth test case all leafs have the same depth, so Alice can clear the forest in one move. | 4
4
0 1 0 3
7
0 1 2 0 4 5 6
4
0 1 1 2
7
0 1 1 2 2 3 3
| NO YES NO YES | 1.5 seconds | 256 megabytes | ['dp', 'games', 'graphs', 'trees', '*2500'] |
F. Non-equal Neighbourstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array of n positive integers a_1, a_2, \ldots, a_n. Your task is to calculate the number of arrays of n positive integers b_1, b_2, \ldots, b_n such that: 1 \le b_i \le a_i for every i (1 \le i \le n), and b_i \neq b_{i+1} for every i (1 \le i \le n - 1). The number of such arrays can be very large, so print it modulo 998\,244\,353.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the array a.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).OutputPrint the answer modulo 998\,244\,353 in a single line.ExamplesInput
3
2 2 2
Output
2Input
2
2 3
Output
4Input
3
1 1 1
Output
0NoteIn the first test case possible arrays are [1, 2, 1] and [2, 1, 2].In the second test case possible arrays are [1, 2], [1, 3], [2, 1] and [2, 3]. | 3
2 2 2
| 2 | 3 seconds | 512 megabytes | ['combinatorics', 'dp', 'math', '*2400'] |
E. Frequency Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPetya has a rooted tree with an integer written on each vertex. The vertex 1 is the root. You are to answer some questions about the tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a node v is the next vertex on the shortest path from v to the root.Each question is defined by three integers v, l, and k. To get the answer to the question, you need to perform the following steps: First, write down the sequence of all integers written on the shortest path from the vertex v to the root (including those written in the v and the root). Count the number of times each integer occurs. Remove all integers with less than l occurrences. Replace the sequence, removing all duplicates and ordering the elements by the number of occurrences in the original list in increasing order. In case of a tie, you can choose the order of these elements arbitrary. The answer to the question is the k-th number in the remaining sequence. Note that the answer is not always uniquely determined, because there could be several orderings. Also, it is possible that the length of the sequence on this step is less than k, in this case the answer is -1. For example, if the sequence of integers on the path from v to the root is [2, 2, 1, 7, 1, 1, 4, 4, 4, 4], l = 2 and k = 2, then the answer is 1.Please answer all questions about the tree.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^6). Description of the test cases follows.The first line of each test case contains two integers n, q (1 \leq n, q \leq 10^6) — the number of vertices in the tree and the number of questions.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq n), where a_i is the number written on the i-th vertex.The third line contains n-1 integers p_2, p_3, \ldots, p_n (1 \leq p_i \leq n), where p_i is the parent of node i. It's guaranteed that the values p define a correct tree.Each of the next q lines contains three integers v, l, k (1 \leq v, l, k \leq n) — descriptions of questions.It is guaranteed that the sum of n and the sum of q over all test cases do not exceed 10^6.OutputFor each question of each test case print the answer to the question. In case of multiple answers, print any.ExampleInput
2
3 3
1 1 1
1 2
3 1 1
3 1 2
3 2 1
5 5
1 2 1 1 2
1 1 2 2
3 1 1
2 1 2
4 1 1
4 2 1
4 2 2
Output
1 -1 1
1 1 2 1 -1
| 2
3 3
1 1 1
1 2
3 1 1
3 1 2
3 2 1
5 5
1 2 1 1 2
1 1 2 2
3 1 1
2 1 2
4 1 1
4 2 1
4 2 2
| 1 -1 1 1 1 2 1 -1 | 4 seconds | 512 megabytes | ['data structures', 'dfs and similar', 'trees', '*2400'] |
D. Yet Another Sorting Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has an array of integers a_1, a_2, \ldots, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 \leq i, j, k \leq n) and apply i \to j \to k \to i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 5 \cdot 10^5). Description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 5 \cdot 10^5) — the length of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq n).It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^5.OutputFor each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).ExampleInput
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
NoteIn the 6-th test case Petya can use the 3-cycle 1 \to 3 \to 2 \to 1 to sort the array.In the 7-th test case Petya can apply 1 \to 3 \to 2 \to 1 and make a = [1, 4, 2, 3]. Then he can apply 2 \to 4 \to 3 \to 2 and finally sort the array. | 7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
| YES YES NO YES NO YES YES | 2 seconds | 256 megabytes | ['data structures', 'math', '*1900'] |
C. Minimize Distancetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA total of n depots are located on a number line. Depot i lies at the point x_i for 1 \le i \le n.You are a salesman with n bags of goods, attempting to deliver one bag to each of the n depots. You and the n bags are initially at the origin 0. You can carry up to k bags at a time. You must collect the required number of goods from the origin, deliver them to the respective depots, and then return to the origin to collect your next batch of goods.Calculate the minimum distance you need to cover to deliver all the bags of goods to the depots. You do not have to return to the origin after you have delivered all the bags.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10\,500). Description of the test cases follows.The first line of each test case contains two integers n and k (1 \le k \le n \le 2 \cdot 10^5).The second line of each test case contains n integers x_1, x_2, \ldots, x_n (-10^9 \le x_i \le 10^9). It is possible that some depots share the same position.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer denoting the minimum distance you need to cover to deliver all the bags of goods to the depots. ExampleInput
4
5 1
1 2 3 4 5
9 3
-5 -10 -15 6 5 8 3 7 4
5 3
2 2 3 3 3
4 2
1000000000 1000000000 1000000000 1000000000
Output
25
41
7
3000000000
NoteIn the first test case, you can carry only one bag at a time. Thus, the following is a solution sequence that gives a minimum travel distance: 0 \to 2 \to 0 \to 4 \to 0 \to 3 \to 0 \to 1 \to 0 \to 5, where each 0 means you go the origin and grab one bag, and each positive integer means you deliver the bag to a depot at this coordinate, giving a total distance of 25 units. It must be noted that there are other sequences that give the same distance.In the second test case, you can follow the following sequence, among multiple such sequences, to travel minimum distance: 0 \to 6 \to 8 \to 7 \to 0 \to 5 \to 4 \to 3 \to 0 \to (-5) \to (-10) \to (-15), with distance 41. It can be shown that 41 is the optimal distance for this test case. | 4
5 1
1 2 3 4 5
9 3
-5 -10 -15 6 5 8 3 7 4
5 3
2 2 3 3 3
4 2
1000000000 1000000000 1000000000 1000000000
| 25 41 7 3000000000 | 1 second | 256 megabytes | ['greedy', '*1300'] |
B. Array Eversiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n.Let's define the eversion operation. Let x = a_n. Then array a is partitioned into two parts: left and right. The left part contains the elements of a that are not greater than x (\le x). The right part contains the elements of a that are strictly greater than x (> x). The order of elements in each part is kept the same as before the operation, i. e. the partition is stable. Then the array is replaced with the concatenation of the left and the right parts.For example, if the array a is [2, 4, 1, 5, 3], the eversion goes like this: [2, 4, 1, 5, 3] \to [2, 1, 3], [4, 5] \to [2, 1, 3, 4, 5].We start with the array a and perform eversions on this array. We can prove that after several eversions the array a stops changing. Output the minimum number k such that the array stops changing after k eversions.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line contains a single integer n (1 \le n \le 2 \cdot 10^5).The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print a single integer k — the number of eversions after which the array stops changing.ExampleInput
3
5
2 4 1 5 3
5
5 3 2 4 1
4
1 1 1 1
Output
1
2
0
NoteConsider the fist example. The first eversion: a = [1, 4, 2, 5, 3], x = 3. [2, 4, 1, 5, 3] \to [2, 1, 3], [4, 5] \to [2, 1, 3, 4, 5]. The second and following eversions: a = [2, 1, 3, 4, 5], x = 5. [2, 1, 3, 4, 5] \to [2, 1, 3, 4, 5], [] \to [2, 1, 3, 4, 5]. This eversion does not change the array, so the answer is 1. Consider the second example. The first eversion: a = [5, 3, 2, 4, 1], x = 1. [5, 3, 2, 4, 1] \to [1], [5, 3, 2, 4] \to [1, 5, 3, 2, 4]. The second eversion: a = [1, 5, 3, 2, 4], x = 4. [1, 5, 3, 2, 4] \to [1, 3, 2, 4], [5] \to [1, 3, 2, 4, 5]. The third and following eversions: a = [1, 3, 2, 4, 5], x = 5. [1, 3, 2, 4, 5] \to [1, 3, 2, 4, 5], [] \to [1, 3, 2, 4, 5]. This eversion does not change the array, so the answer is 2. | 3
5
2 4 1 5 3
5
5 3 2 4 1
4
1 1 1 1
| 1 2 0 | 1 second | 256 megabytes | ['greedy', '*900'] |
A. Life of a Flowertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has got an interesting flower. Petya is a busy person, so he sometimes forgets to water it. You are given n days from Petya's live and you have to determine what happened with his flower in the end.The flower grows as follows: If the flower isn't watered for two days in a row, it dies. If the flower is watered in the i-th day, it grows by 1 centimeter. If the flower is watered in the i-th and in the (i-1)-th day (i > 1), then it grows by 5 centimeters instead of 1. If the flower is not watered in the i-th day, it does not grow. At the beginning of the 1-st day the flower is 1 centimeter tall. What is its height after n days?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line of each test case contains the only integer n (1 \leq n \leq 100).The second line of each test case contains n integers a_1, a_2, \dots, a_n (a_i = 0 or a_i = 1). If a_i = 1, the flower is watered in the i-th day, otherwise it is not watered.OutputFor each test case print a single integer k — the flower's height after n days, or -1, if the flower dies.ExampleInput
4
3
1 0 1
3
0 1 1
4
1 0 0 1
1
0
Output
3
7
-1
1
| 4
3
1 0 1
3
0 1 1
4
1 0 0 1
1
0
| 3 7 -1 1 | 1 second | 256 megabytes | ['implementation', '*800'] |
G. Eligible Segmentstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n distinct points p_1, p_2, \ldots, p_n on the plane and a positive integer R. Find the number of pairs of indices (i, j) such that 1 \le i < j \le n, and for every possible k (1 \le k \le n) the distance from the point p_k to the segment between points p_i and p_j is at most R.InputThe first line contains two integers n, R (1 \le n \le 3000, 1 \le R \le 10^5) — the number of points and the maximum distance between a point and a segment.Each of the next n lines contains two integers x_i, y_i (-10^5 \le x_i, y_i \le 10^5) that define the i-th point p_i=(x_i, y_i). All points are distinct.It is guaranteed that the answer does not change if the parameter R is changed by at most 10^{-2}.OutputPrint the number of suitable pairs (i, j).ExamplesInput
4 2
0 1
0 -1
3 0
-3 0
Output
1Input
3 3
1 -1
-1 -1
0 1
Output
3NoteIn the first example, the only pair of points (-3, 0), (3, 0) is suitable. The distance to the segment between these points from the points (0, 1) and (0, -1) is equal to 1, which is less than R=2.In the second example, all possible pairs of points are eligible. | 4 2
0 1
0 -1
3 0
-3 0
| 1 | 3 seconds | 256 megabytes | ['geometry', '*3200'] |
F. Strange LCStime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n strings s_1, s_2, \ldots, s_n, each consisting of lowercase and uppercase English letters. In addition, it's guaranteed that each character occurs in each string at most twice. Find the longest common subsequence of these strings.A string t is a subsequence of a string s if t can be obtained from s by deletion of several (possibly, zero or all) symbols.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 5) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (2 \leq n \leq 10) — the number of strings.Each of the next n lines contains the corresponding string s_i. Each s_i is non-empty, consists only of uppercase and lowercase English letters, and no character appears more than twice in each string.OutputFor each test case print the answer in two lines:In the first line print the length of the longest common subsequence. In the second line print the longest common subsequence. If there are multiple such subsequences, print any of them.ExampleInput
4
2
ABC
CBA
2
bacab
defed
3
abcde
aBcDe
ace
2
codeforces
technocup
Output
1
A
0
3
ace
3
coc
NoteIn the first test case, the longest common subsequence is "A". There are no common subsequences of length 2.In the second test case, sets of characters of strings don't intersect, so any non-empty string can't be a common subsequence. | 4
2
ABC
CBA
2
bacab
defed
3
abcde
aBcDe
ace
2
codeforces
technocup
| 1 A 0 3 ace 3 coc | 2 seconds | 256 megabytes | ['bitmasks', 'dp', 'graphs', 'greedy', 'strings', '*2600'] |
E. Game with Stonestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob decided to take a break from calculus homework and designed a game for himself. The game is played on a sequence of piles of stones, which can be described with a sequence of integers s_1, \ldots, s_k, where s_i is the number of stones in the i-th pile. On each turn, Bob picks a pair of non-empty adjacent piles i and i+1 and takes one stone from each. If a pile becomes empty, its adjacent piles do not become adjacent. The game ends when Bob can't make turns anymore. Bob considers himself a winner if at the end all piles are empty.We consider a sequence of piles winning if Bob can start with it and win with some sequence of moves.You are given a sequence a_1, \ldots, a_n, count the number of subsegments of a that describe a winning sequence of piles. In other words find the number of segments [l, r] (1 \leq l \leq r \leq n), such that the sequence a_l, a_{l+1}, \ldots, a_r is winning.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 3 \cdot 10^5) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 3 \cdot 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 10^9).It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputPrint a single integer for each test case — the answer to the problem.ExampleInput
6
2
2 2
3
1 2 3
4
1 1 1 1
4
1 2 2 1
4
1 2 1 2
8
1 2 1 2 1 2 1 2
Output
1
0
4
2
1
3
NoteIn the first test case, Bob can't win on subsegments of length 1, as there is no pair of adjacent piles in an array of length 1.In the second test case, every subsegment is not winning.In the fourth test case, the subsegment [1, 4] is winning, because Bob can make moves with pairs of adjacent piles: (2, 3), (1, 2), (3, 4). Another winning subsegment is [2, 3]. | 6
2
2 2
3
1 2 3
4
1 1 1 1
4
1 2 2 1
4
1 2 1 2
8
1 2 1 2 1 2 1 2
| 1 0 4 2 1 3 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'games', 'greedy', '*2300'] |
D. Guess the Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Jury initially had a sequence a of length n, such that a_i = i.The jury chose three integers i, j, k, such that 1 \leq i < j < k \leq n, j - i > 1. After that, Jury reversed subsegments [i, j - 1] and [j, k] of the sequence a.Reversing a subsegment [l, r] of the sequence a means reversing the order of elements a_l, a_{l+1}, \ldots, a_r in the sequence, i. e. a_l is swapped with a_r, a_{l+1} is swapped with a_{r-1}, etc.You are given the number n and you should find i, j, k after asking some questions.In one question you can choose two integers l and r (1 \leq l \leq r \leq n) and ask the number of inversions on the subsegment [l, r] of the sequence a. You will be given the number of pairs (i, j) such that l \leq i < j \leq r, and a_i > a_j.Find the chosen numbers i, j, k after at most 40 questions.The numbers i, j, and k are fixed before the start of your program and do not depend on your queries.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 100) — the number of test cases. Description of the test cases follows.The single line of each test case contains a single integer n (4 \leq n \leq 10^9). After reading it you should start an interaction process by asking questions for that test case. After giving an answer you should: Terminate your program if that is the last test case. Proceed to the next test case otherwise. InteractionTo ask number of inversions on a subsegment [l, r], print "? l r", where (1 \leq l \leq r \leq n). You can ask at most 40 questions in each test case. As a result you should read a single integer x. If x = -1, your program made an invalid question or you exceeded the number of questions for that test case. Your program should terminate immediately (otherwise it can get any verdict instead of "Wrong Answer"). Otherwise x is equal to the number of inversions on the subsegment [l, r] of the sequence a. To give the answer, print "! i j k", where i, j, k are the numbers you found. You should continue solving the next test cases or terminate the program after that.After printing a question or an answer do not forget to print the end of line and flush the output. Otherwise, you will get an "Idleness limit exceeded" verdict. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; See the documentation for other languages.HacksTo make a hack, use the following format:The first line contains a single integer t (1 \leq t \leq 100) — the number of test cases.Each of the next t lines contains four integers n, i, j, k (4 \leq n \leq 10^9, 1 \leq i < j < k \leq n, j - i > 1).ExampleInput
2
5
4
3
3
5
2
2
1 Output
? 1 5
? 2 5
? 3 5
! 1 3 5
? 1 5
? 2 5
? 3 5
! 2 4 5NoteIn the first test case, i = 1, j = 3, k = 5, so the sequence a is [2, 1, 5, 4, 3].In the second test case, i = 2, j = 4, k = 5, so the sequence a is [1, 3, 2, 5, 4]. | 2
5
4
3
3
5
2
2
1 | ? 1 5 ? 2 5 ? 3 5 ! 1 3 5 ? 1 5 ? 2 5 ? 3 5 ! 2 4 5 | 1 second | 256 megabytes | ['binary search', 'combinatorics', 'interactive', 'math', '*2000'] |
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays of integers a_1, a_2, \ldots, a_n and b_1, b_2, \ldots, b_n.Let's define a transformation of the array a: Choose any non-negative integer k such that 0 \le k \le n. Choose k distinct array indices 1 \le i_1 < i_2 < \ldots < i_k \le n. Add 1 to each of a_{i_1}, a_{i_2}, \ldots, a_{i_k}, all other elements of array a remain unchanged. Permute the elements of array a in any order. Is it possible to perform some transformation of the array a exactly once, so that the resulting array is equal to b?InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases. Descriptions of test cases follow.The first line of each test case contains a single integer n (1 \le n \le 100) — the size of arrays a and b.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (-100 \le a_i \le 100).The third line of each test case contains n integers b_1, b_2, \ldots, b_n (-100 \le b_i \le 100).OutputFor each test case, print "YES" (without quotes) if it is possible to perform a transformation of the array a, so that the resulting array is equal to b. Print "NO" (without quotes) otherwise.You can print each letter in any case (upper or lower).ExampleInput
3
3
-1 1 0
0 0 2
1
0
2
5
1 2 3 4 5
1 2 3 4 5
Output
YES
NO
YES
NoteIn the first test case, we can make the following transformation: Choose k = 2. Choose i_1 = 1, i_2 = 2. Add 1 to a_1 and a_2. The resulting array is [0, 2, 0]. Swap the elements on the second and third positions. In the second test case there is no suitable transformation.In the third test case we choose k = 0 and do not change the order of elements. | 3
3
-1 1 0
0 0 2
1
0
2
5
1 2 3 4 5
1 2 3 4 5
| YES NO YES | 1 second | 256 megabytes | ['greedy', 'math', 'sortings', '*900'] |
B. Coloring Rectanglestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDavid was given a red checkered rectangle of size n \times m. But he doesn't like it. So David cuts the original or any other rectangle piece obtained during the cutting into two new pieces along the grid lines. He can do this operation as many times as he wants.As a result, he will get a set of rectangles. Rectangles 1 \times 1 are forbidden.David also knows how to paint the cells blue. He wants each rectangle from the resulting set of pieces to be colored such that any pair of adjacent cells by side (from the same piece) have different colors.What is the minimum number of cells David will have to paint?InputThe first line contains a single integer t (1 \leq t \leq 10^3) — the number of test cases. The next lines contain descriptions of test cases.The only line of each test case contains two integers n, m (1 \leq n, m \leq 3 \cdot 10^4, n \cdot m \geq 2).OutputFor each test case print a single integer — the minimum number of cells David will have to paint blue.ExampleInput
4
1 3
2 2
2 5
3 5
Output
1
2
4
5
NoteThe following pictures show how the initial rectangle can be split and cells colored blue.In the first test case: In the second test case: In the third test case: In the fourth test case: | 4
1 3
2 2
2 5
3 5
| 1 2 4 5 | 1 second | 256 megabytes | ['greedy', 'math', '*1000'] |
A. Mathematical Additiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test have the following form: You are given two positive integers u and v, find any pair of integers (not necessarily positive) x, y, such that: \frac{x}{u} + \frac{y}{v} = \frac{x + y}{u + v}. The solution x = 0, y = 0 is forbidden, so you should find any solution with (x, y) \neq (0, 0). Please help Ivan to solve some equations of this form.InputThe first line contains a single integer t (1 \leq t \leq 10^3) — the number of test cases. The next lines contain descriptions of test cases.The only line of each test case contains two integers u and v (1 \leq u, v \leq 10^9) — the parameters of the equation.OutputFor each test case print two integers x, y — a possible solution to the equation. It should be satisfied that -10^{18} \leq x, y \leq 10^{18} and (x, y) \neq (0, 0).We can show that an answer always exists. If there are multiple possible solutions you can print any.ExampleInput
4
1 1
2 3
3 5
6 9
Output
-1 1
-4 9
-18 50
-4 9
NoteIn the first test case: \frac{-1}{1} + \frac{1}{1} = 0 = \frac{-1 + 1}{1 + 1}.In the second test case: \frac{-4}{2} + \frac{9}{3} = 1 = \frac{-4 + 9}{2 + 3}.In the third test case: \frac{-18}{3} + \frac{50}{5} = 4 = \frac{-18 + 50}{3 + 5}.In the fourth test case: \frac{-4}{6} + \frac{9}{9} = \frac{1}{3} = \frac{-4 + 9}{6 + 9}. | 4
1 1
2 3
3 5
6 9
| -1 1 -4 9 -18 50 -4 9 | 1 second | 256 megabytes | ['math', '*800'] |
H. Omkar and Tourstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputOmkar is hosting tours of his country, Omkarland! There are n cities in Omkarland, and, rather curiously, there are exactly n-1 bidirectional roads connecting the cities to each other. It is guaranteed that you can reach any city from any other city through the road network.Every city has an enjoyment value e. Each road has a capacity c, denoting the maximum number of vehicles that can be on it, and an associated toll t. However, the toll system in Omkarland has an interesting quirk: if a vehicle travels on multiple roads on a single journey, they pay only the highest toll of any single road on which they traveled. (In other words, they pay \max t over all the roads on which they traveled.) If a vehicle traverses no roads, they pay 0 toll.Omkar has decided to host q tour groups. Each tour group consists of v vehicles starting at city x. (Keep in mind that a tour group with v vehicles can travel only on roads with capacity \geq v.) Being the tour organizer, Omkar wants his groups to have as much fun as they possibly can, but also must reimburse his groups for the tolls that they have to pay. Thus, for each tour group, Omkar wants to know two things: first, what is the enjoyment value of the city y with maximum enjoyment value that the tour group can reach from their starting city, and second, how much per vehicle will Omkar have to pay to reimburse the entire group for their trip from x to y? (This trip from x to y will always be on the shortest path from x to y.)In the case that there are multiple reachable cities with the maximum enjoyment value, Omkar will let his tour group choose which one they want to go to. Therefore, to prepare for all possible scenarios, he wants to know the amount of money per vehicle that he needs to guarantee that he can reimburse the group regardless of which city they choose.InputThe first line contains two integers n and q (2 \leq n \leq 2 \cdot 10^5, 1 \leq q \leq 2 \cdot 10^5), representing the number of cities and the number of groups, respectively.The next line contains n integers e_1, e_2, \ldots, e_n (1 \leq e_i \leq 10^9), where e_i represents the enjoyment value for city i.The next n-1 lines each contain four integers a, b, c, and t (1 \leq a,b \leq n, 1 \leq c \leq 10^9, 1 \leq t \leq 10^9), representing an road between city a and city b with capacity c and toll t.The next q lines each contain two integers v and x (1 \leq v \leq 10^9, 1 \leq x \leq n), representing the number of vehicles in the tour group and the starting city, respectively.OutputOutput q lines. The i-th line should contain two integers: the highest possible enjoyment value of a city reachable by the i-th tour group, and the amount of money per vehicle Omkar needs to guarantee that he can reimburse the i-th tour group.ExamplesInput
5 3
2 2 3 3 3
1 2 4 7
1 3 2 8
2 4 8 2
2 5 1 1
1 3
9 5
6 2
Output
3 8
3 0
3 2
Input
5 5
1 2 3 4 5
1 2 4 1
1 3 3 1
1 4 2 1
2 5 1 1
5 1
4 1
3 1
2 1
1 1
Output
1 0
2 1
3 1
4 1
5 1
Input
5 5
1 2 2 2 2
1 2 5 8
1 3 6 3
1 4 4 5
1 5 7 1
4 1
5 1
6 1
7 1
8 1
Output
2 8
2 8
2 3
2 1
1 0
NoteA map of the first sample is shown below. For the nodes, unbolded numbers represent indices and bolded numbers represent enjoyment values. For the edges, unbolded numbers represent capacities and bolded numbers represent tolls. For the first query, a tour group of size 1 starting at city 3 can reach cities 1, 2, 3, 4, and 5. Thus, the largest enjoyment value that they can reach is 3. If the tour group chooses to go to city 4, Omkar will have to pay 8 per vehicle, which is the maximum.For the second query, a tour group of size 9 starting at city 5 can reach only city 5. Thus, the largest reachable enjoyment value is still 3, and Omkar will pay 0 per vehicle.For the third query, a tour group of size 6 starting at city 2 can reach cities 2 and 4. The largest reachable enjoyment value is again 3. If the tour group chooses to go to city 4, Omkar will have to pay 2 per vehicle, which is the maximum.A map of the second sample is shown below: For the first query, a tour group of size 5 starting at city 1 can only reach city 1. Thus, their maximum enjoyment value is 1 and the cost Omkar will have to pay is 0 per vehicle.For the second query, a tour group of size 4 starting at city 1 can reach cities 1 and 2. Thus, their maximum enjoyment value is 2 and Omkar will pay 1 per vehicle.For the third query, a tour group of size 3 starting at city 1 can reach cities 1, 2, and 3. Thus, their maximum enjoyment value is 3 and Omkar will pay 1 per vehicle.For the fourth query, a tour group of size 2 starting at city 1 can reach cities 1, 2, 3 and 4. Thus, their maximum enjoyment value is 4 and Omkar will pay 1 per vehicle.For the fifth query, a tour group of size 1 starting at city 1 can reach cities 1, 2, 3, 4, and 5. Thus, their maximum enjoyment value is 5 and Omkar will pay 1 per vehicle. | 5 3
2 2 3 3 3
1 2 4 7
1 3 2 8
2 4 8 2
2 5 1 1
1 3
9 5
6 2
| 3 8 3 0 3 2 | 3 seconds | 512 megabytes | ['data structures', 'divide and conquer', 'sortings', 'trees', '*3300'] |
G. Omkar and Time Traveltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEl Psy Kongroo.Omkar is watching Steins;Gate.In Steins;Gate, Okabe Rintarou needs to complete n tasks (1 \leq n \leq 2 \cdot 10^5). Unfortunately, he doesn't know when he needs to complete the tasks.Initially, the time is 0. Time travel will now happen according to the following rules:For each k = 1, 2, \ldots, n, Okabe will realize at time b_k that he was supposed to complete the k-th task at time a_k (a_k < b_k). When he realizes this, if k-th task was already completed at time a_k, Okabe keeps the usual flow of time. Otherwise, he time travels to time a_k then immediately completes the task.If Okabe time travels to time a_k, all tasks completed after this time will become incomplete again. That is, for every j, if a_j>a_k, the j-th task will become incomplete, if it was complete (if it was incomplete, nothing will change).Okabe has bad memory, so he can time travel to time a_k only immediately after getting to time b_k and learning that he was supposed to complete the k-th task at time a_k. That is, even if Okabe already had to perform k-th task before, he wouldn't remember it before stumbling on the info about this task at time b_k again.Please refer to the notes for an example of time travelling.There is a certain set s of tasks such that the first moment that all of the tasks in s are simultaneously completed (regardless of whether any other tasks are currently completed), a funny scene will take place. Omkar loves this scene and wants to know how many times Okabe will time travel before this scene takes place. Find this number modulo 10^9 + 7. It can be proven that eventually all n tasks will be completed and so the answer always exists.InputThe first line contains an integer n (1 \leq n \leq 2 \cdot 10^5) — the number of tasks that Okabe needs to complete.n lines follow. The k-th of these lines contain two integers a_k and b_k (1 \leq a_k < b_k \leq 2n) — the time at which Okabe needs to complete the k-th task and the time that he realizes this respectively. All 2n of these times are distinct (so every time from 1 to 2n inclusive appears exactly once in the input).The next line contains a single integer t (1 \leq t \leq n) — the size of the set s of tasks that lead to the funny scene.The last line contains t integers s_1, s_2, \ldots, s_t — (1 \leq s_k \leq n, the numbers s_1, s_2, \ldots, s_t are distinct) — the set s of tasks.OutputOutput a single integer — the number of times that Okabe time travels until all tasks in the set s are simultaneously completed, modulo 10^9 + 7.ExamplesInput
2
1 4
2 3
2
1 2
Output
3
Input
2
1 4
2 3
1
1
Output
2
Input
1
1 2
1
1
Output
1
Input
6
10 12
3 7
4 6
2 9
5 8
1 11
3
2 4 6
Output
17
Input
16
31 32
3 26
17 19
4 24
1 28
15 21
12 16
18 29
20 23
7 8
11 14
9 22
6 30
5 10
25 27
2 13
6
3 8 2 5 12 11
Output
138
NoteFor the first sample, all tasks need to be completed in order for the funny scene to occur.Initially, the time is 0. Nothing happens until time 3, when Okabe realizes that he should have done the 2-nd task at time 2. He then time travels to time 2 and completes the task.As the task is done now, he does not time travel again when the time is again 3. However, at time 4, he travels to time 1 to complete the 1-st task.This undoes the 2-nd task. This means that the 2-nd task is not currently completed, meaning that the funny scene will not occur at this point even though the 1-st task is currently completed and Okabe had previously completed the 2-nd task.Once it is again time 3 he travels back to time 2 once more and does the 2-nd task again.Now all tasks are complete, with Okabe having time travelled 3 times.The second sample has the same tasks for Okabe to complete. However, this time the funny scene only needs the first task to be completed in order to occur. From reading the above sample you can see that this occurs once Okabe has time travelled 2 times. | 2
1 4
2 3
2
1 2
| 3 | 2 seconds | 256 megabytes | ['data structures', 'math', '*3000'] |
F. Defender of Childhood Dreamstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputEven if you just leave them be, they will fall to pieces all by themselves. So, someone has to protect them, right?You find yourself playing with Teucer again in the city of Liyue. As you take the eccentric little kid around, you notice something interesting about the structure of the city.Liyue can be represented as a directed graph containing n nodes. Nodes are labeled from 1 to n. There is a directed edge from node a to node b if and only if a < b.A path between nodes a and b is defined as a sequence of edges such that you can start at a, travel along all of these edges in the corresponding direction, and end at b. The length of a path is defined by the number of edges. A rainbow path of length x is defined as a path in the graph such that there exists at least 2 distinct colors among the set of x edges.Teucer's favorite number is k. You are curious about the following scenario: If you were to label each edge with a color, what is the minimum number of colors needed to ensure that all paths of length k or longer are rainbow paths?Teucer wants to surprise his older brother with a map of Liyue. He also wants to know a valid coloring of edges that uses the minimum number of colors. Please help him with this task!InputThe only line of input contains two integers n and k (2 \leq k < n \leq 1000). OutputOn the first line, output c, the minimum colors you need to satisfy the above requirements.On the second line, print a valid edge coloring as an array of \frac{n(n-1)}{2} integers ranging from 1 to c. Exactly c distinct colors should exist in the construction. Print the edges in increasing order by the start node first, then by the second node.For example, if n=4, the edge colors will correspond to this order of edges: (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)ExamplesInput
5 3
Output
2
1 2 2 2 2 2 2 1 1 1
Input
5 2
Output
3
3 2 2 1 2 2 1 3 1 1
Input
8 7
Output
2
2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Input
3 2
Output
2
1 2 2
NoteThe corresponding construction for the first test case looks like this: It is impossible to satisfy the constraints with less than 2 colors.The corresponding construction for the second test case looks like this: One can show there exists no construction using less than 3 colors. | 5 3
| 2 1 2 2 2 2 2 2 1 1 1 | 3 seconds | 512 megabytes | ['bitmasks', 'constructive algorithms', 'divide and conquer', '*2500'] |
E. Moment of Bloomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputShe does her utmost to flawlessly carry out a person's last rites and preserve the world's balance of yin and yang.Hu Tao, being the little prankster she is, has tried to scare you with this graph problem! You are given a connected undirected graph of n nodes with m edges. You also have q queries. Each query consists of two nodes a and b.Initially, all edges in the graph have a weight of 0. For each query, you must choose a simple path starting from a and ending at b. Then you add 1 to every edge along this path. Determine if it's possible, after processing all q queries, for all edges in this graph to have an even weight. If so, output the choice of paths for each query. If it is not possible, determine the smallest number of extra queries you could add to make it possible. It can be shown that this number will not exceed 10^{18} under the given constraints.A simple path is defined as any path that does not visit a node more than once.An edge is said to have an even weight if its value is divisible by 2.InputThe first line contains two integers n and m (2 \leq n \leq 3 \cdot 10^5, n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2}, 3 \cdot 10^5\right)}).Each of the next m lines contains two integers x and y (1 \leq x, y \leq n, x\neq y) indicating an undirected edge between node x and y. The input will not contain self-loops or duplicate edges, and the provided graph will be connected.The next line contains a single integer q (1 \leq q \leq 3 \cdot 10^5).Each of the next q lines contains two integers a and b (1 \leq a, b \leq n, a \neq b), the description of each query.It is guaranteed that nq \leq 3 \cdot 10^5.OutputIf it is possible to force all edge weights to be even, print "YES" on the first line, followed by 2q lines indicating the choice of path for each query in the same order the queries are given. For each query, the first line should contain a single integer x: the number of nodes in the chosen path. The next line should then contain x spaced separated integers p_i indicating the path you take (p_1 = a, p_x = b and all numbers should fall between 1 and n). This path cannot contain duplicate nodes and must be a valid simple path in the graph.If it is impossible to force all edge weights to be even, print "NO" on the first line and the minimum number of added queries on the second line.ExamplesInput
6 7
2 1
2 3
3 5
1 4
6 1
5 6
4 5
3
1 4
5 1
4 5
Output
YES
2
1 4
4
5 3 2 1
5
4 1 2 3 5
Input
5 7
4 3
4 5
2 1
1 4
1 3
3 5
3 2
4
4 2
3 5
5 1
4 5
Output
NO
2
NoteHere is what the queries look like for the first test case (red corresponds to the 1st query, blue 2nd query, and green 3rd query): Notice that every edge in the graph is part of either 0 or 2 colored query edges.The graph in the second test case looks like this: There does not exist an assignment of paths that will force all edges to have even weights with the given queries. One must add at least 2 new queries to obtain a set of queries that can satisfy the condition. | 6 7
2 1
2 3
3 5
1 4
6 1
5 6
4 5
3
1 4
5 1
4 5
| YES 2 1 4 4 5 3 2 1 5 4 1 2 3 5 | 3 seconds | 512 megabytes | ['constructive algorithms', 'dfs and similar', 'graph matchings', 'graphs', 'greedy', 'trees', '*2200'] |
D. Omkar and the Meaning of Lifetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt turns out that the meaning of life is a permutation p_1, p_2, \ldots, p_n of the integers 1, 2, \ldots, n (2 \leq n \leq 100). Omkar, having created all life, knows this permutation, and will allow you to figure it out using some queries.A query consists of an array a_1, a_2, \ldots, a_n of integers between 1 and n. a is not required to be a permutation. Omkar will first compute the pairwise sum of a and p, meaning that he will compute an array s where s_j = p_j + a_j for all j = 1, 2, \ldots, n. Then, he will find the smallest index k such that s_k occurs more than once in s, and answer with k. If there is no such index k, then he will answer with 0.You can perform at most 2n queries. Figure out the meaning of life p.InteractionStart the interaction by reading single integer n (2 \leq n \leq 100) — the length of the permutation p.You can then make queries. A query consists of a single line "? \enspace a_1 \enspace a_2 \enspace \ldots \enspace a_n" (1 \leq a_j \leq n).The answer to each query will be a single integer k as described above (0 \leq k \leq n).After making 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.To output your answer, print a single line "! \enspace p_1 \enspace p_2 \enspace \ldots \enspace p_n" then terminate.You can make at most 2n queries. Outputting the answer does not count as a query.Hack FormatTo hack, first output a line containing n (2 \leq n \leq 100), then output another line containing the hidden permutation p_1, p_2, \ldots, p_n of numbers from 1 to n.ExampleInput
5
2
0
1
Output
? 4 4 2 3 2
? 3 5 1 5 5
? 5 2 4 3 1
! 3 2 1 5 4
NoteIn the sample, the hidden permutation p is [3, 2, 1, 5, 4]. Three queries were made.The first query is a = [4, 4, 2, 3, 2]. This yields s = [3 + 4, 2 + 4, 1 + 2, 5 + 3, 4 + 2] = [7, 6, 3, 8, 6]. 6 is the only number that appears more than once, and it appears first at index 2, making the answer to the query 2.The second query is a = [3, 5, 1, 5, 5]. This yields s = [3 + 3, 2 + 5, 1 + 1, 5 + 5, 4 + 5] = [6, 7, 2, 10, 9]. There are no numbers that appear more than once here, so the answer to the query is 0.The third query is a = [5, 2, 4, 3, 1]. This yields s = [3 + 5, 2 + 2, 1 + 4, 5 + 3, 4 + 1] = [8, 4, 5, 8, 5]. 5 and 8 both occur more than once here. 5 first appears at index 3, while 8 first appears at index 1, and 1 < 3, making the answer to the query 1.Note that the sample is only meant to provide an example of how the interaction works; it is not guaranteed that the above queries represent a correct strategy with which to determine the answer. | 5
2
0
1
| ? 4 4 2 3 2 ? 3 5 1 5 5 ? 5 2 4 3 1 ! 3 2 1 5 4 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'interactive', '*1800'] |
C. Omkar and Determinationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe problem statement looms below, filling you with determination.Consider a grid in which some cells are empty and some cells are filled. Call a cell in this grid exitable if, starting at that cell, you can exit the grid by moving up and left through only empty cells. This includes the cell itself, so all filled in cells are not exitable. Note that you can exit the grid from any leftmost empty cell (cell in the first column) by going left, and from any topmost empty cell (cell in the first row) by going up.Let's call a grid determinable if, given only which cells are exitable, we can exactly determine which cells are filled in and which aren't.You are given a grid a of dimensions n \times m , i. e. a grid with n rows and m columns. You need to answer q queries (1 \leq q \leq 2 \cdot 10^5). Each query gives two integers x_1, x_2 (1 \leq x_1 \leq x_2 \leq m) and asks whether the subgrid of a consisting of the columns x_1, x_1 + 1, \ldots, x_2 - 1, x_2 is determinable.InputThe first line contains two integers n, m (1 \leq n, m \leq 10^6, nm \leq 10^6) — the dimensions of the grid a.n lines follow. The y-th line contains m characters, the x-th of which is 'X' if the cell on the intersection of the the y-th row and x-th column is filled and "." if it is empty.The next line contains a single integer q (1 \leq q \leq 2 \cdot 10^5) — the number of queries.q lines follow. Each line contains two integers x_1 and x_2 (1 \leq x_1 \leq x_2 \leq m), representing a query asking whether the subgrid of a containing the columns x_1, x_1 + 1, \ldots, x_2 - 1, x_2 is determinable.OutputFor each query, output one line containing "YES" if the subgrid specified by the query is determinable and "NO" otherwise. The output is case insensitive (so "yEs" and "No" will also be accepted).ExampleInput
4 5
..XXX
...X.
...X.
...X.
5
1 3
3 3
4 5
5 5
1 5
Output
YES
YES
NO
YES
NO
NoteFor each query of the example, the corresponding subgrid is displayed twice below: first in its input format, then with each cell marked as "E" if it is exitable and "N" otherwise.For the first query: ..X EEN... EEE... EEE... EEEFor the second query: X N. E. E. ENote that you can exit the grid by going left from any leftmost cell (or up from any topmost cell); you do not need to reach the top left corner cell to exit the grid.For the third query: XX NNX. NNX. NNX. NNThis subgrid cannot be determined only from whether each cell is exitable, because the below grid produces the above "exitability grid" as well: XXXXXXXXFor the fourth query: X N. E. E. EFor the fifth query: ..XXX EENNN...X. EEENN...X. EEENN...X. EEENNThis query is simply the entire grid. It cannot be determined only from whether each cell is exitable because the below grid produces the above "exitability grid" as well: ..XXX...XX...XX...XX | 4 5
..XXX
...X.
...X.
...X.
5
1 3
3 3
4 5
5 5
1 5
| YES YES NO YES NO | 2 seconds | 256 megabytes | ['data structures', 'dp', '*1700'] |
B. Omkar and Heavenly Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLord Omkar would like to have a tree with n nodes (3 \le n \le 10^5) and has asked his disciples to construct the tree. However, Lord Omkar has created m (\mathbf{1 \le m < n}) restrictions to ensure that the tree will be as heavenly as possible. A tree with n nodes is an connected undirected graph with n nodes and n-1 edges. Note that for any two nodes, there is exactly one simple path between them, where a simple path is a path between two nodes that does not contain any node more than once.Here is an example of a tree: A restriction consists of 3 pairwise distinct integers, a, b, and c (1 \le a,b,c \le n). It signifies that node b cannot lie on the simple path between node a and node c. Can you help Lord Omkar and become his most trusted disciple? You will need to find heavenly trees for multiple sets of restrictions. It can be shown that a heavenly tree will always exist for any set of restrictions under the given constraints.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^4). Description of the test cases follows.The first line of each test case contains two integers, n and m (3 \leq n \leq 10^5, \mathbf{1 \leq m < n}), representing the size of the tree and the number of restrictions.The i-th of the next m lines contains three integers a_i, b_i, c_i (1 \le a_i, b_i, c_i \le n, a, b, c are distinct), signifying that node b_i cannot lie on the simple path between nodes a_i and c_i. It is guaranteed that the sum of n across all test cases will not exceed 10^5.OutputFor each test case, output n-1 lines representing the n-1 edges in the tree. On each line, output two integers u and v (1 \le u, v \le n, u \neq v) signifying that there is an edge between nodes u and v. Given edges have to form a tree that satisfies Omkar's restrictions.ExampleInput
2
7 4
1 2 3
3 4 5
5 6 7
6 5 4
5 3
1 2 3
2 3 4
3 4 5
Output
1 2
1 3
3 5
3 4
2 7
7 6
5 1
1 3
3 2
2 4
NoteThe output of the first sample case corresponds to the following tree: For the first restriction, the simple path between 1 and 3 is 1, 3, which doesn't contain 2. The simple path between 3 and 5 is 3, 5, which doesn't contain 4. The simple path between 5 and 7 is 5, 3, 1, 2, 7, which doesn't contain 6. The simple path between 6 and 4 is 6, 7, 2, 1, 3, 4, which doesn't contain 5. Thus, this tree meets all of the restrictions.The output of the second sample case corresponds to the following tree: | 2
7 4
1 2 3
3 4 5
5 6 7
6 5 4
5 3
1 2 3
2 3 4
3 4 5
| 1 2 1 3 3 5 3 4 2 7 7 6 5 1 1 3 3 2 2 4 | 2 seconds | 256 megabytes | ['constructive algorithms', 'trees', '*1200'] |
A. Windblume Odetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person.You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of n (n \ge 3) positive distinct integers (i.e. different, no duplicates are allowed).Find the largest subset (i.e. having the maximum number of elements) of this array such that its sum is a composite number. A positive integer x is called composite if there exists a positive integer y such that 1 < y < x and x is divisible by y.If there are multiple subsets with this largest size with the composite sum, you can output any of them. It can be proven that under the constraints of the problem such a non-empty subset always exists.InputEach test consists of multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line of each test case contains an integer n (3 \leq n \leq 100) — the length of the array.The second line of each test case contains n distinct integers a_{1},a_{2},\dots,a_{n} (1 \leq a_{i} \leq 200) — the elements of the array.OutputEach test case should have two lines of output.The first line should contain a single integer x: the size of the largest subset with composite sum. The next line should contain x space separated integers representing the indices of the subset of the initial array.ExampleInput
4
3
8 1 2
4
6 9 4 2
9
1 2 3 4 5 6 7 8 9
3
200 199 198
Output
2
2 1
4
2 1 4 3
9
6 9 1 2 3 4 5 7 8
3
1 2 3
NoteIn the first test case, the subset \{a_2, a_1\} has a sum of 9, which is a composite number. The only subset of size 3 has a prime sum equal to 11. Note that you could also have selected the subset \{a_1, a_3\} with sum 8 + 2 = 10, which is composite as it's divisible by 2.In the second test case, the sum of all elements equals to 21, which is a composite number. Here we simply take the whole array as our subset. | 4
3
8 1 2
4
6 9 4 2
9
1 2 3 4 5 6 7 8 9
3
200 199 198
| 2 2 1 4 2 1 4 3 9 6 9 1 2 3 4 5 7 8 3 1 2 3 | 1 second | 256 megabytes | ['math', 'number theory', '*800'] |
G. Kuzya and Homeworktime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKuzya started going to school. He was given math homework in which he was given an array a of length n and an array of symbols b of length n, consisting of symbols '*' and '/'.Let's denote a path of calculations for a segment [l; r] (1 \le l \le r \le n) in the following way: Let x=1 initially. For every i from l to r we will consequently do the following: if b_i= '*', x=x*a_i, and if b_i= '/', then x=\frac{x}{a_i}. Let's call a path of calculations for the segment [l; r] a list of all x that we got during the calculations (the number of them is exactly r - l + 1). For example, let a=[7, 12, 3, 5, 4, 10, 9], b=[/, *, /, /, /, *, *], l=2, r=6, then the path of calculations for that segment is [12, 4, 0.8, 0.2, 2].Let's call a segment [l;r] simple if the path of calculations for it contains only integer numbers. Kuzya needs to find the number of simple segments [l;r] (1 \le l \le r \le n). Since he obviously has no time and no interest to do the calculations for each option, he asked you to write a program to get to find that number!InputThe first line contains a single integer n (2 \le n \le 10^6).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^6).The third line contains n symbols without spaces between them — the array b_1, b_2 \ldots b_n (b_i= '/' or b_i= '*' for every 1 \le i \le n).OutputPrint a single integer — the number of simple segments [l;r].ExamplesInput
3
1 2 3
*/*
Output
2
Input
7
6 4 10 1 2 15 1
*/*/*//
Output
8
| 3
1 2 3
*/*
| 2 | 2 seconds | 512 megabytes | ['data structures', 'number theory', '*2600'] |
F2. Korney Korneevich and XOR (hard version)time limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem with bigger constraints.Korney Korneevich dag up an array a of length n. Korney Korneevich has recently read about the operation bitwise XOR, so he wished to experiment with it. For this purpose, he decided to find all integers x \ge 0 such that there exists an increasing subsequence of the array a, in which the bitwise XOR of numbers is equal to x.It didn't take a long time for Korney Korneevich to find all such x, and he wants to check his result. That's why he asked you to solve this problem!A sequence s is a subsequence of a sequence b if s can be obtained from b by deletion of several (possibly, zero or all) elements.A sequence s_1, s_2, \ldots , s_m is called increasing if s_1 < s_2 < \ldots < s_m.InputThe first line contains a single integer n (1 \le n \le 10^6).The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 5000) — the elements of the array a.OutputIn the first line print a single integer k — the number of found x values.In the second line print k integers in increasing order x_1, x_2, \ldots x_k (0 \le x_1 < \ldots < x_k) — found x values.ExamplesInput
4
4 2 2 4
Output
4
0 2 4 6
Input
8
1 0 1 7 12 5 3 2
Output
12
0 1 2 3 4 5 6 7 10 11 12 13
NoteIn the first test case: To get value x = 0 it is possible to choose and empty subsequence To get value x = 2 it is possible to choose a subsequence [2] To get value x = 4 it is possible to choose a subsequence [4] To get value x = 6 it is possible to choose a subsequence [2, 4] | 4
4 2 2 4
| 4 0 2 4 6 | 1.5 seconds | 512 megabytes | ['binary search', 'brute force', 'dp', 'greedy', 'two pointers', '*2400'] |
F1. Korney Korneevich and XOR (easy version)time limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem with smaller constraints.Korney Korneevich dag up an array a of length n. Korney Korneevich has recently read about the operation bitwise XOR, so he wished to experiment with it. For this purpose, he decided to find all integers x \ge 0 such that there exists an increasing subsequence of the array a, in which the bitwise XOR of numbers is equal to x.It didn't take a long time for Korney Korneevich to find all such x, and he wants to check his result. That's why he asked you to solve this problem!A sequence s is a subsequence of a sequence b if s can be obtained from b by deletion of several (possibly, zero or all) elements.A sequence s_1, s_2, \ldots , s_m is called increasing if s_1 < s_2 < \ldots < s_m.InputThe first line contains a single integer n (1 \le n \le 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 500) — the elements of the array a.OutputIn the first line print a single integer k — the number of found x values.In the second line print k integers in increasing order x_1, x_2, \ldots x_k (0 \le x_1 < \ldots < x_k) — found x values.ExamplesInput
4
4 2 2 4
Output
4
0 2 4 6
Input
8
1 0 1 7 12 5 3 2
Output
12
0 1 2 3 4 5 6 7 10 11 12 13
NoteIn the first test case: To get value x = 0 it is possible to choose and empty subsequence To get value x = 2 it is possible to choose a subsequence [2] To get value x = 4 it is possible to choose a subsequence [4] To get value x = 6 it is possible to choose a subsequence [2, 4] | 4
4 2 2 4
| 4 0 2 4 6 | 1.5 seconds | 512 megabytes | ['bitmasks', 'dp', 'greedy', '*1800'] |
E. Pchelyonok and Segmentstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPchelyonok decided to give Mila a gift. Pchelenok has already bought an array a of length n, but gifting an array is too common. Instead of that, he decided to gift Mila the segments of that array!Pchelyonok wants his gift to be beautiful, so he decided to choose k non-overlapping segments of the array [l_1,r_1], [l_2,r_2], \ldots [l_k,r_k] such that: the length of the first segment [l_1,r_1] is k, the length of the second segment [l_2,r_2] is k-1, \ldots, the length of the k-th segment [l_k,r_k] is 1 for each i<j, the i-th segment occurs in the array earlier than the j-th (i.e. r_i<l_j) the sums in these segments are strictly increasing (i.e. let sum(l \ldots r) = \sum\limits_{i=l}^{r} a_i — the sum of numbers in the segment [l,r] of the array, then sum(l_1 \ldots r_1) < sum(l_2 \ldots r_2) < \ldots < sum(l_k \ldots r_k)). Pchelenok also wants his gift to be as beautiful as possible, so he asks you to find the maximal value of k such that he can give Mila a gift!InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases. The next 2 \cdot t lines contain the descriptions of test cases. The description of each test case consists of two lines.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the 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 a.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print the maximum possible value of k.ExampleInput
5
1
1
3
1 2 3
5
1 1 2 2 3
7
1 2 1 1 3 2 6
5
9 6 7 9 7
Output
1
1
2
3
1
| 5
1
1
3
1 2 3
5
1 1 2 2 3
7
1 2 1 1 3 2 6
5
9 6 7 9 7
| 1 1 2 3 1 | 2 seconds | 512 megabytes | ['binary search', 'data structures', 'dp', 'greedy', 'math', '*2000'] |
D. Vupsen, Pupsen and 0time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVupsen and Pupsen were gifted an integer array. Since Vupsen doesn't like the number 0, he threw away all numbers equal to 0 from the array. As a result, he got an array a of length n.Pupsen, on the contrary, likes the number 0 and he got upset when he saw the array without zeroes. To cheer Pupsen up, Vupsen decided to come up with another array b of length n such that \sum_{i=1}^{n}a_i \cdot b_i=0. Since Vupsen doesn't like number 0, the array b must not contain numbers equal to 0. Also, the numbers in that array must not be huge, so the sum of their absolute values cannot exceed 10^9. Please help Vupsen to find any such array b!InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases. The next 2 \cdot t lines contain the description of test cases. The description of each test case consists of two lines.The first line of each test case contains a single integer n (2 \le n \le 10^5) — the length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (-10^4 \le a_i \le 10^4, a_i \neq 0) — the elements of the array a.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print n integers b_1, b_2, \ldots, b_n — elements of the array b (|b_1|+|b_2|+\ldots +|b_n| \le 10^9, b_i \neq 0, \sum_{i=1}^{n}a_i \cdot b_i=0).It can be shown that the answer always exists.ExampleInput
3
2
5 5
5
5 -2 10 -9 4
7
1 2 3 4 5 6 7
Output
1 -1
-1 5 1 -1 -1
-10 2 2 -3 5 -1 -1
NoteIn the first test case, 5 \cdot 1 + 5 \cdot (-1)=5-5=0. You could also print 3 -3, for example, since 5 \cdot 3 + 5 \cdot (-3)=15-15=0In the second test case, 5 \cdot (-1) + (-2) \cdot 5 + 10 \cdot 1 + (-9) \cdot (-1) + 4 \cdot (-1)=-5-10+10+9-4=0. | 3
2
5 5
5
5 -2 10 -9 4
7
1 2 3 4 5 6 7
| 1 -1 -1 5 1 -1 -1 -10 2 2 -3 5 -1 -1 | 1 second | 256 megabytes | ['constructive algorithms', 'math', '*1600'] |
C. Grandma Capa Knits a Scarftime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGrandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string s of length n.Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid offending him, she will choose one lowercase English letter and erase some (at her choice, possibly none or all) occurrences of that letter in string s.She also wants to minimize the number of erased symbols from the pattern. Please help her and find the minimum number of symbols she can erase to make string s a palindrome, or tell her that it's impossible. Notice that she can only erase symbols equal to the one letter she chose.A string is a palindrome if it is the same from the left to the right and from the right to the left. For example, the strings 'kek', 'abacaba', 'r' and 'papicipap' are palindromes, while the strings 'abb' and 'iq' are not.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases. The next 2 \cdot t lines contain the description of test cases. The description of each test case consists of two lines.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the length of the string.The second line of each test case contains the string s consisting of n lowercase English letters.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print the minimum number of erased symbols required to make the string a palindrome, if it is possible, and -1, if it is impossible.ExampleInput
5
8
abcaacab
6
xyzxyz
4
abba
8
rprarlap
10
khyyhhyhky
Output
2
-1
0
3
2
NoteIn the first test case, you can choose a letter 'a' and erase its first and last occurrences, you will get a string 'bcaacb', which is a palindrome. You can also choose a letter 'b' and erase all its occurrences, you will get a string 'acaaca', which is a palindrome as well.In the second test case, it can be shown that it is impossible to choose a letter and erase some of its occurrences to get a palindrome.In the third test case, you don't have to erase any symbols because the string is already a palindrome. | 5
8
abcaacab
6
xyzxyz
4
abba
8
rprarlap
10
khyyhhyhky
| 2 -1 0 3 2 | 1 second | 256 megabytes | ['brute force', 'data structures', 'greedy', 'strings', 'two pointers', '*1200'] |
B. Luntik and Subsequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuntik came out for a morning stroll and found an array a of length n. He calculated the sum s of the elements of the array (s= \sum_{i=1}^{n} a_i). Luntik calls a subsequence of the array a nearly full if the sum of the numbers in that subsequence is equal to s-1.Luntik really wants to know the number of nearly full subsequences of the array a. But he needs to come home so he asks you to solve that problem!A sequence x is a subsequence of a sequence y if x can be obtained from y by deletion of several (possibly, zero or all) elements.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases. The next 2 \cdot t lines contain descriptions of test cases. The description of each test case consists of two lines.The first line of each test case contains a single integer n (1 \le n \le 60) — the length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — the elements of the array a.OutputFor each test case print the number of nearly full subsequences of the array.ExampleInput
5
5
1 2 3 4 5
2
1000 1000
2
1 0
5
3 0 2 1 1
5
2 1 0 3 0
Output
1
0
2
4
4
NoteIn the first test case, s=1+2+3+4+5=15, only (2,3,4,5) is a nearly full subsequence among all subsequences, the sum in it is equal to 2+3+4+5=14=15-1.In the second test case, there are no nearly full subsequences.In the third test case, s=1+0=1, the nearly full subsequences are (0) and () (the sum of an empty subsequence is 0). | 5
5
1 2 3 4 5
2
1000 1000
2
1 0
5
3 0 2 1 1
5
2 1 0 3 0
| 1 0 2 4 4 | 1 second | 256 megabytes | ['combinatorics', 'math', '*900'] |
A. Luntik and Concertstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuntik has decided to try singing. He has a one-minute songs, b two-minute songs and c three-minute songs. He wants to distribute all songs into two concerts such that every song should be included to exactly one concert.He wants to make the absolute difference of durations of the concerts as small as possible. The duration of the concert is the sum of durations of all songs in that concert.Please help Luntik and find the minimal possible difference in minutes between the concerts durations.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.Each test case consists of one line containing three integers a, b, c (1 \le a, b, c \le 10^9) — the number of one-minute, two-minute and three-minute songs.OutputFor each test case print the minimal possible difference in minutes between the concerts durations.ExampleInput
4
1 1 1
2 1 3
5 5 5
1 1 2
Output
0
1
0
1
NoteIn the first test case, Luntik can include a one-minute song and a two-minute song into the first concert, and a three-minute song into the second concert. Then the difference will be equal to 0.In the second test case, Luntik can include two one-minute songs and a two-minute song and a three-minute song into the first concert, and two three-minute songs into the second concert. The duration of the first concert will be 1 + 1 + 2 + 3 = 7, the duration of the second concert will be 6. The difference of them is |7-6| = 1. | 4
1 1 1
2 1 3
5 5 5
1 1 2
| 0 1 0 1 | 1 second | 256 megabytes | ['math', '*800'] |
B. Diameter of Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCQXYM wants to create a connected undirected graph with n nodes and m edges, and the diameter of the graph must be strictly less than k-1. Also, CQXYM doesn't want a graph that contains self-loops or multiple edges (i.e. each edge connects two different vertices and between each pair of vertices there is at most one edge).The diameter of a graph is the maximum distance between any two nodes.The distance between two nodes is the minimum number of the edges on the path which endpoints are the two nodes.CQXYM wonders whether it is possible to create such a graph.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 10^5) — the number of test cases. The description of the test cases follows.Only one line of each test case contains three integers n(1 \leq n \leq 10^9), m, k (0 \leq m,k \leq 10^9).OutputFor each test case, print YES if it is possible to create the graph, or print NO if it is impossible. You can print each letter in any case (upper or lower).ExampleInput
5
1 0 3
4 5 3
4 6 3
5 4 1
2 1 1
Output
YES
NO
YES
NO
NO
NoteIn the first test case, the graph's diameter equal to 0.In the second test case, the graph's diameter can only be 2.In the third test case, the graph's diameter can only be 1. | 5
1 0 3
4 5 3
4 6 3
5 4 1
2 1 1
| YES NO YES NO NO | 1 second | 256 megabytes | ['constructive algorithms', 'graphs', 'greedy', 'math', '*1200'] |
A. CQXYM Count Permutationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCQXYM is counting permutations length of 2n.A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).A permutation p(length of 2n) will be counted only if the number of i satisfying p_i<p_{i+1} is no less than n. For example: Permutation [1, 2, 3, 4] will count, because the number of such i that p_i<p_{i+1} equals 3 (i = 1, i = 2, i = 3). Permutation [3, 2, 1, 4] won't count, because the number of such i that p_i<p_{i+1} equals 1 (i = 3). CQXYM wants you to help him to count the number of such permutations modulo 1000000007 (10^9+7).In addition, modulo operation is to get the remainder. For example: 7 \mod 3=1, because 7 = 3 \cdot 2 + 1, 15 \mod 4=3, because 15 = 4 \cdot 3 + 3. InputThe input consists of multiple test cases. The first line contains an integer t (t \geq 1) — the number of test cases. The description of the test cases follows.Only one line of each test case contains an integer n(1 \leq n \leq 10^5).It is guaranteed that the sum of n over all test cases does not exceed 10^5OutputFor each test case, print the answer in a single line.ExampleInput
4
1
2
9
91234
Output
1
12
830455698
890287984
Noten=1, there is only one permutation that satisfies the condition: [1,2].In permutation [1,2], p_1<p_2, and there is one i=1 satisfy the condition. Since 1 \geq n, this permutation should be counted. In permutation [2,1], p_1>p_2. Because 0<n, this permutation should not be counted.n=2, there are 12 permutations: [1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[2,1,3,4],[2,3,1,4],[2,3,4,1],[2,4,1,3],[3,1,2,4],[3,4,1,2],[4,1,2,3]. | 4
1
2
9
91234
| 1 12 830455698 890287984 | 1 second | 256 megabytes | ['combinatorics', 'math', 'number theory', '*800'] |
F. Problems for Codeforcestime limit per test8 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputXYMXYM and CQXYM will prepare n problems for Codeforces. The difficulty of the problem i will be an integer a_i, where a_i \geq 0. The difficulty of the problems must satisfy a_i+a_{i+1}<m (1 \leq i < n), and a_1+a_n<m, where m is a fixed integer. XYMXYM wants to know how many plans of the difficulty of the problems there are modulo 998\,244\,353.Two plans of difficulty a and b are different only if there is an integer i (1 \leq i \leq n) satisfying a_i \neq b_i.InputA single line contains two integers n and m (2 \leq n \leq 50\,000, 1 \leq m \leq 10^9).OutputPrint a single integer — the number of different plans.ExamplesInput
3 2
Output
4
Input
5 9
Output
8105
Input
21038 3942834
Output
338529212
NoteIn the first test case, the valid a are: [0,0,0], [0,0,1], [0,1,0], [1,0,0].[1,0,1] is invalid since a_1+a_n \geq m. | 3 2
| 4 | 8 seconds | 256 megabytes | ['combinatorics', 'fft', 'math', '*3300'] |
E. Railway Constructiontime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBecause the railway system in Gensokyo is often congested, as an enthusiastic engineer, Kawasiro Nitori plans to construct more railway to ease the congestion.There are n stations numbered from 1 to n and m two-way railways in Gensokyo. Every two-way railway connects two different stations and has a positive integer length d. No two two-way railways connect the same two stations. Besides, it is possible to travel from any station to any other using those railways. Among these n stations, station 1 is the main station. You can get to any station from any other station using only two-way railways.Because of the technological limitation, Nitori can only construct one-way railways, whose length can be arbitrary positive integer. Constructing a one-way railway from station u will costs w_u units of resources, no matter where the railway ends. To ease the congestion, Nitori plans that after construction there are at least two shortest paths from station 1 to any other station, and these two shortest paths do not pass the same station except station 1 and the terminal. Besides, Nitori also does not want to change the distance of the shortest path from station 1 to any other station.Due to various reasons, sometimes the cost of building a new railway will increase uncontrollably. There will be a total of q occurrences of this kind of incident, and the i-th event will add additional amount of x_i to the cost of building a new railway from the station k_i.To save resources, before all incidents and after each incident, Nitori wants you to help her calculate the minimal cost of railway construction.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, 0 \le q \le 2\cdot10^5).The second line contains n integers w_1,w_2,\ldots,w_n (1 \le w_i \le 10^9).Each of the next m lines contains three integers u, v, d (1 \le u,v \le n, u \ne v, 1 \le d \le 10^9), denoting a two-way railway connecting station u and station v, with length d.The i-th of the next q lines contains two integers k_i,x_i (1 \le k_i \le n, 1 \le x_i \le 4 \times 10^8).OutputPrint q+1 lines, and the i-th of these lines contains one integer, denoting the minimal cost of railway construction after the i-1-th incident (especially, the 0-th incident means no incident occurred).ExamplesInput
5 5 1
1 1 1 1 1
1 2 1
2 3 1
2 4 1
3 5 1
4 5 1
1 2
Output
3
9
Input
8 11 0
14 4 16 15 1 3 1 14
4 2 1
1 2 3
7 5 4
2 3 1
8 6 2
8 5 5
5 4 5
7 6 7
3 5 5
1 6 6
8 1 4
Output
46
Input
10 16 8
29 1 75 73 51 69 24 17 1 97
1 2 18
2 3 254
2 4 546
2 5 789
5 6 998
6 7 233
7 8 433
1 9 248
5 10 488
2 6 1787
10 8 1176
3 8 2199
4 8 1907
2 10 1277
4 10 731
9 10 1047
1 11
1 9
8 8
1 3
2 19
9 5
9 4
7 6
Output
34
45
54
54
57
76
96
112
112
NoteIn the second example, Nitori can build railways as follows: 1 \rightarrow 2, 1 \rightarrow 3, 1 \rightarrow 4, 2 \rightarrow 8, and the cost is 14 + 14 + 14 + 4 = 46. | 5 5 1
1 1 1 1 1
1 2 1
2 3 1
2 4 1
3 5 1
4 5 1
1 2
| 3 9 | 2.5 seconds | 512 megabytes | ['brute force', 'constructive algorithms', 'data structures', 'graphs', 'shortest paths', '*3400'] |
D. Subsequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice has an integer sequence a of length n and all elements are different. She will choose a subsequence of a of length m, and defines the value of a subsequence a_{b_1},a_{b_2},\ldots,a_{b_m} as \sum_{i = 1}^m (m \cdot a_{b_i}) - \sum_{i = 1}^m \sum_{j = 1}^m f(\min(b_i, b_j), \max(b_i, b_j)), where f(i, j) denotes \min(a_i, a_{i + 1}, \ldots, a_j).Alice wants you to help her to maximize the value of the subsequence she choose.A sequence s is a subsequence of a sequence t if s can be obtained from t by deletion of several (possibly, zero or all) elements.InputThe first line contains two integers n and m (1 \le m \le n \le 4000).The second line contains n distinct integers a_1, a_2, \ldots, a_n (1 \le a_i < 2^{31}).OutputPrint the maximal value Alice can get.ExamplesInput
6 4
15 2 18 12 13 4
Output
100
Input
11 5
9 3 7 1 8 12 10 20 15 18 5
Output
176
Input
1 1
114514
Output
0
Input
2 1
666 888
Output
0
NoteIn the first example, Alice can choose the subsequence [15, 2, 18, 13], which has the value 4 \cdot (15 + 2 + 18 + 13) - (15 + 2 + 2 + 2) - (2 + 2 + 2 + 2) - (2 + 2 + 18 + 12) - (2 + 2 + 12 + 13) = 100. In the second example, there are a variety of subsequences with value 176, and one of them is [9, 7, 12, 20, 18]. | 6 4
15 2 18 12 13 4
| 100 | 1 second | 256 megabytes | ['brute force', 'divide and conquer', 'dp', 'greedy', 'trees', '*2900'] |
C. Train Maintenancetime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputKawasiro Nitori is excellent in engineering. Thus she has been appointed to help maintain trains.There are n models of trains, and Nitori's department will only have at most one train of each model at any moment. In the beginning, there are no trains, at each of the following m days, one train will be added, or one train will be removed. When a train of model i is added at day t, it works for x_i days (day t inclusive), then it is in maintenance for y_i days, then in work for x_i days again, and so on until it is removed.In order to make management easier, Nitori wants you to help her calculate how many trains are in maintenance in each day.On a day a train is removed, it is not counted as in maintenance.InputThe first line contains two integers n, m (1 \le n,m \le 2 \cdot 10^5).The i-th of the next n lines contains two integers x_i,y_i (1 \le x_i,y_i \le 10^9).Each of the next m lines contains two integers op, k (1 \le k \le n, op = 1 or op = 2). If op=1, it means this day's a train of model k is added, otherwise the train of model k is removed. It is guaranteed that when a train of model x is added, there is no train of the same model in the department, and when a train of model x is removed, there is such a train in the department.OutputPrint m lines, The i-th of these lines contains one integers, denoting the number of trains in maintenance in the i-th day.ExamplesInput
3 4
10 15
12 10
1 1
1 3
1 1
2 1
2 3
Output
0
1
0
0
Input
5 4
1 1
10000000 100000000
998244353 1
2 1
1 2
1 5
2 5
1 5
1 1
Output
0
0
0
1
NoteConsider the first example:The first day: Nitori adds a train of model 3. Only a train of model 3 is running and no train is in maintenance.The second day: Nitori adds a train of model 1. A train of model 1 is running and a train of model 3 is in maintenance.The third day: Nitori removes a train of model 1. The situation is the same as the first day.The fourth day: Nitori removes a train of model 3. There are no trains at all. | 3 4
10 15
12 10
1 1
1 3
1 1
2 1
2 3
| 0 1 0 0 | 1 second | 512 megabytes | ['brute force', 'data structures', 'implementation', '*2200'] |
B. Mathematics Curriculumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet c_1, c_2, \ldots, c_n be a permutation of integers 1, 2, \ldots, n. Consider all subsegments of this permutation containing an integer x. Given an integer m, we call the integer x good if there are exactly m different values of maximum on these subsegments.Cirno is studying mathematics, and the teacher asks her to count the number of permutations of length n with exactly k good numbers.Unfortunately, Cirno isn't good at mathematics, and she can't answer this question. Therefore, she asks you for help.Since the answer may be very big, you only need to tell her the number of permutations modulo p.A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).A sequence a is a subsegment of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputThe first line contains four integers n, m, k, p (1 \le n \le 100, 1 \le m \le n, 1 \le k \le n, 1 \le p \le 10^9).OutputOutput the number of permutations modulo p.ExamplesInput
4 3 2 10007
Output
4
Input
6 4 1 769626776
Output
472
Input
66 11 9 786747482
Output
206331312
Input
99 30 18 650457567
Output
77365367
NoteIn the first test case, there are four permutations: [1, 3, 2, 4], [2, 3, 1, 4], [4, 1, 3, 2] and [4, 2, 3, 1].Take permutation [1, 3, 2, 4] as an example:For number 1, all subsegments containing it are: [1], [1, 3], [1, 3, 2] and [1, 3, 2, 4], and there're three different maxima 1, 3 and 4.Similarly, for number 3, there're two different maxima 3 and 4. For number 2, there're three different maxima 2, 3 and 4. And for number 4, there're only one, that is 4 itself. | 4 3 2 10007
| 4 | 2 seconds | 256 megabytes | ['brute force', 'combinatorics', 'dp', 'trees', '*2600'] |
A. Portaltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCQXYM found a rectangle A of size n \times m. There are n rows and m columns of blocks. Each block of the rectangle is an obsidian block or empty. CQXYM can change an obsidian block to an empty block or an empty block to an obsidian block in one operation.A rectangle M size of a \times b is called a portal if and only if it satisfies the following conditions: a \geq 5,b \geq 4. For all 1 < x < a, blocks M_{x,1} and M_{x,b} are obsidian blocks. For all 1 < x < b, blocks M_{1,x} and M_{a,x} are obsidian blocks. For all 1<x<a,1<y<b, block M_{x,y} is an empty block. M_{1, 1}, M_{1, b}, M_{a, 1}, M_{a, b} can be any type. Note that the there must be a rows and b columns, not b rows and a columns.Note that corners can be any typeCQXYM wants to know the minimum number of operations he needs to make at least one sub-rectangle a portal.InputThe first line contains an integer t (t \geq 1), which is the number of test cases.For each test case, the first line contains two integers n and m (5 \le n \le 400, 4 \le m \le 400). Then n lines follow, each line contains m characters 0 or 1. If the j-th character of i-th line is 0, block A_{i,j} is an empty block. Otherwise, block A_{i,j} is an obsidian block.It is guaranteed that the sum of n over all test cases does not exceed 400.It is guaranteed that the sum of m over all test cases does not exceed 400.OutputOutput t answers, and each answer in a line.ExamplesInput
1
5 4
1000
0000
0110
0000
0001
Output
12
Input
1
9 9
001010001
101110100
000010011
100000001
101010101
110001111
000001111
111100000
000110000
Output
5
NoteIn the first test case, the final portal is like this:11101001100110010111 | 1
5 4
1000
0000
0110
0000
0001
| 12 | 1 second | 256 megabytes | ['brute force', 'data structures', 'dp', 'greedy', 'implementation', '*1700'] |
G. Minimal Coveragetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n lengths of segments that need to be placed on an infinite axis with coordinates.The first segment is placed on the axis so that one of its endpoints lies at the point with coordinate 0. Let's call this endpoint the "start" of the first segment and let's call its "end" as that endpoint that is not the start. The "start" of each following segment must coincide with the "end" of the previous one. Thus, if the length of the next segment is d and the "end" of the previous one has the coordinate x, the segment can be placed either on the coordinates [x-d, x], and then the coordinate of its "end" is x - d, or on the coordinates [x, x+d], in which case its "end" coordinate is x + d.The total coverage of the axis by these segments is defined as their overall union which is basically the set of points covered by at least one of the segments. It's easy to show that the coverage will also be a segment on the axis. Determine the minimal possible length of the coverage that can be obtained by placing all the segments on the axis without changing their order.InputThe first line contains an integer t (1 \leq t \leq 1000) — the number of test cases.The next 2t lines contain descriptions of the test cases. The first line of each test case description contains an integer n (1 \le n \le 10^4) — the number of segments. The second line of the description contains n space-separated integers a_i (1 \le a_i \le 1000) — lengths of the segments in the same order they should be placed on the axis.It is guaranteed that the sum of n over all test cases does not exceed 10^4.OutputPrint t lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer — the minimal possible length of the axis coverage.ExampleInput
6
2
1 3
3
1 2 3
4
6 2 3 9
4
6 8 4 5
7
1 2 4 6 7 7 3
8
8 6 5 1 2 2 3 6
Output
3
3
9
9
7
8
NoteIn the third sample test case the segments should be arranged as follows: [0, 6] \rightarrow [4, 6] \rightarrow [4, 7] \rightarrow [-2, 7]. As you can see, the last segment [-2, 7] covers all the previous ones, and the total length of coverage is 9.In the fourth sample test case the segments should be arranged as [0, 6] \rightarrow [-2, 6] \rightarrow [-2, 2] \rightarrow [2, 7]. The union of these segments also occupies the area [-2, 7] and has the length of 9. | 6
2
1 3
3
1 2 3
4
6 2 3 9
4
6 8 4 5
7
1 2 4 6 7 7 3
8
8 6 5 1 2 2 3 6
| 3 3 9 9 7 8 | 1 second | 256 megabytes | ['dp', '*2200'] |
F. Array Stabilization (AND version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a[0 \ldots n - 1] = [a_0, a_1, \ldots, a_{n - 1}] of zeroes and ones only. Note that in this problem, unlike the others, the array indexes are numbered from zero, not from one.In one step, the array a is replaced by another array of length n according to the following rules: First, a new array a^{\rightarrow d} is defined as a cyclic shift of the array a to the right by d cells. The elements of this array can be defined as a^{\rightarrow d}_i = a_{(i + n - d) \bmod n}, where (i + n - d) \bmod n is the remainder of integer division of i + n - d by n. It means that the whole array a^{\rightarrow d} can be represented as a sequence a^{\rightarrow d} = [a_{n - d}, a_{n - d + 1}, \ldots, a_{n - 1}, a_0, a_1, \ldots, a_{n - d - 1}] Then each element of the array a_i is replaced by a_i \,\&\, a^{\rightarrow d}_i, where \& is a logical "AND" operator. For example, if a = [0, 0, 1, 1] and d = 1, then a^{\rightarrow d} = [1, 0, 0, 1] and the value of a after the first step will be [0 \,\&\, 1, 0 \,\&\, 0, 1 \,\&\, 0, 1 \,\&\, 1], that is [0, 0, 0, 1].The process ends when the array stops changing. For a given array a, determine whether it will consist of only zeros at the end of the process. If yes, also find the number of steps the process will take before it finishes.InputThe first line contains an integer t (1 \leq t \leq 1000) — the number of test cases.The next 2t lines contain descriptions of the test cases. The first line of each test case description contains two integers: n (1 \le n \le 10^6) — array size and d (1 \le d \le n) — cyclic shift offset. The second line of the description contains n space-separated integers a_i (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^6.OutputPrint t lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer — the number of steps after which the array will contain only zeros for the first time. If there are still elements equal to 1 in the array after the end of the process, print -1.ExampleInput
5
2 1
0 1
3 2
0 1 0
5 2
1 1 0 1 0
4 2
0 1 0 1
1 1
0
Output
1
1
3
-1
0
NoteIn the third sample test case the array will change as follows: At the beginning a = [1, 1, 0, 1, 0], and a^{\rightarrow 2} = [1, 0, 1, 1, 0]. Their element-by-element "AND" is equal to [1 \,\&\, 1, 1 \,\&\, 0, 0 \,\&\, 1, 1 \,\&\, 1, 0 \,\&\, 0] = [1, 0, 0, 1, 0] Now a = [1, 0, 0, 1, 0], then a^{\rightarrow 2} = [1, 0, 1, 0, 0]. Their element-by-element "AND" equals to [1 \,\&\, 1, 0 \,\&\, 0, 0 \,\&\, 1, 1 \,\&\, 0, 0 \,\&\, 0] = [1, 0, 0, 0, 0] And finally, when a = [1, 0, 0, 0, 0] we get a^{\rightarrow 2} = [0, 0, 1, 0, 0]. Their element-by-element "AND" equals to [1 \,\&\, 0, 0 \,\&\, 0, 0 \,\&\, 1, 0 \,\&\, 0, 0 \,\&\, 0] = [0, 0, 0, 0, 0] Thus, the answer is 3 steps.In the fourth sample test case, the array will not change as it shifts by 2 to the right, so each element will be calculated as 0 \,\&\, 0 or 1 \,\&\, 1 thus not changing its value. So the answer is -1, the array will never contain only zeros. | 5
2 1
0 1
3 2
0 1 0
5 2
1 1 0 1 0
4 2
0 1 0 1
1 1
0
| 1 1 3 -1 0 | 2 seconds | 256 megabytes | ['brute force', 'graphs', 'math', 'number theory', 'shortest paths', '*1700'] |
E2. Array Optimization by Dequetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.You are given an integer array a[1 \ldots n] = [a_1, a_2, \ldots, a_n].Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements [3, 4, 4] currently in the deque, adding an element 1 to the beginning will produce the sequence [\color{red}{1}, 3, 4, 4], and adding the same element to the end will produce [3, 4, 4, \color{red}{1}].The elements of the array are sequentially added to the initially empty deque, starting with a_1 and finishing with a_n. Before adding each element to the deque, you may choose whether to add it to the beginning or to the end.For example, if we consider an array a = [3, 7, 5, 5], one of the possible sequences of actions looks like this: \quad 1.add 3 to the beginning of the deque:deque has a sequence [\color{red}{3}] in it;\quad 2.add 7 to the end of the deque:deque has a sequence [3, \color{red}{7}] in it;\quad 3.add 5 to the end of the deque:deque has a sequence [3, 7, \color{red}{5}] in it;\quad 4.add 5 to the beginning of the deque:deque has a sequence [\color{red}{5}, 3, 7, 5] in it;Find the minimal possible number of inversions in the deque after the whole array is processed. An inversion in sequence d is a pair of indices (i, j) such that i < j and d_i > d_j. For example, the array d = [5, 3, 7, 5] has exactly two inversions — (1, 2) and (3, 4), since d_1 = 5 > 3 = d_2 and d_3 = 7 > 5 = d_4.InputThe first line contains an integer t (1 \leq t \leq 1000) — the number of test cases.The next 2t lines contain descriptions of the test cases. The first line of each test case description contains an integer n (1 \le n \le 2 \cdot 10^5) — array size. The second line of the description contains n space-separated integers a_i (-10^9 \le a_i \le 10^9) — elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputPrint t lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer — the minimal possible number of inversions in the deque after executing the described algorithm.ExampleInput
6
4
3 7 5 5
3
3 2 1
3
3 1 2
4
-1 2 2 -1
4
4 5 1 3
5
1 3 1 3 2
Output
2
0
1
0
1
2
NoteOne of the ways to get the sequence [5, 3, 7, 5] in the deque, containing only two inversions, from the initial array [3, 7, 5, 5] (the first sample test case) is described in the problem statement. Also, in this example, you could get the answer of two inversions by simply putting each element of the original array at the end of the deque. In this case, the original sequence [3, 7, 5, 5], also containing exactly two inversions, will be in the deque as-is. | 6
4
3 7 5 5
3
3 2 1
3
3 1 2
4
-1 2 2 -1
4
4 5 1 3
5
1 3 1 3 2
| 2 0 1 0 1 2 | 2 seconds | 256 megabytes | ['data structures', 'greedy', '*1700'] |
E1. Permutation Minimization by Dequetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.A permutation p of size n is given. A permutation of size n is an array of size n in which each integer from 1 to n occurs exactly once. For example, [1, 4, 3, 2] and [4, 2, 1, 3] are correct permutations while [1, 2, 4] and [1, 2, 2] are not.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements [1, 5, 2] currently in the deque, adding an element 4 to the beginning will produce the sequence [\color{red}{4}, 1, 5, 2], and adding same element to the end will produce [1, 5, 2, \color{red}{4}].The elements of the permutation are sequentially added to the initially empty deque, starting with p_1 and finishing with p_n. Before adding each element to the deque, you may choose whether to add it to the beginning or the end.For example, if we consider a permutation p = [3, 1, 2, 4], one of the possible sequences of actions looks like this: \quad 1.add 3 to the end of the deque:deque has a sequence [\color{red}{3}] in it;\quad 2.add 1 to the beginning of the deque:deque has a sequence [\color{red}{1}, 3] in it;\quad 3.add 2 to the end of the deque:deque has a sequence [1, 3, \color{red}{2}] in it;\quad 4.add 4 to the end of the deque:deque has a sequence [1, 3, 2, \color{red}{4}] in it;Find the lexicographically smallest possible sequence of elements in the deque after the entire permutation has been processed. A sequence [x_1, x_2, \ldots, x_n] is lexicographically smaller than the sequence [y_1, y_2, \ldots, y_n] if there exists such i \leq n that x_1 = y_1, x_2 = y_2, \ldots, x_{i - 1} = y_{i - 1} and x_i < y_i. In other words, if the sequences x and y have some (possibly empty) matching prefix, and the next element of the sequence x is strictly smaller than the corresponding element of the sequence y. For example, the sequence [1, 3, 2, 4] is smaller than the sequence [1, 3, 4, 2] because after the two matching elements [1, 3] in the start the first sequence has an element 2 which is smaller than the corresponding element 4 in the second sequence.InputThe first line contains an integer t (1 \leq t \leq 1000) — the number of test cases.The next 2t lines contain descriptions of the test cases. The first line of each test case description contains an integer n (1 \le n \le 2 \cdot 10^5) — permutation size. The second line of the description contains n space-separated integers p_i (1 \le p_i \le n; all p_i are all unique) — elements of the permutation.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputPrint t lines, each line containing the answer to the corresponding test case. The answer to a test case should contain n space-separated integer numbers — the elements of the lexicographically smallest permutation that is possible to find in the deque after executing the described algorithm.ExampleInput
5
4
3 1 2 4
3
3 2 1
3
3 1 2
2
1 2
2
2 1
Output
1 3 2 4
1 2 3
1 3 2
1 2
1 2
NoteOne of the ways to get a lexicographically smallest permutation [1, 3, 2, 4] from the permutation [3, 1, 2, 4] (the first sample test case) is described in the problem statement. | 5
4
3 1 2 4
3
3 2 1
3
3 1 2
2
1 2
2
2 1
| 1 3 2 4 1 2 3 1 3 2 1 2 1 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*1000'] |
D. Productive Meetingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn important meeting is to be held and there are exactly n people invited. At any moment, any two people can step back and talk in private. The same two people can talk several (as many as they want) times per meeting.Each person has limited sociability. The sociability of the i-th person is a non-negative integer a_i. This means that after exactly a_i talks this person leaves the meeting (and does not talk to anyone else anymore). If a_i = 0, the i-th person leaves the meeting immediately after it starts.A meeting is considered most productive if the maximum possible number of talks took place during it.You are given an array of sociability a, determine which people should talk to each other so that the total number of talks is as large as possible.InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases.The next 2t lines contain descriptions of the test cases.The first line of each test case description contains an integer n (2 \le n \le 2 \cdot 10^5) —the number of people in the meeting. The second line consists of n space-separated integers a_1, a_2, \dots, a_n (0 \le a_i \le 2 \cdot 10^5) — the sociability parameters of all people. It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5. It is also guaranteed that the sum of all a_i (over all test cases and all i) does not exceed 2 \cdot 10^5.OutputPrint t answers to all test cases.On the first line of each answer print the number k — the maximum number of talks possible in a meeting.On each of the next k lines print two integers i and j (1 \le i, j \le n and i \neq j) — the numbers of people who will have another talk.If there are several possible answers, you may print any of them.ExampleInput
8
2
2 3
3
1 2 3
4
1 2 3 4
3
0 0 2
2
6 2
3
0 0 2
5
8 2 0 1 1
5
0 1 0 0 6
Output
2
1 2
1 2
3
1 3
2 3
2 3
5
1 3
2 4
2 4
3 4
3 4
0
2
1 2
1 2
0
4
1 2
1 5
1 4
1 2
1
5 2
| 8
2
2 3
3
1 2 3
4
1 2 3 4
3
0 0 2
2
6 2
3
0 0 2
5
8 2 0 1 1
5
0 1 0 0 6
| 2 1 2 1 2 3 1 3 2 3 2 3 5 1 3 2 4 2 4 3 4 3 4 0 2 1 2 1 2 0 4 1 2 1 5 1 4 1 2 1 5 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'graphs', 'greedy', '*1400'] |
C. Tickstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCasimir has a rectangular piece of paper with a checkered field of size n \times m. Initially, all cells of the field are white.Let us denote the cell with coordinates i vertically and j horizontally by (i, j). The upper left cell will be referred to as (1, 1) and the lower right cell as (n, m).Casimir draws ticks of different sizes on the field. A tick of size d (d > 0) with its center in cell (i, j) is drawn as follows: First, the center cell (i, j) is painted black. Then exactly d cells on the top-left diagonally to the center and exactly d cells on the top-right diagonally to the center are also painted black. That is all the cells with coordinates (i - h, j \pm h) for all h between 0 and d are painted. In particular, a tick consists of 2d + 1 black cells. An already painted cell will remain black if painted again. Below you can find an example of the 4 \times 9 box, with two ticks of sizes 2 and 3. You are given a description of a checkered field of size n \times m. Casimir claims that this field came about after he drew some (possibly 0) ticks on it. The ticks could be of different sizes, but the size of each tick is at least k (that is, d \ge k for all the ticks).Determine whether this field can indeed be obtained by drawing some (possibly none) ticks of sizes d \ge k or not.InputThe first line contains an integer t (1 \leq t \leq 100) — the number test cases.The following lines contain the descriptions of the test cases. The first line of the test case description contains the integers n, m, and k (1 \le k \le n \le 10; 1 \le m \le 19) — the field size and the minimum size of the ticks that Casimir drew. The following n lines describe the field: each line consists of m characters either being '.' if the corresponding cell is not yet painted or '*' otherwise.OutputPrint t lines, each line containing the answer to the corresponding test case. The answer to a test case should be YES if the given field can be obtained by drawing ticks of at least the given size and NO otherwise.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answers).ExampleInput
8
2 3 1
*.*
...
4 9 2
*.*.*...*
.*.*...*.
..*.*.*..
.....*...
4 4 1
*.*.
****
.**.
....
5 5 1
.....
*...*
.*.*.
..*.*
...*.
5 5 2
.....
*...*
.*.*.
..*.*
...*.
4 7 1
*.....*
.....*.
..*.*..
...*...
3 3 1
***
***
***
3 5 1
*...*
.***.
.**..
Output
NO
YES
YES
YES
NO
NO
NO
NO
NoteThe first sample test case consists of two asterisks neither of which can be independent ticks since ticks of size 0 don't exist.The second sample test case is already described in the statement (check the picture in the statement). This field can be obtained by drawing ticks of sizes 2 and 3, as shown in the figure.The field in the third sample test case corresponds to three ticks of size 1. Their center cells are marked with \color{blue}{\text{blue}}, \color{red}{\text{red}} and \color{green}{\text{green}} colors: *.*.*\color{blue}{\textbf{*}}**.\color{green}{\textbf{*}}\color{red}{\textbf{*}}.....The field in the fourth sample test case could have been obtained by drawing two ticks of sizes 1 and 2. Their vertices are marked below with \color{blue}{\text{blue}} and \color{red}{\text{red}} colors respectively: .....*...*.*.*...\color{red}{\textbf{*}}.*...\color{blue}{\textbf{*}}.The field in the fifth sample test case can not be obtained because k = 2, and the last asterisk in the fourth row from the top with coordinates (4, 5) can only be a part of a tick of size 1.The field in the sixth sample test case can not be obtained because the top left asterisk (1, 1) can't be an independent tick, since the sizes of the ticks must be positive, and cannot be part of a tick with the center cell in the last row, since it is separated from it by a gap (a point, '.') in (2, 2).In the seventh sample test case, similarly, the field can not be obtained by the described process because the asterisks with coordinates (1, 2) (second cell in the first row), (3, 1) and (3, 3) (leftmost and rightmost cells in the bottom) can not be parts of any ticks. | 8
2 3 1
*.*
...
4 9 2
*.*.*...*
.*.*...*.
..*.*.*..
.....*...
4 4 1
*.*.
****
.**.
....
5 5 1
.....
*...*
.*.*.
..*.*
...*.
5 5 2
.....
*...*
.*.*.
..*.*
...*.
4 7 1
*.....*
.....*.
..*.*..
...*...
3 3 1
***
***
***
3 5 1
*...*
.***.
.**..
| NO YES YES YES NO NO NO NO | 2 seconds | 256 megabytes | ['greedy', 'implementation', '*1500'] |
B. Shifting Sorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe new generation external memory contains an array of integers a[1 \ldots n] = [a_1, a_2, \ldots, a_n].This type of memory does not support changing the value of an arbitrary element. Instead, it allows you to cut out any segment of the given array, cyclically shift (rotate) it by any offset and insert it back into the same place.Technically, each cyclic shift consists of two consecutive actions: You may select arbitrary indices l and r (1 \le l < r \le n) as the boundaries of the segment. Then you replace the segment a[l \ldots r] with it's cyclic shift to the left by an arbitrary offset d. The concept of a cyclic shift can be also explained by following relations: the sequence [1, 4, 1, 3] is a cyclic shift of the sequence [3, 1, 4, 1] to the left by the offset 1 and the sequence [4, 1, 3, 1] is a cyclic shift of the sequence [3, 1, 4, 1] to the left by the offset 2. For example, if a = [1, \color{blue}{3, 2, 8}, 5], then choosing l = 2, r = 4 and d = 2 yields a segment a[2 \ldots 4] = [3, 2, 8]. This segment is then shifted by the offset d = 2 to the left, and you get a segment [8, 3, 2] which then takes the place of of the original elements of the segment. In the end you get a = [1, \color{blue}{8, 3, 2}, 5].Sort the given array a using no more than n cyclic shifts of any of its segments. Note that you don't need to minimize the number of cyclic shifts. Any method that requires n or less cyclic shifts will be accepted.InputThe first line contains an integer t (1 \leq t \leq 1000) — the number of test cases.The next 2t lines contain the descriptions of the test cases. The first line of each test case description contains an integer n (2 \leq n \leq 50) — the length of the array. The second line consists of space-separated elements of the array a_i (-10^9 \leq a_i \leq 10^9). Elements of array a may repeat and don't have to be unique.OutputPrint t answers to all input test cases. The first line of the answer of each test case should contain an integer k (0 \le k \le n) — the number of actions to sort the array. The next k lines should contain descriptions of the actions formatted as "l r d" (without quotes) where l and r (1 \le l < r \le n) are the boundaries of the segment being shifted, while d (1 \le d \le r - l) is the offset value. Please remember that only the cyclic shifts to the left are considered so the chosen segment will be shifted by the offset d to the to the left.Note that you are not required to find the minimum number of cyclic shifts needed for sorting. Any sorting method where the number of shifts does not exceed n will be accepted.If the given array a is already sorted, one of the possible answers is k = 0 and an empty sequence of cyclic shifts.If there are several possible answers, you may print any of them.ExampleInput
4
2
2 1
3
1 2 1
4
2 4 1 3
5
2 5 1 4 3
Output
1
1 2 1
1
1 3 2
3
2 4 1
2 3 1
1 3 2
4
2 4 2
1 5 3
1 2 1
1 3 1
NoteExplanation of the fourth data set in the example: The segment a[2 \ldots 4] is selected and is shifted to the left by 2: [2, \color{blue}{5, 1, 4}, 3] \longrightarrow [2, \color{blue}{4, 5, 1}, 3] The segment a[1 \ldots 5] is then selected and is shifted to the left by 3: [\color{blue}{2, 4, 5, 1, 3}] \longrightarrow [\color{blue}{1, 3, 2, 4, 5}] After that the segment a[1 \ldots 2] is selected and is shifted to the left by 1: [\color{blue}{1, 3}, 2, 4, 5] \longrightarrow [\color{blue}{3, 1}, 2, 4, 5] And in the end the segment a[1 \ldots 3] is selected and is shifted to the left by 1: [\color{blue}{3, 1, 2}, 4, 5] \longrightarrow [\color{blue}{1, 2, 3}, 4, 5] | 4
2
2 1
3
1 2 1
4
2 4 1 3
5
2 5 1 4 3
| 1 1 2 1 1 1 3 2 3 2 4 1 2 3 1 1 3 2 4 2 4 2 1 5 3 1 2 1 1 3 1 | 2 seconds | 256 megabytes | ['implementation', 'sortings', '*1100'] |
A. Casimir's String Solitairetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCasimir has a string s which consists of capital Latin letters 'A', 'B', and 'C' only. Each turn he can choose to do one of the two following actions: he can either erase exactly one letter 'A' and exactly one letter 'B' from arbitrary places of the string (these letters don't have to be adjacent); or he can erase exactly one letter 'B' and exactly one letter 'C' from arbitrary places in the string (these letters don't have to be adjacent). Therefore, each turn the length of the string is decreased exactly by 2. All turns are independent so for each turn, Casimir can choose any of two possible actions.For example, with s = "ABCABC" he can obtain a string s = "ACBC" in one turn (by erasing the first occurrence of 'B' and the second occurrence of 'A'). There are also many other options for a turn aside from this particular example.For a given string s determine whether there is a sequence of actions leading to an empty string. In other words, Casimir's goal is to erase all letters from the string. Is there a way to do this?InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases.Each test case is described by one string s, for which you need to determine if it can be fully erased by some sequence of turns. The string s consists of capital letters 'A', 'B', 'C' and has a length from 1 to 50 letters, inclusive.OutputPrint t lines, each line containing the answer to the corresponding test case. The answer to a test case should be YES if there is a way to fully erase the corresponding string and NO otherwise.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answers).ExampleInput
6
ABACAB
ABBA
AC
ABC
CABCBB
BCBCBCBCBCBCBCBC
Output
NO
YES
NO
NO
YES
YES
| 6
ABACAB
ABBA
AC
ABC
CABCBB
BCBCBCBCBCBCBCBC
| NO YES NO NO YES YES | 2 seconds | 256 megabytes | ['math', 'strings', '*800'] |
M. The Mindtime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.In this problem, you need to come up with a strategy for a cooperative game. This game is played by two players. Each player receives 5 cards. Each card has a random integer between 1 and 100 on it. It is guaranteed that all numbers on cards are distinct.The goal of the game is to play a card with a minimal number on it out of all 10 cards dealt to the players before any other card. The problem is that each player can only see their own cards and cannot communicate with another player in any way.The game consists of 5 turns. During each turn, players simultaneously make a move. Each player can either play their smallest card or do nothing. If on some turn the smallest card is played, and no other card is played on or before that turn, players win. If two cards are played at the same turn or if after all 5 turns, no card is still played, players lose.Players cannot communicate, so a strategy for the game should only be based on 5 cards that the player has. You can describe a strategy as five numbers 0.0 \le p_i \le 1.0, \sum_{i=1}^{5}p_i \le 1, where p_i — the probability of playing the player's smallest card in their hand on i-th turn. If you know the cards dealt to the players, and the strategies that players choose, you can compute the probability of winning by a simple formula. You will be given n=1000 randomly generated hands of 5 cards. You need to generate a strategy for each of the hands to maximize the probability of winning. After the judge program receives all n strategies, it generates all possible valid pairs of those hands (pairs which have the same numbers are discarded), and computes a probability of winning based on two strategies provided by your program. To ensure that answers for different hands are independent, you must output a strategy for a hand and flush the standard output before reading information about the next hand.If the average probability of winning a game is more than 85% over all valid pairs of hands, the test is considered passed. This problem contains the sample test and 20 randomly generated tests with n = 1000.InputThe first line contains one integer n — the number of hands. It is guaranteed that n = 1000 for all cases except the first sample case. Each of the next n lines contains 5 numbers a_i (1 \le a_i \le 100, a_i < a_{i+1}) — the cards in the hand. It is guaranteed that each possible set of 5 cards has an equal probability of being chosen. OutputFor each of the n hands you need to output 5 numbers 0.0 \le p_i \le 1.0, \sum_{i=1}^{5}p_i \le 1, where p_i — probability of playing the smallest card on i-th turn.ExampleInput
2
2 12 27 71 100
22 29 39 68 90Output
0.8 0.2 0.0 0.0 0.0
0.0 0.2 0.2 0.2 0.3 NoteIn the example test there is only one valid pair of hands. The winning probability for the example output is equal to 0.8 + 0.2 \cdot (1 - 0.2) = 0.96. Also note that the second player will not play a card at all with probability 0.1. | 2
2 12 27 71 100
22 29 39 68 90 | 0.8 0.2 0.0 0.0 0.0 0.0 0.2 0.2 0.2 0.3 | 2 seconds | 1024 megabytes | ['constructive algorithms', 'interactive', 'probabilities', '*2700'] |
L. Labyrinthtime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIn a dream, Lucy found herself in a labyrinth. This labyrinth consists of n rooms, connected by m passages (i-th passage is w_i cm wide). Each passage can be traversed in both directions. It is guaranteed that it is possible to get from any room to any other room. But this is not an ordinary labyrinth — each room in this labyrinth contains a magic candy. When Lucy eats this magic candy, she is getting wider. Specifically, if she eats candy from room i she becomes wider by c_i cm. Note that she is not obliged to eat candy the first time she visits a particular room, but she can eat each candy only once. Unfortunately, passages in this labyrinth are pretty narrow, so after eating some candy, Lucy can get too wide and will not be able to traverse them — her width should not be greater than the width of the corresponding passage.Lucy starts her journey in a room number 1. She wants to eat all the candies. After that, she will just wake up, so she does not have to be able to return to the room 1. She realizes that with her current width, she may not be able to do so, so she plans a workout before embarking on her journey. Lucy wants to know if it is possible to start with some positive width and still eat all the candies. If yes, then what is the maximal starting width with which it is possible.InputThe first line contains two integers, n and m (2 \le n \le 10^5; n - 1 \le m \le 10^5) — the number of rooms and the number of passages.The second line contains n integers — c_i (1 \le c_i \le 10^9).Next m lines contain three integers each — a_i, b_i and w_i (1 \le a_i, b_i \le n; a_i \ne b_i; 1 \le w_i \le 10^9) describing passage that connects rooms a_i and b_i and is w_i cm wide. It is guaranteed that the resulting labyrinth is connected and there is at most one passage between any pair of rooms.OutputIf it is possible to eat all the candies, output the maximal possible starting width, otherwise output -1.ExamplesInput
3 3
1 2 3
1 2 4
1 3 4
2 3 6
Output
3
Input
2 1
1 1
1 2 1
Output
-1
| 3 3
1 2 3
1 2 4
1 3 4
2 3 6
| 3 | 2 seconds | 1024 megabytes | ['binary search', 'dsu', 'greedy', '*2400'] |
K. Kingdom of Islandstime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThe Kingdom of Islands consists of p islands. As the king, you rule over the whole kingdom, while each island is ruled over by one or several jarls under your rule. In total, there are n jarls under your jurisdiction.Each island of the kingdom has its own strong traditions, so jarls that rule over the same island support each other and never have conflicts. The downsides of such strength are cultural conflicts between people inhabiting different islands. Thus, two jarls that rule over different islands are in conflict.However, recent years brought a few changes to traditional relations between the jarls. To your knowledge, there are exactly k pairs of jarls such that relationships between two jarls in the pair are different from the traditional. That is, if two jarls of the pair you know rule over the same island, these jarls are in conflict. If they rule over different islands, then they overcome cultural disagreement and there is no conflict between them anymore.As a true responsible king, you are worried about whether the kingdom is close to a major conflict. In order to estimate the current situation, you would like to find the largest possible group of jarls such that every two jarls in the group are in conflict.InputThe first line of the input consists of two integers p and n (1 \le p \le n \le 10^5; 1 \le p \le 10^4).The second line consists of n integers s_1, s_2, \ldots, s_n (1 \le s_i \le p). The integer s_i denotes that the i-th jarl rules over the island number s_i. It is guaranteed that each island is ruled by at least one jarl.The third line consists of a single integer k (0 \le k \le 20).Then k lines follow. The j-th of these lines consists of two distinct integers a_j and b_j (1 \le a_j < b_j \le n), denoting that the relation between the a_j-th jarl and the b_j-th jarl differs from traditional. It is guaranteed that no pair of jarls appears twice in this list.OutputIn the first line print a single integer q between 1 and n — the largest possible number of jarls in a pairwise conflicting group. In the second line print q distinct integers between 1 and n — the numbers of jarls in the group. The numbers of jarls can be printed in any order.ExamplesInput
4 4
1 2 3 4
1
2 3
Output
3
1 4 2 Input
2 4
1 1 2 2
1
3 4
Output
3
2 4 3 Input
4 8
1 1 1 2 2 3 4 4
7
1 2
2 3
3 6
4 5
5 7
2 7
3 8
Output
6
8 6 5 4 2 1 NoteThe conflict graph for the last sample testcase is given below. Each circle represents an island. | 4 4
1 2 3 4
1
2 3
| 3 1 4 2 | 2 seconds | 1024 megabytes | ['brute force', 'graphs', 'implementation', '*2800'] |
J. Just Kingdomtime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThe Just Kingdom is ruled by a king and his n lords, numbered 1 to n. Each of the lords is a vassal of some overlord, who might be the king himself, or a different lord closer to the king. The king, and all his lords, are just and kind.Each lord has certain needs, which can be expressed as a certain amount of money they need. However, if a lord, or the king, receives any money, they will first split it equally between all their vassals who still have unmet needs. Only if all the needs of all their vassals are met, they will take the money to fulfill their own needs. If there is any money left over, they will return the excess to their overlord (who follows the standard procedure for distributing money).At the beginning of the year, the king receives a certain sum of tax money and proceeds to split it according to the rules above. If the amount of tax money is greater than the total needs of all the lords, the procedure guarantees everybody's needs will be fulfilled, and the excess money will be left with the king. However, if there is not enough money, some lords will not have their needs met.For each lord, determine the minimum amount of tax money the king has to receive so that this lord's needs are met.InputThe first line of the input contains the number of lords n (0 \le n \le 3 \cdot 10^5). Each of the next n lines describes one of the lords. The i-th line contains two integers: o_i (0 \le o_i < i) — the index of the overlord of the i-th lord (with zero meaning the king is the overlord), and m_i (1 \le m_i \le 10^6) — the amount of money the i-th lord needs.OutputPrint n integer numbers t_i. The i-th number should be the minimum integer amount of tax money the king has to receive for which the needs of the i-th lord will be met.ExampleInput
5
0 2
1 2
0 1
1 1
0 5
Output
11
7
3
5
11
NoteIn the sample input, if the king receives 5 units of tax money, he will split it equally between his vassals — the lords 1, 3, and 5, with each receiving \frac{5}{3} of money. Lord 1 will split the money equally between his vassals — 2 and 4, with each receiving \frac{5}{6}. Lord 5 will keep the money (having no vassals). Lord 3 will keep 1 unit of money, and give the remaining \frac{2}{3} to the king. The king will then split the \frac{2}{3} between the vassals with unmet needs — 1 and 5, passing \frac{1}{3} to each. Lord 5 will keep the extra cash (now having a total of 2, still not enough to meet his needs). Lord 1 will split it equally between his vassals, and the extra \frac{1}{6} will be enough to meet the needs of lord 4. | 5
0 2
1 2
0 1
1 1
0 5
| 11 7 3 5 11 | 5 seconds | 1024 megabytes | ['brute force', 'data structures', 'dfs and similar', '*3100'] |
I. Interactive Raystime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Your goal is to find a circle on a plane by shooting rays and getting the distance to the circle as a result. Interactor has three hidden integer parameters that are determined in advance for each test, but which you don't know — x_c, y_c, and r_c. (x_c, y_c) are coordinates of the circle's center and r_c is its radius. The absolute values of x_c, y_c, and r_c do not exceed 10^5, and 1 \leq r_c \leq \sqrt{x_c^2 + y_c^2} - 1.You can shoot rays that extend from the origin (0,0) and go via a point (x_q,y_q) with the integer coordinates you specify. For each ray, you get a distance from the ray to the circle or 0 if the ray intersects the circle. InteractionThe interaction starts with your program printing a query to the standard output and finishes when your program finds and prints the answer to the problem.Each query has a form of "? x_q y_q", where x_q and y_q are integers (|x_q|, |y_q| \le 10^6; x_q \ne 0 or y_q \ne 0). The interactor outputs a line with a single floating-point number — the distance between a query ray and a circle that is precise to 10^{-10} by an absolute value.Your program can make the next query, read the output, and so on. You are allowed to do at most 60 queries. At the end of the interaction, print the answer line "! x_c y_c r_c", flush the output and exit.Note, that the output of the interactor is actually rounded to the 10-th digit after a decimal point, so if you are stress-testing your solution locally, make sure that you also perform the corresponding rounding.ExampleInput
? 0 -10
? 10 -10
? 10 0
? 10 10
? 10 20
? 10 30
! 20 10 10Output
12.360679775
11.2132034356
0.0
0.0
3.416407865
5.8113883008Note Illustration of the queries from the example interaction. | ? 0 -10
? 10 -10
? 10 0
? 10 10
? 10 20
? 10 30
! 20 10 10 | 12.360679775 11.2132034356 0.0 0.0 3.416407865 5.8113883008 | 2 seconds | 1024 megabytes | ['geometry', 'interactive', '*3300'] |
H. Higher Order Functionstime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHelen studies functional programming and she is fascinated with a concept of higher order functions — functions that are taking other functions as parameters. She decides to generalize the concept of the function order and to test it on some examples. For her study, she defines a simple grammar of types. In her grammar, a type non-terminal T is defined as one of the following grammar productions, together with \textrm{order}(T), defining an order of the corresponding type: "()" is a unit type, \textrm{order}(\textrm{"}\texttt{()}\textrm{"}) = 0. "(" T ")" is a parenthesized type, \textrm{order}(\textrm{"}\texttt{(}\textrm{"}\,T\,\textrm{"}\texttt{)}\textrm{"}) = \textrm{order}(T). T_1 "->" T_2 is a functional type, \textrm{order}(T_1\,\textrm{"}\texttt{->}\textrm{"}\,T_2) = max(\textrm{order}(T_1) + 1, \textrm{order}(T_2)). The function constructor T_1 "->" T_2 is right-to-left associative, so the type "()->()->()" is the same as the type "()->(()->())" of a function returning a function, and it has an order of 1. While "(()->())->()" is a function that has an order-1 type "(()->())" as a parameter, and it has an order of 2. Helen asks for your help in writing a program that computes an order of the given type.InputThe single line of the input contains a string consisting of characters '(', ')', '-', and '>' that describes a type that is valid according to the grammar from the problem statement. The length of the line is at most 10^4 characters.OutputPrint a single integer — the order of the given type.ExamplesInput
()
Output
0
Input
()->()
Output
1
Input
()->()->()
Output
1
Input
(()->())->()
Output
2
Input
()->(((()->())->()->())->())
Output
3
| ()
| 0 | 2 seconds | 1024 megabytes | ['implementation', 'strings', '*1700'] |
G. Game of Chancetime limit per test6 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThe King wants to marry off his daughter, and he wants her husband to have the greatest innate luckiness possible. To find such a person he decided to hold a heads-or-tails tournament. If person A with luckiness x and person B with luckiness y play heads-or-tails against each other, person A wins with probability x/(x+y). The tournament has several rounds. Each round some participants are split into pairs. Each pair plays against each other, and the loser leaves the tournament. The participants are numbered from 1 to n. During the first round, a number k (1 \le k \le n) is selected such that n-k/2 is a power of 2 (such k always exists and is unique). Only participants numbered from 1 to k take part in the first round. It ensures that in all other rounds the number of participants is the power of 2. During other rounds, all the participants who still have not left the tournament take part. If during some round, participants numbered p_1 < \ldots < p_{2m} take part, then they are split into pairs in the following manner: participant p_{2i-1} plays against participant p_{2i} for each i from 1 to m. The rounds are held until only one participant is left. He is declared the winner of the tournament and he will marry the King's daughter. The princess can't wait to find out who is her future husband. She asked every participant to tell her his luckiness. Assuming they did not lie, she wants to know the probability of each participant winning the tournament. As you are the best friend of the princess, she asks you to help her.InputThe first line of the input contains the number of participants, n (2 \le n \le 3 \cdot 10^5). The second line of the input contains n integer numbers, a_1, \ldots, a_{n} (1 \le a_i \le 10^9). The luckiness of the i-th participant equals to a_i.OutputPrint n numbers p_i. The i-th number should be the probability of the i-th participant winning the tournament. The absolute error of your answer must not exceed 10^{-9}.ExampleInput
5
1 4 1 1 4
Output
0.026 0.3584 0.0676 0.0616 0.4864
NoteHere is an example of a tournament bracket, showing the winning probability in each pair. | 5
1 4 1 1 4
| 0.026 0.3584 0.0676 0.0616 0.4864 | 6 seconds | 1024 megabytes | ['math', 'probabilities', '*3500'] |
F. Framing Picturestime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputLife has been discovered on Venus! What is more, the life forms appear to be convex polygons. An international consortium is designing a probe to send to Venus to take pictures, but they need to estimate the bandwidth needed to send back pictures.When the probe takes a picture of a life form and wishes to send it back to Earth, the bandwidth required is proportional to the area of the bounding box (in other words, the smallest axis-aligned rectangle that contains the life-form). The shape and size of the life forms are known, but the orientation relative to the camera is random. You must thus determine the expected (average) area of the bounding box across all orientations.InputThe input describes the shape of a life form as a convex polygon in two dimensions.The first line of input contains an integer n (3 \le n \le 200\,000) — the number of vertices. The remaining n lines each contain two integers x and y (-10^9 \le x, y \le 10^9) — the coordinates of a vertex. The vertices are given in counterclockwise order, and no three vertices lie on a straight line.OutputOutput a single line containing the expected area of the bounding box of the polygon. Your answer should have an absolute or relative error of at most 10^{-6}.ExamplesInput
4
0 0
10 0
10 10
0 10
Output
163.661977237
Input
5
0 0
10 0
15 8
5 20
-5 7
Output
365.666028588
NoteThe pictures show example life forms and various camera orientations. | 4
0 0
10 0
10 10
0 10
| 163.661977237 | 2 seconds | 1024 megabytes | ['geometry', '*2900'] |
E. Easy Schedulingtime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputEonathan Eostar decided to learn the magic of multiprocessor systems. He has a full binary tree of tasks with height h. In the beginning, there is only one ready task in the tree — the task in the root. At each moment of time, p processes choose at most p ready tasks and perform them. After that, tasks whose parents were performed become ready for the next moment of time. Once the task becomes ready, it stays ready until it is performed. You shall calculate the smallest number of time moments the system needs to perform all the tasks.InputThe first line of the input contains the number of tests t (1 \leq t \leq 5\cdot 10^5). Each of the next t lines contains the description of a test. A test is described by two integers h (1 \leq h \leq 50) and p (1 \leq p \leq 10^4) — the height of the full binary tree and the number of processes. It is guaranteed that all the tests are different.OutputFor each test output one integer on a separate line — the smallest number of time moments the system needs to perform all the tasks.ExampleInput
3
3 1
3 2
10 6
Output
7
4
173
NoteLet us consider the second test from the sample input. There is a full binary tree of height 3 and there are two processes. At the first moment of time, there is only one ready task, 1, and p_1 performs it. At the second moment of time, there are two ready tasks, 2 and 3, and the processes perform them. At the third moment of time, there are four ready tasks, 4, 5, 6, and 7, and p_1 performs 6 and p_2 performs 5. At the fourth moment of time, there are two ready tasks, 4 and 7, and the processes perform them. Thus, the system spends 4 moments of time to perform all the tasks. | 3
3 1
3 2
10 6
| 7 4 173 | 2 seconds | 1024 megabytes | ['implementation', 'math', '*1200'] |
D. Dragon Curvetime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA dragon curve is a self-similar fractal curve. In this problem, it is a curve that consists of straight-line segments of the same length connected at right angles. A simple way to construct a dragon curve is as follows: take a strip of paper, fold it in half n times in the same direction, then partially unfold it such that the segments are joined at right angles. This is illustrated here: In this example, a dragon curve of order 3 is constructed. In general, a dragon curve of a higher order will have a dragon curve of a lower order as its prefix. This allows us to define a dragon curve of infinite order, which is the limit of dragon curves of a finite order as the order approaches infinity.Consider four dragon curves of infinite order. Each starts at the origin (the point (0,0)), and the length of each segment is \sqrt2. The first segments of the curves end at the points (1,1), (-1,1), (-1,-1) and (1,-1), respectively. The first turn of each curve is left (that is, the second segment of the first curve ends at the point (0,2)). In this case, every segment is a diagonal of an axis-aligned unit square with integer coordinates, and it can be proven that there is exactly one segment passing through every such square.Given a point (x,y), your task is to find on which of the four curves lies the segment passing through the square with the opposite corners at (x,y) and (x+1,y+1), as well as the position of that segment on that curve. The curves are numbered 1 through 4. Curve 1 goes through (1,1), 2 through (-1,1), 3 through (-1,-1), and 4 through (1,-1). The segments are numbered starting with 1.InputThe first line contains an integer n (1\le n\le2\cdot10^5) — the number of test cases.Each of the following n lines contains two integers x and y (-10^9\le x,y\le10^9) — the coordinates.OutputFor each test case, print a line containing two integers — the first is the index of the curve (an integer between 1 and 4, inclusive), and the second is the position on the curve (the first segment has the position 1).ExampleInput
5
0 0
-2 0
-7 -7
5 -9
9 9
Output
1 1
2 2
3 189
4 186
2 68
NoteYou can use this illustration to debug your solution: | 5
0 0
-2 0
-7 -7
5 -9
9 9
| 1 1 2 2 3 189 4 186 2 68 | 5 seconds | 1024 megabytes | ['*3200'] |
C. Cactus Lady and her Cingtime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputCactus lady loves her cactuses very much. Especially she likes a small cactus named Cing. Cing can be seen as a connected undirected graph in which every vertex lies on at most one simple cycle. Intuitively, a cactus is a generalization of a tree where some cycles are allowed. Multiedges (multiple edges between a pair of vertices) and loops (edges that connect a vertex to itself) are not allowed.She bought a special grid for her special little cactus Cing. This grid can be represented as a graph consisting of two paths of length 400\,000, u_{(0, -200\,000)} - u_{(0, -199\,999)} - \ldots - u_{(0, 200\,000)} and u_{(1, -200\,000)} - u_{(1, -199\,999)} - \ldots - u_{(1, 200\,000)}, connected together by 400\,001 edges (u_{(0, i)}, u_{(1, i)}) for each i. In other words, a grid can be seen as a ladder. Cactus lady wants to know whether she can embed Cing into this grid, i.e., map each vertex of the cactus onto a separate vertex of the grid while each edge of the cactus will be mapped onto some edge of the grid.InputThe first line contains an integer t — the number of test cases.Each test case begins with a line containing two integers n and m — the number of vertices and the number of edges in a given cactus, respectively (1 \le n \le 200\,000; 0 \le m \le 250\,000).Each of the following m lines contains two integers v and u, describing the edges of the cactus (1 \le v, u \le n, u \ne v).The total sum of all n in the input doesn't exceed 200\,000.OutputPrint an answer for each test case in the same order the cases appear in the input.For each test case print "No" in the first line, if no layout exists.Otherwise print "Yes" in the first line, and the following n lines describing the layout. The i-th of these n lines should contain two integers x_i and y_i, the location of the i-th vertex (0 \le x_i \le 1; -200\,000 \le y_i \le 200\,000).ExampleInput
5
4 3
1 2
2 3
3 4
8 7
1 2
3 2
2 4
4 5
4 6
6 7
6 8
5 4
1 2
1 3
1 4
1 5
8 9
1 2
2 3
3 4
1 4
4 5
5 6
6 7
7 8
5 8
10 10
1 2
2 3
3 4
4 5
5 6
6 1
3 7
4 8
1 9
6 10Output
Yes
0 0
0 1
1 1
1 2
Yes
0 3
1 3
1 4
1 2
0 2
1 1
0 1
1 0
No
Yes
0 0
1 0
1 1
0 1
0 2
0 3
1 3
1 2
Yes
1 1
1 2
1 3
0 3
0 2
0 1
1 4
0 4
1 0
0 0NoteEmpty lines between test cases are for clarity. In real test cases there are no empty lines.In these notes, we consider the embeddings for tests 2 and 4.We start with the embedding for test 2. Here goes the embedding for test 4. | 5
4 3
1 2
2 3
3 4
8 7
1 2
3 2
2 4
4 5
4 6
6 7
6 8
5 4
1 2
1 3
1 4
1 5
8 9
1 2
2 3
3 4
1 4
4 5
5 6
6 7
7 8
5 8
10 10
1 2
2 3
3 4
4 5
5 6
6 1
3 7
4 8
1 9
6 10 | Yes 0 0 0 1 1 1 1 2 Yes 0 3 1 3 1 4 1 2 0 2 1 1 0 1 1 0 No Yes 0 0 1 0 1 1 0 1 0 2 0 3 1 3 1 2 Yes 1 1 1 2 1 3 0 3 0 2 0 1 1 4 0 4 1 0 0 0 | 5 seconds | 1024 megabytes | ['*3500'] |
B. Building Forest Trailstime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThere are n villages lying equidistant on a circle in the middle of a thick, impassable forest. From ancient times, it was impossible to move from one village to another, but technical progress has changed a lot. Now, there is a technology to build passable trails in the forest. The building process consists of m events. Each event is either building a trail or querying if two villages are connected. Trails are built as straight lines connecting two villages. After a trail is built, anybody can walk along the trail from one village to another. Moreover, if two trails cross, anybody can turn at the intersection, and if other trails leave a village you have just reached, they can also be used to walk along. So, for example, if villages are numbered 1 to 6 in the order around the circle, and there are trails 1 to 3, 2 to 4, and 4 to 6, then all villages, except the 5-th, are reachable from the 1-st village.Given a list of m events, for each query, find if two given villages are reachable from each other at that moment.InputThe first line contains two integers n (2 \le n \le 2\cdot 10^5) and m (1 \le m \le 3\cdot 10^5) — the number of villages and the number of events respectively. Next m lines contain events. Each event description consists of three integers e (e is 1 or 2), v (1 \le v \le n), and u (1 \le u \le n, u \ne v). If e = 1, then the event is building a trail between villages v and u. If e = 2, then the event is a query if the villages v and u are connected. It is guaranteed that each trail is built at most once. Villages are numbered 1 to n in clockwise order around the circle. OutputFor each query print one character '0' if villages are not reachable, and '1' if villages are reachable from each other. Print answers for all queries as a single string in one line.ExamplesInput
6 9
1 1 3
1 4 6
2 3 4
1 2 4
2 1 2
2 1 3
2 1 4
2 6 1
2 5 3
Output
011110
Input
2 5
2 1 2
2 2 1
1 1 2
2 1 2
2 2 1
Output
0011
| 6 9
1 1 3
1 4 6
2 3 4
1 2 4
2 1 2
2 1 3
2 1 4
2 6 1
2 5 3
| 011110 | 3 seconds | 1024 megabytes | ['data structures', 'dsu', '*2800'] |
A. Anti-Tetristime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputLet us consider the game "Sticky Tetris". In this game, there is a field of n \times m squares. Tiles appear on the field and the player can move the tiles. Each tile is a 4-connected set of at most 7 squares.Each new tile appears in any position that fits inside the field, does not intersect any other tile, and the top cell of the tile is at the top row of the field. The player can move the tile left, right, and down, and at any moment the tile must still entirely fit inside the field and must not intersect other tiles. The player can stop the tile at any position at any time. After that, it cannot be moved. Since this is "Sticky Tetris," the tile will not fall once stopped.You are given a final configuration of a "Sticky Tetris" game. You need to restore a sequence of steps that leads to that configuration if it exists.InputThe first line contains two integers n and m (1 \le n, m \le 50) — the size of the playing field.The next n lines contain a string of m characters each. Each character could be either a '.', or lowercase English letter. Connected components of the same letter correspond to a single tile. Each tile consists of at most 7 squares.OutputIf there is no solution, print -1.Otherwise, print k — the number of different tiles that are placed on the field.On the next k lines print the sequence of steps for each of the tiles in the order they are placed. Each line consists of a number x followed by a string with steps. x (1 \le x \le m) is the starting column of the leftmost square in the top row of the tile. The string consists of characters 'L' (for left), 'R' (for right), and 'D' (for down), describing the path of that tile, ending with a single character 'S' (for stop). The final position of the tile determines which tile is being placed. The string with steps can have at most n \cdot m + 1 characters.ExamplesInput
3 2
aa
ab
aa
Output
2
2 DS
1 S
Input
5 6
....dd
.ccccd
.cbbdd
.aab.a
aabbaa
Output
5
2 DDDS
4 DDLS
6 DDDS
2 DS
5 S
Input
5 3
...
aab
abb
aab
.bb
Output
-1
| 3 2
aa
ab
aa
| 2 2 DS 1 S | 2 seconds | 1024 megabytes | ['constructive algorithms', 'graphs', 'shortest paths', '*2800'] |
A. Communication Routing Challengetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn optical communication networks, appropriate path planning can improve the utilization of communication resources and bring a smooth communication experience to users. The following figure shows an inter-satellite optical communication network. User messages are sent from one terrestrial base station (nodes 4 to 7) and transmitted through satellites (nodes 0 to 3) in space to another terrestrial base station (nodes 4 to 7). In the preceding figures, there are communication connections (edges for short) between base stations and satellites and between satellites. The base stations and satellites are referred to as nodes. User messages are transmitted on these edges and referred to as flows. Some users may make video calls with friends, and some users may send short messages to their family members. Therefore, the message traffic (called flow rate) of each user differs. There are many parallel edges (for example, edges 0, 1, and 2) between two nodes, and the capacity of each edge also differs. Larger capacity indicates that more user messages can be transmitted, as well as shorter transmission distance indicates lower latency and better communication quality. Nodes also have their internal structure. As shown below, some edges inside a node cannot communicate with each other because these edges (constrained edge pair) are not fully connected. For example, edge 5 and edge 7 inside node 2 cannot communicate with each other, and therefore flows cannot pass through node 2 by traversing the two unconnected edges. Now, in the input network, the source node, target node, and required flow rate for each user flow are specified. Because network resources are limited, paths may not be successfully calculated for all user flows. We hope that you can provide a solution with the highest score.Note, that all edges are undirected, so flows may come in both directions, edges has both capacity and length (named distance), several flows may use the same edge, flows may come through the same edge in opposite directions simultaneously, for the purpose of this problem, there is no difference between satellites and base stations, so flows may come through several base stations before reaching the destination station. Constraints The capacity of each edge is limited. The total rate of all flows carried by an edge cannot exceed the capacity of the edge. The capacity limits the total flows in both directions. The calculated flow path does not allow loops or cycles. Due to the hardware limitation inside satellites, the number of flows passing through a node (including source and target node) cannot exceed the site flow limit (\mathit{SFL}) of the node. The value of \mathit{SFL} is 200. There are multiple parallel edges between two nodes, which may belong to different groups. Links in each group are managed by the same chip on a node, and there is a group flow limit (\mathit{GFL}). The total number of different flows on all the edges in a group cannot exceed the \mathit{GFL} of the group. The value of \mathit{GFL} is 100. By default, all edges are connected to each other in each node. But there are some constrained edge pairs — the pairs of edges inside specified nodes that cannot communicate with each other. You can make no more than 2 submissions on each 5 minutes interval. InputThe first line contains four integers separated by space: \mathit{NodeCount}, \mathit{EdgeCount}, \mathit{ConstrainedCount}, and \mathit{FlowCount}. 8 \le \mathit{NodeCount} \le 1400, 15 \le \mathit{EdgeCount} \le 15000, 3 \le \mathit{ConstrainedCount} \le 3600, 1 \le \mathit{FlowCount} \le 14000. The next \mathit{EdgeCount} lines contain information about the network. Each line contains six integers: \mathit{EdgeID}, \mathit{GroupID}, \mathit{StartNodeID}, \mathit{EndNodeID}, \mathit{Distance}, and \mathit{Capacity}. 0 \le \mathit{EdgeID} < \mathit{EdgeCount}, 0 \le \mathit{GroupID} \le 4500, 0 \le \mathit{StartNodeID}, \mathit{EndNodeID} < \mathit{NodeCount}, \mathit{StartNodeID} \ne \mathit{EndNodeID}, 100 \le \mathit{Distance} \le 10000, 1 < \mathit{Capacity} \le 10^5. It's guaranteed that only multiple edges may share the same \mathit{GroupID}.The next \mathit{ConstrainedCount} lines contain information about the edge pairs that are not connected in the specified nodes of the network. All other edges are connected to each other by default. Each line contains three integers: \mathit{NodeID}, \mathit{EdgeID}_1, and \mathit{EdgeID}_2. 0 \le \mathit{NodeID} < \mathit{NodeCount}, 0 \le \mathit{EdgeID}_1, \mathit{EdgeID}_2 < \mathit{EdgeCount}, \mathit{EdgeID}_1 \ne \mathit{EdgeID}_2. The next \mathit{FlowCount} lines contain information about the flows to be calculated. Each line contains four integers: \mathit{FlowID}, \mathit{SourceNode}, \mathit{TargetNode}, and \mathit{FlowRate}. 0 \le \mathit{FlowID} < \mathit{FlowCount}, 0 \le \mathit{SourceNode}, \mathit{TargetNode} < \mathit{NodeCount}, \mathit{SourceNode} \ne \mathit{TargetNode}, 2 \le \mathit{FlowRate} \le 12000 Don't forget that the \mathit{SFL} and \mathit{GFL} mentioned above are also important parameters.For the simplicity, both \mathit{EdgeID} and \mathit{FlowID} of the i-th (0-indexed) edge (flow) is always equal to i.OutputIn the first line, output the number of your success flows.Next, each line output edge information about the path that a flow passes through. The format is as follows: \mathit{FlowID}\ \mathit{EdgeID}_1\ \mathit{EdgeID}_2\ \mathit{EdgeID}_3\ \dots\ \mathit{EdgeID}_n.There is no requirement on the output sequence between flow paths, but edges in one flow must be outputted in order, from source node to target node. Please output all successfully calculated flow paths. For other flows that are not output, the checker determines that you have not found appropriate paths for the flows by default.Scoring The solutions that violate constraints, time out, or exceed the memory limit are invalid. According to the formula \mathit{Score}=\mathit{SuccessFlowNum}+\max \left(1-\left(\frac{\mathit{AvgDistance}}{1000000}\right),0\right), the solution with a higher score wins. (That is, the solution with more successfully planned flow paths wins. If two solutions have the same number of successfully planned flow paths, the solution with a smaller average of path distances wins. Output with 0 flow paths will be considered incorrect.) If two solutions have the same score, the solution submitted first wins. For multiple tests, the ranking is performed based on the sum of all tests. If the solution has no result on any test, it will be recorded as no result on the whole. Among your multiple submissions, the one with the highest score is the final score. The checker runs your solution on exactly one CPU core, so multithreading implementation will not provide any profit. You can make no more than 2 submissions on each 5 minutes interval. ExampleInput
8 15 3 1
0 0 0 1 100 1050
1 1 0 1 200 2200
2 1 0 1 200 99400
3 2 0 3 100 450
4 3 0 3 500 1120
5 4 1 2 1000 40000
6 5 2 3 600 10000
7 5 2 3 600 10000
8 6 1 4 120 2500
9 6 1 4 120 450
10 7 1 5 170 1250
11 8 2 5 200 2500
12 9 3 5 100 1250
13 10 3 6 300 1150
14 11 3 7 300 1100
2 5 7
2 6 7
2 6 11
0 4 6 100
Output
1
0 8 0 3 13
NoteThe total distance of a flow path is 620 (120 + 100 + 100 + 300 = 620). (Note: 0 9 10 12 13 is also a valid output result.) | 8 15 3 1
0 0 0 1 100 1050
1 1 0 1 200 2200
2 1 0 1 200 99400
3 2 0 3 100 450
4 3 0 3 500 1120
5 4 1 2 1000 40000
6 5 2 3 600 10000
7 5 2 3 600 10000
8 6 1 4 120 2500
9 6 1 4 120 450
10 7 1 5 170 1250
11 8 2 5 200 2500
12 9 3 5 100 1250
13 10 3 6 300 1150
14 11 3 7 300 1100
2 5 7
2 6 7
2 6 11
0 4 6 100
| 1 0 8 0 3 13 | 2 seconds | 512 megabytes | ['*special problem'] |
M. Managing Telephone Polestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMr. Chanek's city can be represented as a plane. He wants to build a housing complex in the city.There are some telephone poles on the plane, which is represented by a grid a of size (n + 1) \times (m + 1). There is a telephone pole at (x, y) if a_{x, y} = 1.For each point (x, y), define S(x, y) as the square of the Euclidean distance between the nearest pole and (x, y). Formally, the square of the Euclidean distance between two points (x_1, y_1) and (x_2, y_2) is (x_2 - x_1)^2 + (y_2 - y_1)^2.To optimize the building plan, the project supervisor asks you the sum of all S(x, y) for each 0 \leq x \leq n and 0 \leq y \leq m. Help him by finding the value of \sum_{x=0}^{n} {\sum_{y=0}^{m} {S(x, y)}}.InputThe first line contains two integers n and m (0 \leq n, m < 2000) — the size of the grid.Then (n + 1) lines follow, each containing (m + 1) integers a_{i, j} (0 \leq a_{i, j} \leq 1) — the grid denoting the positions of telephone poles in the plane. There is at least one telephone pole in the given grid.OutputOutput an integer denoting the value of \sum_{x=0}^{n} {\sum_{y=0}^{m} {S(x, y)}}.ExamplesInput
2 2
101
000
000
Output
18
Input
5 4
10010
00000
01000
00001
00100
00010
Output
36
Note In the first example, the nearest telephone pole for the points (0,0), (1,0), (2,0), (0,1), (1,1), and (2,1) is at (0, 0). While the nearest telephone pole for the points (0, 2), (1,2), and (2,2) is at (0, 2). Thus, \sum_{x=0}^{n} {\sum_{y=0}^{m} {S(x, y)}} = (0 + 1 + 4) + (1 + 2 + 5) + (0 + 1 + 4) = 18. | 2 2
101
000
000
| 18 | 2 seconds | 512 megabytes | ['data structures', 'geometry', '*2400'] |
L. Longest Array Deconstructiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMr. Chanek gives you a sequence a indexed from 1 to n. Define f(a) as the number of indices where a_i = i. You can pick an element from the current sequence and remove it, then concatenate the remaining elements together. For example, if you remove the 3-rd element from the sequence [4, 2, 3, 1], the resulting sequence will be [4, 2, 1]. You want to remove some elements from a in order to maximize f(a), using zero or more operations. Find the largest possible f(a).InputThe first line contains one integer n (1 \leq n \leq 2 \cdot 10^5) — the initial length of the sequence.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 2 \cdot 10^5) — the initial sequence a.OutputOutput an integer denoting the largest f(a) that can be obtained by doing zero or more operations.ExamplesInput
7
2 1 4 2 5 3 7
Output
3
Input
4
4 2 3 1
Output
2
NoteIn the first example, f(A) = 3 by doing the following operations.[2,1,\textbf{4},2,5,3,7] \rightarrow [\textbf{2},1,2,5,3,7] \rightarrow [1,2,5,3,\textbf{7}] \rightarrow [1,2,\textbf{5},3] \rightarrow [1,2,3]In the second example, f(A) = 2 and no additional operation is needed. | 7
2 1 4 2 5 3 7
| 3 | 2 seconds | 512 megabytes | ['data structures', 'divide and conquer', 'dp', 'sortings', '*2100'] |
K. Knitting Batiktime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMr. Chanek wants to knit a batik, a traditional cloth from Indonesia. The cloth forms a grid a with size n \times m. There are k colors, and each cell in the grid can be one of the k colors.Define a sub-rectangle as an ordered pair of two cells ((x_1, y_1), (x_2, y_2)), denoting the top-left cell and bottom-right cell (inclusively) of a sub-rectangle in a. Two sub-rectangles ((x_1, y_1), (x_2, y_2)) and ((x_3, y_3), (x_4, y_4)) have the same pattern if and only if the following holds: they have the same width (x_2 - x_1 = x_4 - x_3); they have the same height (y_2 - y_1 = y_4 - y_3); for every pair (i, j) where 0 \leq i \leq x_2 - x_1 and 0 \leq j \leq y_2 - y_1, the color of cells (x_1 + i, y_1 + j) and (x_3 + i, y_3 + j) are equal. Count the number of possible batik color combinations, such that the subrectangles ((a_x, a_y),(a_x + r - 1, a_y + c - 1)) and ((b_x, b_y),(b_x + r - 1, b_y + c - 1)) have the same pattern.Output the answer modulo 10^9 + 7.InputThe first line contains five integers n, m, k, r, and c (1 \leq n, m \leq 10^9, 1 \leq k \leq 10^9, 1 \leq r \leq \min(10^6, n), 1 \leq c \leq \min(10^6, m)) — the size of the batik, the number of colors, and size of the sub-rectangle.The second line contains four integers a_x, a_y, b_x, and b_y (1 \leq a_x, b_x \leq n, 1 \leq a_y, b_y \leq m) — the top-left corners of the first and second sub-rectangle. Both of the sub-rectangles given are inside the grid (1 \leq a_x + r - 1, b_x + r - 1 \leq n, 1 \leq a_y + c - 1, b_y + c - 1 \leq m).OutputOutput an integer denoting the number of possible batik color combinations modulo 10^9 + 7.ExamplesInput
3 3 2 2 2
1 1 2 2
Output
32
Input
4 5 170845 2 2
1 4 3 1
Output
756680455
NoteThe following are all 32 possible color combinations in the first example. | 3 3 2 2 2
1 1 2 2
| 32 | 2 seconds | 512 megabytes | ['implementation', 'math', '*2200'] |
J. Jeopardy of Dropped Ballstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMr. Chanek has a new game called Dropping Balls. Initially, Mr. Chanek has a grid a of size n \times mEach cell (x,y) contains an integer a_{x,y} denoting the direction of how the ball will move. a_{x,y}=1 — the ball will move to the right (the next cell is (x, y + 1)); a_{x,y}=2 — the ball will move to the bottom (the next cell is (x + 1, y)); a_{x,y}=3 — the ball will move to the left (the next cell is (x, y - 1)). Every time a ball leaves a cell (x,y), the integer a_{x,y} will change to 2. Mr. Chanek will drop k balls sequentially, each starting from the first row, and on the c_1, c_2, \dots, c_k-th (1 \leq c_i \leq m) columns.Determine in which column each ball will end up in (position of the ball after leaving the grid).InputThe first line contains three integers n, m, and k (1 \leq n, m \leq 1000, 1 \leq k \leq 10^5) — the size of the grid and the number of balls dropped by Mr. Chanek.The i-th of the next n lines contains m integers a_{i,1},a_{i,2},\ldots,a_{i,m} (1 \leq a_{i,j} \leq 3). It will satisfy a_{i, 1} \ne 3 and a_{i, m} \ne 1.The next line contains k integers c_1, c_2, \ldots, c_k (1 \leq c_i \leq m) — the balls' column positions dropped by Mr. Chanek sequentially.OutputOutput k integers — the i-th integer denoting the column where the i-th ball will end.ExamplesInput
5 5 3
1 2 3 3 3
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
1 2 1
Output
2 2 1
Input
1 2 2
1 3
1 2
Output
1 2
NoteIn the first example, the first ball will drop as follows. Note that the cell (1, 1) will change direction to the bottom direction. The second and third balls will drop as follows. All balls will be dropped from the first row and on the c_1, c_2, \dots, c_k-th columns respectively. A ball will stop dropping once it leaves the grid. | 5 5 3
1 2 3 3 3
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
1 2 1
| 2 2 1 | 2 seconds | 512 megabytes | ['binary search', 'brute force', 'dsu', 'implementation', '*1500'] |
I. Illusions of the Deserttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputChanek Jones is back, helping his long-lost relative Indiana Jones, to find a secret treasure in a maze buried below a desert full of illusions.The map of the labyrinth forms a tree with n rooms numbered from 1 to n and n - 1 tunnels connecting them such that it is possible to travel between each pair of rooms through several tunnels.The i-th room (1 \leq i \leq n) has a_i illusion rate. To go from the x-th room to the y-th room, there must exist a tunnel between x and y, and it takes \max(|a_x + a_y|, |a_x - a_y|) energy. |z| denotes the absolute value of z.To prevent grave robbers, the maze can change the illusion rate of any room in it. Chanek and Indiana would ask q queries.There are two types of queries to be done: 1\ u\ c — The illusion rate of the x-th room is changed to c (1 \leq u \leq n, 0 \leq |c| \leq 10^9). 2\ u\ v — Chanek and Indiana ask you the minimum sum of energy needed to take the secret treasure at room v if they are initially at room u (1 \leq u, v \leq n). Help them, so you can get a portion of the treasure!InputThe first line contains two integers n and q (2 \leq n \leq 10^5, 1 \leq q \leq 10^5) — the number of rooms in the maze and the number of queries.The second line contains n integers a_1, a_2, \ldots, a_n (0 \leq |a_i| \leq 10^9) — inital illusion rate of each room.The i-th of the next n-1 lines contains two integers s_i and t_i (1 \leq s_i, t_i \leq n), meaning there is a tunnel connecting s_i-th room and t_i-th room. The given edges form a tree.The next q lines contain the query as described. The given queries are valid.OutputFor each type 2 query, output a line containing an integer — the minimum sum of energy needed for Chanek and Indiana to take the secret treasure.ExampleInput
6 4
10 -9 2 -1 4 -6
1 5
5 4
5 6
6 2
6 3
2 1 2
1 1 -3
2 1 2
2 3 3
Output
39
32
0
Note In the first query, their movement from the 1-st to the 2-nd room is as follows. 1 \rightarrow 5 — takes \max(|10 + 4|, |10 - 4|) = 14 energy. 5 \rightarrow 6 — takes \max(|4 + (-6)|, |4 - (-6)|) = 10 energy. 6 \rightarrow 2 — takes \max(|-6 + (-9)|, |-6 - (-9)|) = 15 energy. In total, it takes 39 energy.In the second query, the illusion rate of the 1-st room changes from 10 to -3.In the third query, their movement from the 1-st to the 2-nd room is as follows. 1 \rightarrow 5 — takes \max(|-3 + 4|, |-3 - 4|) = 7 energy. 5 \rightarrow 6 — takes \max(|4 + (-6)|, |4 - (-6)|) = 10 energy. 6 \rightarrow 2 — takes \max(|-6 + (-9)|, |-6 - (-9)|) = 15 energy. Now, it takes 32 energy. | 6 4
10 -9 2 -1 4 -6
1 5
5 4
5 6
6 2
6 3
2 1 2
1 1 -3
2 1 2
2 3 3
| 39 32 0 | 3 seconds | 512 megabytes | ['data structures', 'trees', '*2300'] |
H. Holiday Wall Ornamentstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Winter holiday will be here soon. Mr. Chanek wants to decorate his house's wall with ornaments. The wall can be represented as a binary string a of length n. His favorite nephew has another binary string b of length m (m \leq n).Mr. Chanek's nephew loves the non-negative integer k. His nephew wants exactly k occurrences of b as substrings in a. However, Mr. Chanek does not know the value of k. So, for each k (0 \leq k \leq n - m + 1), find the minimum number of elements in a that have to be changed such that there are exactly k occurrences of b in a.A string s occurs exactly k times in t if there are exactly k different pairs (p,q) such that we can obtain s by deleting p characters from the beginning and q characters from the end of t.InputThe first line contains two integers n and m (1 \leq m \leq n \leq 500) — size of the binary string a and b respectively.The second line contains a binary string a of length n.The third line contains a binary string b of length m.OutputOutput n - m + 2 integers — the (k+1)-th integer denotes the minimal number of elements in a that have to be changed so there are exactly k occurrences of b as a substring in a.ExampleInput
9 3
100101011
101
Output
1 1 0 1 6 -1 -1 -1
NoteFor k = 0, to make the string a have no occurrence of 101, you can do one character change as follows.100101011 \rightarrow 100100011For k = 1, you can also change a single character.100101011 \rightarrow 100001011For k = 2, no changes are needed. | 9 3
100101011
101
| 1 1 0 1 6 -1 -1 -1 | 3 seconds | 512 megabytes | ['dp', 'strings', '*2200'] |
G. GCD Festivaltime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMr. Chanek has an array a of n integers. The prettiness value of a is denoted as:\sum_{i=1}^{n} {\sum_{j=1}^{n} {\gcd(a_i, a_j) \cdot \gcd(i, j)}}where \gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y.In other words, the prettiness value of an array a is the total sum of \gcd(a_i, a_j) \cdot \gcd(i, j) for all pairs (i, j).Help Mr. Chanek find the prettiness value of a, and output the result modulo 10^9 + 7!InputThe first line contains an integer n (2 \leq n \leq 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^5).OutputOutput an integer denoting the prettiness value of a modulo 10^9 + 7.ExampleInput
5
3 6 2 1 4
Output
77
| 5
3 6 2 1 4
| 77 | 3 seconds | 512 megabytes | ['math', 'number theory', '*2200'] |
F. Finding Expected Valuetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMr. Chanek opened a letter from his fellow, who is currently studying at Singanesia. Here is what it says.Define an array b (0 \leq b_i < k) with n integers. While there exists a pair (i, j) such that b_i \ne b_j, do the following operation: Randomly pick a number i satisfying 0 \leq i < n. Note that each number i has a probability of \frac{1}{n} to be picked. Randomly Pick a number j satisfying 0 \leq j < k. Change the value of b_i to j. It is possible for b_i to be changed to the same value. Denote f(b) as the expected number of operations done to b until all elements of b are equal. You are given two integers n and k, and an array a (-1 \leq a_i < k) of n integers. For every index i with a_i = -1, replace a_i with a random number j satisfying 0 \leq j < k. Let c be the number of occurrences of -1 in a. There are k^c possibilites of a after the replacement, each with equal probability of being the final array.Find the expected value of f(a) modulo 10^9 + 7. Formally, let M = 10^9 + 7. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.After reading the letter, Mr. Chanek gave the task to you. Solve it for the sake of their friendship!InputThe first line contains two integers n and k (2 \leq n \leq 10^5, 2 \leq k \leq 10^9). The second line contains n integers a_1, a_2, \ldots, a_n (-1 \leq a_i < k).OutputOutput an integer denoting the expected value of f(a) modulo 10^9 + 7.ExamplesInput
2 2
0 1
Output
2
Input
2 2
0 -1
Output
1
Input
3 3
0 1 1
Output
12
Input
3 3
-1 -1 -1
Output
11
Input
10 9
-1 0 -1 1 1 2 2 3 3 3
Output
652419213
| 2 2
0 1
| 2 | 3 seconds | 512 megabytes | ['math', '*2900'] |
E. Eye-Pleasing City Park Tourtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is a city park represented as a tree with n attractions as its vertices and n - 1 rails as its edges. The i-th attraction has happiness value a_i.Each rail has a color. It is either black if t_i = 0, or white if t_i = 1. Black trains only operate on a black rail track, and white trains only operate on a white rail track. If you are previously on a black train and want to ride a white train, or you are previously on a white train and want to ride a black train, you need to use 1 ticket.The path of a tour must be a simple path — it must not visit an attraction more than once. You do not need a ticket the first time you board a train. You only have k tickets, meaning you can only switch train types at most k times. In particular, you do not need a ticket to go through a path consisting of one rail color.Define f(u, v) as the sum of happiness values of the attractions in the tour (u, v), which is a simple path that starts at the u-th attraction and ends at the v-th attraction. Find the sum of f(u,v) for all valid tours (u, v) (1 \leq u \leq v \leq n) that does not need more than k tickets, modulo 10^9 + 7.InputThe first line contains two integers n and k (2 \leq n \leq 2 \cdot 10^5, 0 \leq k \leq n-1) — the number of attractions in the city park and the number of tickets you have.The second line contains n integers a_1, a_2,\ldots, a_n (0 \leq a_i \leq 10^9) — the happiness value of each attraction.The i-th of the next n - 1 lines contains three integers u_i, v_i, and t_i (1 \leq u_i, v_i \leq n, 0 \leq t_i \leq 1) — an edge between vertices u_i and v_i with color t_i. The given edges form a tree.OutputOutput an integer denoting the total happiness value for all valid tours (u, v) (1 \leq u \leq v \leq n), modulo 10^9 + 7.ExamplesInput
5 0
1 3 2 6 4
1 2 1
1 4 0
3 2 1
2 5 0
Output
45
Input
3 1
1 1 1
1 2 1
3 2 0
Output
10
| 5 0
1 3 2 6 4
1 2 1
1 4 0
3 2 1
2 5 0
| 45 | 4 seconds | 512 megabytes | ['data structures', 'trees', '*2600'] |
D. Divisible by Twenty-Fivetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMr. Chanek has an integer represented by a string s. Zero or more digits have been erased and are denoted by the character _. There are also zero or more digits marked by the character X, meaning they're the same digit.Mr. Chanek wants to count the number of possible integer s, where s is divisible by 25. Of course, s must not contain any leading zero. He can replace the character _ with any digit. He can also replace the character X with any digit, but it must be the same for every character X.As a note, a leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation. For example, 0025 has two leading zeroes. An exception is the integer zero, (0 has no leading zero, but 0000 has three leading zeroes).InputOne line containing the string s (1 \leq |s| \leq 8). The string s consists of the characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, _, and X.OutputOutput an integer denoting the number of possible integer s.ExamplesInput
25
Output
1
Input
_00
Output
9
Input
_XX
Output
9
Input
0
Output
1
Input
0_25
Output
0
NoteIn the first example, the only possible s is 25.In the second and third example, s \in \{100, 200,300,400,500,600,700,800,900\}.In the fifth example, all possible s will have at least one leading zero. | 25
| 1 | 2 seconds | 512 megabytes | ['brute force', 'dfs and similar', 'dp', '*1800'] |
C. Cyclic Sumtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDenote a cyclic sequence of size n as an array s such that s_n is adjacent to s_1. The segment s[r, l] where l < r is the concatenation of s[r, n] and s[1, l].You are given an array a consisting of n integers. Define b as the cyclic sequence obtained from concatenating m copies of a. Note that b has size n \cdot m.You are given an integer k where k = 1 or k is a prime number. Find the number of different segments in b where the sum of elements in the segment is divisible by k.Two segments are considered different if the set of indices of the segments are different. For example, when n = 3 and m = 2, the set of indices for segment s[2, 5] is \{2, 3, 4, 5\}, and for segment s[5, 2] is \{5, 6, 1, 2\}. In particular, the segments s[1, 6], s[2,1], \ldots, s[6, 5] are considered as the same segment.Output the answer modulo 10^9 + 7.InputThe first line contains three integers n, m, and k (1 \leq n, m, k \leq 2 \cdot 10^5, k = 1 or k is a prime number).The second line contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 2 \cdot 10^5).OutputOutput an integer denoting the number of different segments in b where the sum of elements in the segment is divisible by k, modulo 10^9 + 7.ExamplesInput
5 1 5
1 2 3 4 3
Output
4
Input
5 1 5
1 2 3 4 5
Output
5
Input
5 4 5
1 2 3 4 5
Output
125
NoteIn the first example, all valid segments are [1,4], [2, 3], [3, 5], and [4, 2].In the second example, one of the valid segments is [1, 5]. | 5 1 5
1 2 3 4 3
| 4 | 3 seconds | 512 megabytes | ['data structures', 'fft', 'number theory', '*3000'] |
B. Building an Amusement Parktime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMr. Chanek lives in a city represented as a plane. He wants to build an amusement park in the shape of a circle of radius r. The circle must touch the origin (point (0, 0)).There are n bird habitats that can be a photo spot for the tourists in the park. The i-th bird habitat is at point p_i = (x_i, y_i). Find the minimum radius r of a park with at least k bird habitats inside. A point is considered to be inside the park if and only if the distance between p_i and the center of the park is less than or equal to the radius of the park. Note that the center and the radius of the park do not need to be integers.In this problem, it is guaranteed that the given input always has a solution with r \leq 2 \cdot 10^5.InputThe first line contains two integers n and k (1 \leq n \leq 10^5, 1 \leq k \leq n) — the number of bird habitats in the city and the number of bird habitats required to be inside the park.The i-th of the next n lines contains two integers x_i and y_i (0 \leq |x_i|, |y_i| \leq 10^5) — the position of the i-th bird habitat.OutputOutput a single real number r denoting the minimum radius of a park with at least k bird habitats inside. It is guaranteed that the given input always has a solution with r \leq 2 \cdot 10^5.Your answer is considered correct if its absolute or relative error does not exceed 10^{-4}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-4}.ExamplesInput
8 4
-3 1
-4 4
1 5
2 2
2 -2
-2 -4
-1 -1
-6 0
Output
3.1622776589
Input
1 1
0 0
Output
0.0000000000
NoteIn the first example, Mr. Chanek can put the center of the park at (-3, -1) with radius \sqrt{10} \approx 3.162. It can be proven this is the minimum r.The following illustrates the first example. The blue points represent bird habitats and the red circle represents the amusement park. | 8 4
-3 1
-4 4
1 5
2 2
2 -2
-2 -4
-1 -1
-6 0
| 3.1622776589 | 5 seconds | 512 megabytes | ['binary search', 'geometry', '*2300'] |
A. Another Sorting Problemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAndi and Budi were given an assignment to tidy up their bookshelf of n books. Each book is represented by the book title — a string s_i numbered from 1 to n, each with length m. Andi really wants to sort the book lexicographically ascending, while Budi wants to sort it lexicographically descending.Settling their fight, they decided to combine their idea and sort it asc-desc-endingly, where the odd-indexed characters will be compared ascendingly, and the even-indexed characters will be compared descendingly.A string a occurs before a string b in asc-desc-ending order if and only if in the first position where a and b differ, the following holds: if it is an odd position, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b; if it is an even position, the string a has a letter that appears later in the alphabet than the corresponding letter in b. InputThe first line contains two integers n and m (1 \leq n \cdot m \leq 10^6).The i-th of the next n lines contains a string s_i consisting of m uppercase Latin letters — the book title. The strings are pairwise distinct.OutputOutput n integers — the indices of the strings after they are sorted asc-desc-endingly.ExampleInput
5 2
AA
AB
BB
BA
AZ
Output
5 2 1 3 4
NoteThe following illustrates the first example. | 5 2
AA
AB
BB
BA
AZ
| 5 2 1 3 4 | 2 seconds | 512 megabytes | ['data structures', 'sortings', 'strings', '*1100'] |
F. Occurrencestime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA subarray of array a from index l to the index r is the array [a_l, a_{l+1}, \dots, a_{r}]. The number of occurrences of the array b in the array a is the number of subarrays of a such that they are equal to b.You are given n arrays A_1, A_2, \dots, A_n; the elements of these arrays are integers from 1 to k. You have to build an array a consisting of m integers from 1 to k in such a way that, for every given subarray A_i, the number of occurrences of A_i in the array a is not less than the number of occurrences of each non-empty subarray of A_i in a. Note that if A_i doesn't occur in a, and no subarray of A_i occurs in a, this condition is still met for A_i.Your task is to calculate the number of different arrays a you can build, and print it modulo 998244353.InputThe first line contains three integers n, m and k (1 \le n, m, k \le 3 \cdot 10^5) — the number of the given arrays, the desired length of the array a, and the upper bound on the values in the arrays.Then n lines follow. The i-th line represents the array A_i. The first integer in the i-th line is c_i (1 \le c_i \le m) — the number of elements in A_i; then, c_i integers from 1 to k follow — the elements of the array A_i.Additional constraint on the input: \sum\limits_{i=1}^n c_i \le 3 \cdot 10^5; i. e., the number of elements in the given arrays in total does not exceed 3 \cdot 10^5.OutputPrint one integer — the number of different arrays a you can build, taken modulo 998244353.ExamplesInput
2 4 3
2 1 2
1 3
Output
5
Input
2 4 3
2 1 2
3 3 2 1
Output
0
Input
1 42 1337
2 13 31
Output
721234447
| 2 4 3
2 1 2
1 3
| 5 | 7 seconds | 512 megabytes | ['combinatorics', 'dfs and similar', 'dp', 'dsu', 'fft', 'graphs', '*2700'] |
E. Coloringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA matrix of size n \times m, such that each cell of it contains either 0 or 1, is considered beautiful if the sum in every contiguous submatrix of size 2 \times 2 is exactly 2, i. e. every "square" of size 2 \times 2 contains exactly two 1's and exactly two 0's.You are given a matrix of size n \times m. Initially each cell of this matrix is empty. Let's denote the cell on the intersection of the x-th row and the y-th column as (x, y). You have to process the queries of three types: x y -1 — clear the cell (x, y), if there was a number in it; x y 0 — write the number 0 in the cell (x, y), overwriting the number that was there previously (if any); x y 1 — write the number 1 in the cell (x, y), overwriting the number that was there previously (if any). After each query, print the number of ways to fill the empty cells of the matrix so that the resulting matrix is beautiful. Since the answers can be large, print them modulo 998244353.InputThe first line contains three integers n, m and k (2 \le n, m \le 10^6; 1 \le k \le 3 \cdot 10^5) — the number of rows in the matrix, the number of columns, and the number of queries, respectively.Then k lines follow, the i-th of them contains three integers x_i, y_i, t_i (1 \le x_i \le n; 1 \le y_i \le m; -1 \le t_i \le 1) — the parameters for the i-th query.OutputFor each query, print one integer — the number of ways to fill the empty cells of the matrix after the respective query, taken modulo 998244353.ExampleInput
2 2 7
1 1 1
1 2 1
2 1 1
1 1 0
1 2 -1
2 1 -1
1 1 -1
Output
3
1
0
1
2
3
6
| 2 2 7
1 1 1
1 2 1
2 1 1
1 1 0
1 2 -1
2 1 -1
1 1 -1
| 3 1 0 1 2 3 6 | 2 seconds | 256 megabytes | ['combinatorics', 'constructive algorithms', 'implementation', 'math', '*2500'] |
D. The Strongest Buildtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan is playing yet another roguelike computer game. He controls a single hero in the game. The hero has n equipment slots. There is a list of c_i items for the i-th slot, the j-th of them increases the hero strength by a_{i,j}. The items for each slot are pairwise distinct and are listed in the increasing order of their strength increase. So, a_{i,1} < a_{i,2} < \dots < a_{i,c_i}.For each slot Ivan chooses exactly one item. Let the chosen item for the i-th slot be the b_i-th item in the corresponding list. The sequence of choices [b_1, b_2, \dots, b_n] is called a build.The strength of a build is the sum of the strength increases of the items in it. Some builds are banned from the game. There is a list of m pairwise distinct banned builds. It's guaranteed that there's at least one build that's not banned.What is the build with the maximum strength that is not banned from the game? If there are multiple builds with maximum strength, print any of them.InputThe first line contains a single integer n (1 \le n \le 10) — the number of equipment slots.The i-th of the next n lines contains the description of the items for the i-th slot. First, one integer c_i (1 \le c_i \le 2 \cdot 10^5) — the number of items for the i-th slot. Then c_i integers a_{i,1}, a_{i,2}, \dots, a_{i,c_i} (1 \le a_{i,1} < a_{i,2} < \dots < a_{i,c_i} \le 10^8).The sum of c_i doesn't exceed 2 \cdot 10^5.The next line contains a single integer m (0 \le m \le 10^5) — the number of banned builds.Each of the next m lines contains a description of a banned build — a sequence of n integers b_1, b_2, \dots, b_n (1 \le b_i \le c_i).The builds are pairwise distinct, and there's at least one build that's not banned.OutputPrint the build with the maximum strength that is not banned from the game. If there are multiple builds with maximum strength, print any of them.ExamplesInput
3
3 1 2 3
2 1 5
3 2 4 6
2
3 2 3
3 2 2
Output
2 2 3
Input
3
3 1 2 3
2 1 5
3 2 4 6
2
3 2 3
2 2 3
Output
1 2 3
Input
3
3 1 2 3
2 1 5
3 2 4 6
2
3 2 3
2 2 3
Output
3 2 2
Input
4
1 10
1 4
1 7
1 3
0
Output
1 1 1 1
| 3
3 1 2 3
2 1 5
3 2 4 6
2
3 2 3
3 2 2
| 2 2 3 | 3 seconds | 256 megabytes | ['binary search', 'brute force', 'data structures', 'dfs and similar', 'graphs', 'greedy', 'hashing', 'implementation', '*2000'] |
C. Slay the Dragontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Petya learned about a new game "Slay the Dragon". As the name suggests, the player will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To do this, the player has a squad of n heroes, the strength of the i-th hero is equal to a_i.According to the rules of the game, exactly one hero should go kill the dragon, all the others will defend the castle. If the dragon's defense is equal to x, then you have to send a hero with a strength of at least x to kill it. If the dragon's attack power is y, then the total strength of the heroes defending the castle should be at least y.The player can increase the strength of any hero by 1 for one gold coin. This operation can be done any number of times.There are m dragons in the game, the i-th of them has defense equal to x_i and attack power equal to y_i. Petya was wondering what is the minimum number of coins he needs to spend to defeat the i-th dragon.Note that the task is solved independently for each dragon (improvements are not saved).InputThe first line contains a single integer n (2 \le n \le 2 \cdot 10^5) — number of heroes.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{12}), where a_i is the strength of the i-th hero.The third line contains a single integer m (1 \le m \le 2 \cdot 10^5) — the number of dragons.The next m lines contain two integers each, x_i and y_i (1 \le x_i \le 10^{12}; 1 \le y_i \le 10^{18}) — defense and attack power of the i-th dragon.OutputPrint m lines, i-th of which contains a single integer — the minimum number of coins that should be spent to defeat the i-th dragon.ExampleInput
4
3 6 2 3
5
3 12
7 9
4 14
1 10
8 7
Output
1
2
4
0
2
NoteTo defeat the first dragon, you can increase the strength of the third hero by 1, then the strength of the heroes will be equal to [3, 6, 3, 3]. To kill the dragon, you can choose the first hero.To defeat the second dragon, you can increase the forces of the second and third heroes by 1, then the strength of the heroes will be equal to [3, 7, 3, 3]. To kill the dragon, you can choose a second hero.To defeat the third dragon, you can increase the strength of all the heroes by 1, then the strength of the heroes will be equal to [4, 7, 3, 4]. To kill the dragon, you can choose a fourth hero.To defeat the fourth dragon, you don't need to improve the heroes and choose a third hero to kill the dragon.To defeat the fifth dragon, you can increase the strength of the second hero by 2, then the strength of the heroes will be equal to [3, 8, 2, 3]. To kill the dragon, you can choose a second hero. | 4
3 6 2 3
5
3 12
7 9
4 14
1 10
8 7
| 1 2 4 0 2 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'sortings', 'ternary search', '*1300'] |
B. Combinatorics Homeworktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given four integer values a, b, c and m.Check if there exists a string that contains: a letters 'A'; b letters 'B'; c letters 'C'; no other letters; exactly m pairs of adjacent equal letters (exactly m such positions i that the i-th letter is equal to the (i+1)-th one). InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.Each of the next t lines contains the description of the testcase — four integers a, b, c and m (1 \le a, b, c \le 10^8; 0 \le m \le 10^8).OutputFor each testcase print "YES" if there exists a string that satisfies all the requirements. Print "NO" if there are no such strings.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).ExampleInput
3
2 2 1 0
1 1 1 1
1 2 3 2
Output
YES
NO
YES
NoteIn the first testcase strings "ABCAB" or "BCABA" satisfy the requirements. There exist other possible strings.In the second testcase there's no way to put adjacent equal letters if there's no letter that appears at least twice.In the third testcase string "CABBCC" satisfies the requirements. There exist other possible strings. | 3
2 2 1 0
1 1 1 1
1 2 3 2
| YES NO YES | 2 seconds | 256 megabytes | ['combinatorics', 'greedy', 'math', '*1100'] |
A. Regular Bracket Sequencestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You are given an integer n. Your goal is to construct and print exactly n different regular bracket sequences of length 2n.InputThe first line contains one integer t (1 \le t \le 50) — the number of test cases.Each test case consists of one line containing one integer n (1 \le n \le 50).OutputFor each test case, print n lines, each containing a regular bracket sequence of length exactly 2n. All bracket sequences you output for a testcase should be different (though they may repeat in different test cases). If there are multiple answers, print any of them. It can be shown that it's always possible.ExampleInput
3
3
1
3
Output
()()()
((()))
(()())
()
((()))
(())()
()(())
| 3
3
1
3
| ()()() ((())) (()()) () ((())) (())() ()(()) | 2 seconds | 512 megabytes | ['constructive algorithms', '*800'] |
F. Stationstime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in a row numbered from 1 to n.The cities will be building broadcasting stations. The station in the i-th city has height h_i and range w_i. It can broadcast information to city j if the following constraints are met: i \le j \le w_i, and for each k such that i < k \le j, the following condition holds: h_k < h_i. In other words, the station in city i can broadcast information to city j if j \ge i, j is in the range of i-th station, and i is strictly highest on the range from i to j (including city j).At the beginning, for every city i, h_i = 0 and w_i = i.Then q events will take place. During i-th event one of the following will happen: City c_i will rebuild its station so that its height will be strictly highest among all stations and w_{c_i} will be set to g_i. Let b_j be the number of stations that can broadcast information to city j. Print the sum of b_j over all j satisfying l_i \le j \le r_i. Your task is to react to all events and print answers to all queries.InputThe first line contains two integers n and q (1 \le n, q \le 2\cdot10^5) — number of cities and number of events.Then q lines follow. The i-th line begins with an integer p_i (p_i = 1 or p_i = 2).If p_i = 1 a station will be rebuilt. Then two integers c_i and g_i (1 \le c_i \le g_i \le n) follow — the city in which the station is rebuilt and its new broadcasting range.If p_i = 2 you are given a query. Then two integers l_i and r_i (1 \le l_i \le r_i \le n) follow — the range of cities in the query.OutputFor each query, print in a single line the sum of b_j over the given interval.ExamplesInput
1 3
2 1 1
1 1 1
2 1 1
Output
1
1
Input
5 10
1 3 4
2 3 5
1 1 5
2 1 5
1 4 5
2 2 4
1 2 3
2 1 3
1 5 5
2 2 5
Output
4
10
5
4
5
NoteIn the first test case, only station 1 reaches city 1 before and after it is rebuilt.In the second test case, after each rebuild, the array b looks as follows: [1, 1, 1, 2, 1]; [1, 2, 2, 3, 2]; [1, 2, 2, 1, 2]; [1, 1, 2, 1, 2]; [1, 1, 2, 1, 1]. | 1 3
2 1 1
1 1 1
2 1 1
| 1 1 | 2.5 seconds | 256 megabytes | ['data structures', '*3400'] |
E. Polygontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a strictly convex polygon with n vertices.You will make k cuts that meet the following conditions: each cut is a segment that connects two different nonadjacent vertices; two cuts can intersect only at vertices of the polygon. Your task is to maximize the area of the smallest region that will be formed by the polygon and those k cuts.InputThe first line contains two integers n, k (3 \le n \le 200, 0 \le k \le n-3).The following n lines describe vertices of the polygon in anticlockwise direction. The i-th line contains two integers x_i, y_i (|x_i|, |y_i| \le 10^8) — the coordinates of the i-th vertex.It is guaranteed that the polygon is convex and that no two adjacent sides are parallel.OutputPrint one integer: the maximum possible area of the smallest region after making k cuts multiplied by 2.ExamplesInput
8 4
-2 -4
2 -2
4 2
1 5
0 5
-4 4
-5 0
-5 -1
Output
11
Input
6 3
2 -2
2 -1
1 2
0 2
-2 1
-1 0
Output
3
NoteIn the first example, it's optimal to make cuts between the following pairs of vertices: (-2, -4) and (4, 2), (-2, -4) and (1, 5), (-5, -1) and (1, 5), (-5, 0) and (0, 5). Points (-5, -1), (1, 5), (0, 5), (-5, 0) determine the smallest region with double area of 11. In the second example, it's optimal to make cuts between the following pairs of vertices: (2, -1) and (0, 2), (2, -1) and (1, 0), (-1, 0) and (0, 2). Points (2, -2), (2, -1), (-1, 0) determine one of the smallest regions with double area of 3. | 8 4
-2 -4
2 -2
4 2
1 5
0 5
-4 4
-5 0
-5 -1
| 11 | 3 seconds | 256 megabytes | ['binary search', 'dp', 'geometry', '*3000'] |
D. Bridge Clubtime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are currently n hot topics numbered from 0 to n-1 at your local bridge club and 2^n players numbered from 0 to 2^n-1. Each player holds a different set of views on those n topics, more specifically, the i-th player holds a positive view on the j-th topic if i\ \&\ 2^j > 0, and a negative view otherwise. Here \& denotes the bitwise AND operation.You are going to organize a bridge tournament capable of accommodating at most k pairs of players (bridge is played in teams of two people). You can select teams arbitrarily while each player is in at most one team, but there is one catch: two players cannot be in the same pair if they disagree on 2 or more of those n topics, as they would argue too much during the play.You know that the i-th player will pay you a_i dollars if they play in this tournament. Compute the maximum amount of money that you can earn if you pair the players in your club optimally.InputThe first line contains two integers n, k (1 \le n \le 20, 1 \le k \le 200) — the number of hot topics and the number of pairs of players that your tournament can accommodate.The second line contains 2^n integers a_0, a_1, \dots, a_{2^n-1} (0 \le a_i \le 10^6) — the amounts of money that the players will pay to play in the tournament.OutputPrint one integer: the maximum amount of money that you can earn if you pair the players in your club optimally under the above conditions.ExamplesInput
3 1
8 3 5 7 1 10 3 2
Output
13
Input
2 3
7 4 5 7
Output
23
Input
3 2
1 9 1 5 7 8 1 1
Output
29
NoteIn the first example, the best we can do is to pair together the 0-th player and the 2-nd player resulting in earnings of 8 + 5 = 13 dollars. Although pairing the 0-th player with the 5-th player would give us 8 + 10 = 18 dollars, we cannot do this because those two players disagree on 2 of the 3 hot topics.In the second example, we can pair the 0-th player with the 1-st player and pair the 2-nd player with the 3-rd player resulting in earnings of 7 + 4 + 5 + 7 = 23 dollars. | 3 1
8 3 5 7 1 10 3 2
| 13 | 2.5 seconds | 512 megabytes | ['flows', 'graph matchings', 'graphs', 'greedy', '*2800'] |
C. Painttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a 1 by n pixel image. The i-th pixel of the image has color a_i. For each color, the number of pixels of that color is at most 20.You can perform the following operation, which works like the bucket tool in paint programs, on this image: pick a color — an integer from 1 to n; choose a pixel in the image; for all pixels connected to the selected pixel, change their colors to the selected color (two pixels of the same color are considered connected if all the pixels between them have the same color as those two pixels). Compute the minimum number of operations needed to make all the pixels in the image have the same color.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^3).The first line of each test case contains a single integer n (1 \le n \le 3\cdot10^3) — the number of pixels in the image.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the colors of the pixels in the image.Note: for each color, the number of pixels of that color is at most 20.It is guaranteed that the sum of n over all test cases does not exceed 3\cdot10^3.OutputFor each test case, print one integer: the minimum number of operations needed to make all the pixels in the image have the same color.ExampleInput
3
5
1 2 3 2 1
4
1 1 2 2
5
1 2 1 4 2
Output
2
1
3
NoteIn the first example, the optimal solution is to apply the operation on the third pixel changing its color to 2 and then to apply the operation on any pixel that has color 2 changing its color and the color of all pixels connected to it to 1. The sequence of operations is then: [1, 2, 3, 2, 1] \to [1, 2, 2, 2, 1] \to [1, 1, 1, 1, 1].In the second example, we can either change the 1s to 2s in one operation or change the 2s to 1s also in one operation.In the third example, one possible way to make all the pixels have the same color is to apply the operation on the first, third and the fourth pixel each time changing its color to 2. | 3
5
1 2 3 2 1
4
1 1 2 2
5
1 2 1 4 2
| 2 1 3 | 1 second | 256 megabytes | ['dp', 'greedy', '*2700'] |
B. Xor of 3time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a of length n consisting of 0s and 1s.You can perform the following operation on this sequence: Pick an index i from 1 to n-2 (inclusive). Change all of a_{i}, a_{i+1}, a_{i+2} to a_{i} \oplus a_{i+1} \oplus a_{i+2} simultaneously, where \oplus denotes the bitwise XOR operation Find a sequence of at most n operations that changes all elements of a to 0s or report that it's impossible.We can prove that if there exists a sequence of operations of any length that changes all elements of a to 0s, then there is also such a sequence of length not greater than n.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4).The first line of each test case contains a single integer n (3 \le n \le 2\cdot10^5) — the length of a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (a_i = 0 or a_i = 1) — elements of a.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot10^5.OutputFor each test case, do the following: if there is no way of making all the elements of a equal to 0 after performing the above operation some number of times, print "NO". otherwise, in the first line print "YES", in the second line print k (0 \le k \le n) — the number of operations that you want to perform on a, and in the third line print a sequence b_1, b_2, \dots, b_k (1 \le b_i \le n - 2) — the indices on which the operation should be applied. If there are multiple solutions, you may print any.ExampleInput
3
3
0 0 0
5
1 1 1 1 0
4
1 0 0 1
Output
YES
0
YES
2
3 1
NO
NoteIn the first example, the sequence contains only 0s so we don't need to change anything.In the second example, we can transform [1, 1, 1, 1, 0] to [1, 1, 0, 0, 0] and then to [0, 0, 0, 0, 0] by performing the operation on the third element of a and then on the first element of a.In the third example, no matter whether we first perform the operation on the first or on the second element of a we will get [1, 1, 1, 1], which cannot be transformed to [0, 0, 0, 0]. | 3
3
0 0 0
5
1 1 1 1 0
4
1 0 0 1
| YES 0 YES 2 3 1 NO | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', 'two pointers', '*2500'] |
A. Booktime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a book with n chapters.Each chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list.Currently you don't understand any of the chapters. You are going to read the book from the beginning till the end repeatedly until you understand the whole book. Note that if you read a chapter at a moment when you don't understand some of the required chapters, you don't understand this chapter.Determine how many times you will read the book to understand every chapter, or determine that you will never understand every chapter no matter how many times you read the book.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 2\cdot10^4).The first line of each test case contains a single integer n (1 \le n \le 2\cdot10^5) — number of chapters.Then n lines follow. The i-th line begins with an integer k_i (0 \le k_i \le n-1) — number of chapters required to understand the i-th chapter. Then k_i integers a_{i,1}, a_{i,2}, \dots, a_{i, k_i} (1 \le a_{i, j} \le n, a_{i, j} \ne i, a_{i, j} \ne a_{i, l} for j \ne l) follow — the chapters required to understand the i-th chapter.It is guaranteed that the sum of n and sum of k_i over all testcases do not exceed 2\cdot10^5.OutputFor each test case, if the entire book can be understood, print how many times you will read it, otherwise print -1.ExampleInput
5
4
1 2
0
2 1 4
1 2
5
1 5
1 1
1 2
1 3
1 4
5
0
0
2 1 2
1 2
2 2 1
4
2 2 3
0
0
2 3 2
5
1 2
1 3
1 4
1 5
0
Output
2
-1
1
2
5
NoteIn the first example, we will understand chapters \{2, 4\} in the first reading and chapters \{1, 3\} in the second reading of the book.In the second example, every chapter requires the understanding of some other chapter, so it is impossible to understand the book.In the third example, every chapter requires only chapters that appear earlier in the book, so we can understand everything in one go.In the fourth example, we will understand chapters \{2, 3, 4\} in the first reading and chapter 1 in the second reading of the book.In the fifth example, we will understand one chapter in every reading from 5 to 1. | 5
4
1 2
0
2 1 4
1 2
5
1 5
1 1
1 2
1 3
1 4
5
0
0
2 1 2
1 2
2 2 1
4
2 2 3
0
0
2 3 2
5
1 2
1 3
1 4
1 5
0
| 2 -1 1 2 5 | 1.5 seconds | 256 megabytes | ['binary search', 'brute force', 'data structures', 'dp', 'graphs', 'implementation', 'sortings', '*1800'] |
J. Two Railroadstime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThere are n cities in Berland, and they are connected by two railroads — the Main railroad and the Auxiliary railroad. Each city has two railway stations, one connected to the Main railroad (called the Main station), and the other connected to the Auxiliary railroad.The railroads are identical in their structure. The Main railroad consists of n-1 railroad segments; the i-th railroad segment connects the Main station of the city i with the Main station of the city i+1. Similarly, the Auxiliary railroad consists of n-1 railroad segments; the i-th railroad segment connects the Auxiliary station of the city i with the Auxiliary station of the city i+1.These railroads are used to transfer different goods and resources from one city to another. In particular, the Ministry of Energetics is interested in using these railroads to transfer coal.The Ministry has estimated the following capabilities of the railroads: for every i \in [1, n-1], at most a_i tons of coal per day can be transferred from the Main station i to the Main station i+1 (only in this direction); for every i \in [1, n-1], at most b_i tons of coal per day can be transferred from the Auxiliary station i to the Auxiliary station i+1 (only in this direction); for every i \in [1, n], at most c_i tons of coal per day can be transferred from the Main station i to the Auxiliary station i, or in the opposite direction. To analyze the capacity of the whole railroad network, the Ministry requires a software that would process and answer queries of the following format: calculate the maximum number of tons of coal that can be transferred per day from the Main station l_i to the Main station r_i. Your task is to implement this software.InputThe first line contains one integer n (2 \le n \le 3 \cdot 10^5) — the number of cities.The second line contains n-1 integers a_1, a_2, \dots, a_{n-1} (1 \le a_i \le 10^9).The third line contains n-1 integers b_1, b_2, \dots, b_{n-1} (1 \le b_i \le 10^9).The fourth line contains n integers c_1, c_2, \dots, c_{n} (1 \le c_i \le 10^9).The fifth line contains one integer q (1 \le q \le 3 \cdot 10^5) — the number of queries.Then q lines follow, the i-th line contains two integers l_i and r_i (1 \le l_i < r_i \le n) — the parameters of the i-th query.OutputPrint q integers, where the i-th integer should be the answer to the i-th query, i. e. the maximum number of tons of coal that can be transferred per day from the Main station l_i to the Main station r_i.ExampleInput
5
3 4 7 4
8 5 3 5
10 5 3 4 10
4
1 4
1 2
3 4
2 4
Output
9 8 10 9
| 5
3 4 7 4
8 5 3 5
10 5 3 4 10
4
1 4
1 2
3 4
2 4
| 9 8 10 9 | 5 seconds | 1024 megabytes | ['*special problem', '*3000'] |
I. Physical Examinationtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plans to undergo a full physical examination at his local clinic. There are n doctors, numbered from 1 to n. The i-th doctor takes patients from minute L_i to minute R_i, so Polycarp can visit him at any minute in this range. It takes each doctor exactly one minute to examine Polycarp's health.Polycarp wants to arrive at the clinic at some minute x and visit all n doctors in some order without waiting or visiting any doctor several times.More formally, he chooses an integer x and a permutation p_1, p_2, \dots, p_n (a sequence of n integers from 1 to n such that each integer appears exactly once), then proceeds to visit: doctor p_1 at minute x; doctor p_2 at minute x+1; ... doctor p_n at minute x+n-1. The p_i-th doctor should be able to take patients at minute x+i-1, so the following should hold: L[p_i] \le x + i - 1 \le R[p_i].Determine if it's possible for Polycarp to choose such a minute x and a permutation p that he'll be able to visit all n doctors in without waiting or visiting any doctor several times. If there are multiple answers, print any of them.InputThe first line contains a single integer t (1 \le t \le 100) — the number of testcases.Then the descriptions of t testcases follow.The first line of the testcase contains a single integer n (1 \le n \le 10^5) — the number of doctors.The second line of the testcase contains n integers L_1, L_2, \dots L_n (1 \le L_i \le 10^9).The third line of the testcase contains n integers R_1, R_2, \dots R_n (L_i \le R_i \le 10^9).The sum of n over all testcases doesn't exceed 10^5.OutputFor each testcase print an answer.If there exists such a minute x and a permutation p that Polycarp is able to visit all n doctors without waiting or visiting any doctor several times, then print x in the first line and a permutation p in the second line. If there are multiple answers, print any of them.Otherwise, print -1 in the only line.ExampleInput
5
3
2 3 1
3 3 2
8
6 6 5 4 9 4 3 6
7 6 10 6 9 6 6 8
2
4 2
4 2
3
2 2 2
3 3 3
1
5
10
Output
1
3 1 2
3
7 4 6 2 1 8 5 3
-1
-1
7
1
NoteIn the third testcase it's impossible to visit all doctors, because Polycarp has to visit doctor 2 at minute 2 and doctor 1 at minute 4. However, that would require him to wait a minute between the visits, which is not allowed.In the fourth testcase all doctors take patients in the span of 2 minutes. However, since there are three of them, Polycarp can't visit them all. | 5
3
2 3 1
3 3 2
8
6 6 5 4 9 4 3 6
7 6 10 6 9 6 6 8
2
4 2
4 2
3
2 2 2
3 3 3
1
5
10
| 1 3 1 2 3 7 4 6 2 1 8 5 3 -1 -1 7 1 | 4 seconds | 256 megabytes | ['*special problem', 'binary search', 'data structures', '*3200'] |
H. Laser Beamstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIra is developing a computer game. This game features randomized generation and difficulty of levels. To achieve randomized difficulty, some enemies in each level are randomly replaced with stronger ones.To describe how do the levels in the game look, let's introduce a coordinate system in such a way that Ox axis goes from left to right, and Oy axis goes from bottom to top. A level is a rectangle with opposite corners in points (0, 0) and (a, b). Each enemy's position is a point in this rectangle.As for now, Ira has implemented one type of enemy in the game, in two different versions — basic and upgraded. Both versions of enemies Ira has implemented fire laser rays in several directions: basic enemies fire four laser rays in four directions: to the right (in the same direction as the vector (1, 0)), to the left (in the same direction as the vector (-1, 0)), up (in the same direction as the vector (0, 1)), and down (in the same direction as the vector (0, -1)); upgraded enemies fire eight laser rays in eight directions: four directions listed for basic enemies, and four directions corresponding to vectors (1, 1), (1, -1), (-1, 1), (-1, -1). Laser rays pass through enemies and are blocked only by the borders of the level (sides of the rectangle that denotes the level). Enemies are unaffected by lasers.The level Ira is working on has n enemies. The i-th enemy is in the point (x_i, y_i), and it has a probability of p_i to be upgraded (it's either upgraded with probability p_i, or basic with probability 1-p_i). All these events are independent.Ira wants to estimate the expected difficulty. She considers that a good way to evaluate the difficulty of the level is to count the number of parts in which the level is divided by the laser rays. So, she wants to calculate the expected number of these parts.Help her to do the evaluation of the level!InputThe first line contains three integers n, a and b (1 \le n \le 100; 2 \le a, b \le 100) — the number of enemies in the level and the dimensions of the level.Then n lines follow, the i-th of them contains three integers x_i, y_i and p'_i (1 \le x_i \le a - 1; 1 \le y_i \le b - 1; 1 \le p'_i \le 999999), meaning that the i-th enemy is located at (x_i, y_i) and has a probability of \frac{p'_i}{10^6} to be upgraded.No two enemies are located in the same point.OutputPrint one integer — the expected number of parts in which the lasers divide the level, taken modulo 998244353 (i. e. let the expected number of parts be \frac{x}{y} as an irreducible fraction; you have to print x \cdot y^{-1} \bmod 998244353, where y^{-1} is a number such that y \cdot y^{-1} \bmod 998244353 = 1).ExamplesInput
1 2 2
1 1 500000
Output
6
Input
2 3 2
1 1 500000
2 1 500000
Output
499122187
NoteExplanation to the first example:With probability \frac{1}{2}, the only enemy is not upgraded and the level looks like this (4 parts): With probability \frac{1}{2}, the only enemy is upgraded and the level looks like this (8 parts): So, the expected number of parts is 4 \cdot \frac{1}{2} + 8 \cdot \frac{1}{2} = 6. | 1 2 2
1 1 500000
| 6 | 2 seconds | 512 megabytes | ['*special problem', 'geometry', 'probabilities', '*2900'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.