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. Weight of the System of Nested Segmentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the number line there are m points, i-th of which has integer coordinate x_i and integer weight w_i. The coordinates of all points are different, and the points are numbered from 1 to m.A sequence of n segments [l_1, r_1], [l_2, r_2], \dots, [l_n, r_n] is called system of nested segments if for each pair i, j (1 \le i < j \le n) the condition l_i < l_j < r_j < r_i is satisfied. In other words, the second segment is strictly inside the first one, the third segment is strictly inside the second one, and so on.For a given number n, find a system of nested segments such that: both ends of each segment are one of m given points; the sum of the weights 2\cdot n of the points used as ends of the segments is minimal. For example, let m = 8. The given points are marked in the picture, their weights are marked in red, their coordinates are marked in blue. Make a system of three nested segments: weight of the first segment: 1 + 1 = 2 weight of the second segment: 10 + (-1) = 9 weight of the third segment: 3 + (-2) = 1 sum of the weights of all the segments in the system: 2 + 9 + 1 = 12 System of three nested segments InputThe first line of input data contains an integer t (1 \le t \le 10^4) —the number of input test cases.An empty line is written before each test case.The first line of each test case contains two positive integers n (1 \le n \le 10^5) and m (2 \cdot n \le m \le 2 \cdot 10^5). The next m lines contain pairs of integers x_i (-10^9 \le x_i \le 10^9) and w_i (-10^4 \le w_i \le 10^4) — coordinate and weight of point number i (1 \le i \le m) respectively. All x_i are different.It is guaranteed that the sum of m values over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output n + 1 lines: in the first of them, output the weight of the composed system, and in the next n lines output exactly two numbers — the indices of the points which are the endpoints of the i-th segment (1 \le i \le n). The order in which you output the endpoints of a segment is not important — you can output the index of the left endpoint first and then the number of the right endpoint, or the other way around.If there are several ways to make a system of nested segments with minimal weight, output any of them.ExampleInput
3
3 8
0 10
-2 1
4 10
11 20
7 -1
9 1
2 3
5 -2
3 6
-1 2
1 3
3 -1
2 4
4 0
8 2
2 5
5 -1
3 -2
1 0
-2 0
-5 -3
Output
12
2 6
5 1
7 8
10
1 6
5 2
3 4
-6
5 1
4 2NoteThe first test case coincides with the example from the condition. It can be shown that the weight of the composed system is minimal.The second test case has only 6 points, so you need to use each of them to compose 3 segments. | 3
3 8
0 10
-2 1
4 10
11 20
7 -1
9 1
2 3
5 -2
3 6
-1 2
1 3
3 -1
2 4
4 0
8 2
2 5
5 -1
3 -2
1 0
-2 0
-5 -3
| 12 2 6 5 1 7 8 10 1 6 5 2 3 4 -6 5 1 4 2 | 2 seconds | 256 megabytes | ['greedy', 'hashing', 'implementation', 'sortings', '*1200'] |
B. DIV + MODtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNot so long ago, Vlad came up with an interesting function: f_a(x)=\left\lfloor\frac{x}{a}\right\rfloor + x \bmod a, where \left\lfloor\frac{x}{a}\right\rfloor is \frac{x}{a}, rounded down, x \bmod a — the remainder of the integer division of x by a.For example, with a=3 and x=11, the value f_3(11) = \left\lfloor\frac{11}{3}\right\rfloor + 11 \bmod 3 = 3 + 2 = 5.The number a is fixed and known to Vlad. Help Vlad find the maximum value of f_a(x) if x can take any integer value from l to r inclusive (l \le x \le r).InputThe first line of input data contains an integer t (1 \le t \le 10^4) — the number of input test cases.This is followed by t lines, each of which contains three integers l_i, r_i and a_i (1 \le l_i \le r_i \le 10^9, 1 \le a_i \le 10^9) — the left and right boundaries of the segment and the fixed value of a.OutputFor each test case, output one number on a separate line — the maximum value of the function on a given segment for a given a.ExampleInput
5
1 4 3
5 8 4
6 10 6
1 1000000000 1000000000
10 12 8
Output
2
4
5
999999999
5
NoteIn the first sample: f_3(1) = \left\lfloor\frac{1}{3}\right\rfloor + 1 \bmod 3 = 0 + 1 = 1, f_3(2) = \left\lfloor\frac{2}{3}\right\rfloor + 2 \bmod 3 = 0 + 2 = 2, f_3(3) = \left\lfloor\frac{3}{3}\right\rfloor + 3 \bmod 3 = 1 + 0 = 1, f_3(4) = \left\lfloor\frac{4}{3}\right\rfloor + 4 \bmod 3 = 1 + 1 = 2 As an answer, obviously, f_3(2) and f_3(4) are suitable. | 5
1 4 3
5 8 4
6 10 6
1 1000000000 1000000000
10 12 8
| 2 4 5 999999999 5 | 2 seconds | 256 megabytes | ['math', '*900'] |
A. Deletions of Two Adjacent Letterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe string s is given, the string length is odd number. The string consists of lowercase letters of the Latin alphabet.As long as the string length is greater than 1, the following operation can be performed on it: select any two adjacent letters in the string s and delete them from the string. For example, from the string "lemma" in one operation, you can get any of the four strings: "mma", "lma", "lea" or "lem" In particular, in one operation, the length of the string reduces by 2.Formally, let the string s have the form s=s_1s_2 \dots s_n (n>1). During one operation, you choose an arbitrary index i (1 \le i < n) and replace s=s_1s_2 \dots s_{i-1}s_{i+2} \dots s_n.For the given string s and the letter c, determine whether it is possible to make such a sequence of operations that in the end the equality s=c will be true? In other words, is there such a sequence of operations that the process will end with a string of length 1, which consists of the letter c?InputThe first line of input data contains an integer t (1 \le t \le 10^3) — the number of input test cases.The descriptions of the t cases follow. Each test case is represented by two lines: string s, which has an odd length from 1 to 49 inclusive and consists of lowercase letters of the Latin alphabet; is a string containing one letter c, where c is a lowercase letter of the Latin alphabet. OutputFor each test case in a separate line output: YES, if the string s can be converted so that s=c is true; NO otherwise. You can output YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive response).ExampleInput
5
abcde
c
abcde
b
x
y
aaaaaaaaaaaaaaa
a
contest
t
Output
YES
NO
NO
YES
YES
NoteIn the first test case, s="abcde". You need to get s="c". For the first operation, delete the first two letters, we get s="cde". In the second operation, we delete the last two letters, so we get the expected value of s="c".In the third test case, s="x", it is required to get s="y". Obviously, this cannot be done. | 5
abcde
c
abcde
b
x
y
aaaaaaaaaaaaaaa
a
contest
t
| YES NO NO YES YES | 2 seconds | 256 megabytes | ['implementation', 'strings', '*800'] |
B. Game of Ball Passingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDaniel is watching a football team playing a game during their training session. They want to improve their passing skills during that session.The game involves n players, making multiple passes towards each other. Unfortunately, since the balls were moving too fast, after the session Daniel is unable to know how many balls were involved during the game. The only thing he knows is the number of passes delivered by each player during all the session.Find the minimum possible amount of balls that were involved in the game.InputThere are several test cases in the input data. The first line contains a single integer t (1 \leq t \leq 5 \cdot 10^4) — the number of test cases. This is followed by the test cases description.The first line of each test case contains one integer n (2 \leq n \leq 10^5) — the number of players.The second line of the test case contains a sequence of integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 10^9), where a_i is the number of passes delivered by the i-th player.It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.OutputFor each test case print a single integer — the answer to the problem.ExampleInput
4
4
2 3 3 2
3
1 5 2
2
0 0
4
1000000000 1000000000 1000000000 1000000000
Output
1
2
0
1
NoteIn the first test case, with the only ball, the game can go like this:2 \rightarrow 1 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 2 \rightarrow 3 \rightarrow 2.In the second test case, there is no possible way to play the game with only one ball. One possible way to play with two balls:2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 1.2 \rightarrow 3 \rightarrow 2 \rightarrow 1In the third example, there were no passes, so 0 balls are possible. | 4
4
2 3 3 2
3
1 5 2
2
0 0
4
1000000000 1000000000 1000000000 1000000000
| 1 2 0 1 | 1 second | 256 megabytes | ['greedy', 'implementation', '*1300'] |
A. Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a very popular computer game. The next level consists of n consecutive locations, numbered from 1 to n, each of them containing either land or water. It is known that the first and last locations contain land, and for completing the level you have to move from the first location to the last. Also, if you become inside a location with water, you will die, so you can only move between locations with land.You can jump between adjacent locations for free, as well as no more than once jump from any location with land i to any location with land i + x, spending x coins (x \geq 0).Your task is to spend the minimum possible number of coins to move from the first location to the last one.Note that this is always possible since both the first and last locations are the land locations.InputThere are several test cases in the input data. The first line contains a single integer t (1 \leq t \leq 100) — the number of test cases. This is followed by the test cases description.The first line of each test case contains one integer n (2 \leq n \leq 100) — the number of locations.The second line of the test case contains a sequence of integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 1), where a_i = 1 means that the i-th location is the location with land, and a_i = 0 means that the i-th location is the location with water. It is guaranteed that a_1 = 1 and a_n = 1.OutputFor each test case print a single integer — the answer to the problem.ExampleInput
3
2
1 1
5
1 0 1 0 1
4
1 0 1 1
Output
0
4
2
NoteIn the first test case, it is enough to make one free jump from the first location to the second one, which is also the last one, so the answer is 0.In the second test case, the only way to move from the first location to the last one is to jump between them, which will cost 4 coins.In the third test case, you can jump from the first location to the third for 2 coins, and then jump to the fourth location for free, so the answer is 2. It can be shown that this is the optimal way. | 3
2
1 1
5
1 0 1 0 1
4
1 0 1 1
| 0 4 2 | 1 second | 256 megabytes | ['implementation', '*800'] |
F. Two Avenuestime limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn order to make the capital of Berland a more attractive place for tourists, the great king came up with the following plan: choose two streets of the city and call them avenues. Certainly, these avenues will be proclaimed extremely important historical places, which should attract tourists from all over the world.The capital of Berland can be represented as a graph, the vertices of which are crossroads, and the edges are streets connecting two crossroads. In total, there are n vertices and m edges in the graph, you can move in both directions along any street, you can get from any crossroad to any other by moving only along the streets, each street connects two different crossroads, and no two streets connect the same pair of crossroads.In order to reduce the flow of ordinary citizens moving along the great avenues, it was decided to introduce a toll on each avenue in both directions. Now you need to pay 1 tugrik for one passage along the avenue. You don't have to pay for the rest of the streets.Analysts have collected a sample of k citizens, i-th of them needs to go to work from the crossroad a_i to the crossroad b_i. After two avenues are chosen, each citizen will go to work along the path with minimal cost.In order to earn as much money as possible, it was decided to choose two streets as two avenues, so that the total number of tugriks paid by these k citizens is maximized. Help the king: according to the given scheme of the city and a sample of citizens, find out which two streets should be made avenues, and how many tugriks the citizens will pay according to this choice.InputEach test consists of multiple test cases. The first line contains one integer t (1 \leq t \leq 10^5) — the number of test cases.The first line of each test case contains two integers n and m (3 \leq n \leq 500\,000, n - 1 \leq m \leq 500\,000, m \le \frac{n (n - 1)}{2}) — the number of crossroads and streets, respectively.The next m lines contain the description of streets, i-th line contains two integers s_i and f_i (1 \leq s_i, f_i \leq n, s_i \neq f_i) — indexes of crossroads which are connected by i-th street. It is guaranteed that no two streets connect the same pair of crossroads, you can get from any crossroad to any other by moving only along the streets.The next line contains a single integer k (1 \leq k \leq 500\,000) — the amount of citizens in the sample.The next k lines contain the description of citizens, i-th line contains two integers a_i and b_i (1 \leq a_i, b_i \leq n, a_i \neq b_i) — i-th citizen goes to work from crossroad a_i to crossroad b_i.Let M be the sum of m over all test cases and K be the sum of k over all test cases. It is guaranteed that M, K \le 500\,000.OutputFor each test case print the answer to the problem.In the first line print the total amount of tugriks that will be paid by citizens.In the second line print two integers x_1 and y_1 — the numbers of crossroads that will be connected by the first avenue.In the third line print two integers x_2 and y_2 — the numbers of crossroads that will be connected by the second avenue.The numbers of crossroads connected by an avenue can be printed in any order, each of the printed streets should be among m streets of the city, chosen streets should be different.ExampleInput
36 51 22 32 44 54 631 65 32 55 51 22 33 44 55 161 51 31 32 42 55 38 101 22 33 44 55 66 77 87 11 83 642 53 72 57 8Output
5
4 2
5 4
5
1 5
3 2
3
7 6
2 3
| 36 51 22 32 44 54 631 65 32 55 51 22 33 44 55 161 51 31 32 42 55 38 101 22 33 44 55 66 77 87 11 83 642 53 72 57 8 | 5 4 2 5 4 5 1 5 3 2 3 7 6 2 3 | 8 seconds | 512 megabytes | ['data structures', 'dfs and similar', 'graphs', '*3500'] |
E. Air Reformtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland is a large country with developed airlines. In total, there are n cities in the country that are historically served by the Berlaflot airline. The airline operates bi-directional flights between m pairs of cities, i-th of them connects cities with numbers a_i and b_i and has a price c_i for a flight in both directions.It is known that Berlaflot flights can be used to get from any city to any other (possibly with transfers), and the cost of any route that consists of several consequent flights is equal to the cost of the most expensive of them. More formally, the cost of the route from a city t_1 to a city t_k with (k-2) transfers using cities t_2,\ t_3,\ t_4,\ \ldots,\ t_{k - 1} is equal to the maximum cost of flights from t_1 to t_2, from t_2 to t_3, from t_3 to t_4 and so on until the flight from t_{k - 1} to t_k. Of course, all these flights must be operated by Berlaflot.A new airline, S8 Airlines, has recently started operating in Berland. This airline provides bi-directional flights between all pairs of cities that are not connected by Berlaflot direct flights. Thus, between each pair of cities there is a flight of either Berlaflot or S8 Airlines.The cost of S8 Airlines flights is calculated as follows: for each pair of cities x and y that is connected by a S8 Airlines flight, the cost of this flight is equal to the minimum cost of the route between the cities x and y at Berlaflot according to the pricing described earlier.It is known that with the help of S8 Airlines flights you can get from any city to any other with possible transfers, and, similarly to Berlaflot, the cost of a route between any two cities that consists of several S8 Airlines flights is equal to the cost of the most expensive flight.Due to the increased competition with S8 Airlines, Berlaflot decided to introduce an air reform and change the costs of its flights. Namely, for the i-th of its flight between the cities a_i and b_i, Berlaflot wants to make the cost of this flight equal to the minimum cost of the route between the cities a_i and b_i at S8 Airlines. Help Berlaflot managers calculate new flight costs.InputEach test consists of multiple test cases. The first line contains one integer t (1 \le t \le 10\,000) — the amount of test cases.The first line of each test case contains two integers n and m (4 \le n \le 200\,000, n - 1 \le m \le 200\,000, m \le \frac{(n - 1) (n - 2)}{2}) — the amount of cities in Berland and the amount of Berlaflot flights.The next m lines contain the description of Berlaflot flights. The i-th line contains three integers a_i, b_i and c_i (1 \le a_i, b_i \le n, 1 \le c_i \le 10^9) — the numbers of cities that are connected with i-th Berlaflot flight and the price of i-th Berlaflot flight.It is guaranteed that no flight connects a city with itself, no two flights connect the same pair of cities. It is guaranteed that by using Berlaflot flights it is possible to get from any city to any other and by using S8 Airlines flights it is possible to get from any city to any other.Let N be the sum of n over all test cases and M be the sum of m over all test cases. It is guaranteed that N, M \le 200\,000.OutputFor each test case you should print m integers in a single line, i-th of them should be the price of i-th Berlaflot flight after the air reform.ExampleInput
34 31 2 12 3 24 3 35 51 2 11 3 12 4 14 5 25 1 36 61 2 32 3 13 6 53 4 24 5 42 4 2Output
3 3 3
1 1 1 2 2
4 4 5 3 4 4
NoteIn the first test case S8 Airlines will provide flights between these pairs of cities: (1, 3), (1, 4) and (2, 4).The cost of a flight between cities 1 and 3 will be equal to 2, since the minimum cost of the Berlaflot route is 2 — the route consists of a flight between cities 1 and 2 costing 1 and a flight between cities 2 and 3 costing 2, the maximum cost is 2.The cost of a flight between cities 1 and 4 will be 3, since the minimum cost of the Berlaflot route is 3 — the route consists of a flight between cities 1 and 2 costing 1, a flight between cities 2 and 3 costing 2 and a flight between cities 3 and 4 costing 3, the maximum cost is 3.The cost of a flight between cities 2 and 4 will be 3, since the minimum cost of the Berlaflot route is 3 — the route consists of a flight between cities 2 and 3 costing 2 and a flight between cities 3 and 4 costing 3, the maximum cost is 3.After the air reform, the cost of the Berlaflot flight between cities 1 and 2 will be 3, since the minimum cost of the S8 Airlines route between these cities is 3 — the route consists of a flight between cities 1 and 4 costing 3 and a flight between cities 2 and 4 costing 3, the maximum cost is 3.The cost of the Berlaflot flight between cities 2 and 3 will be 3, since the minimum cost of the S8 Airlines route between these cities is 3 — the route consists of a flight between cities 2 and 4 costing 3, a flight between cities 1 and 4 costing 3 and a flight between 1 and 3 costing 2, the maximum cost is 3.The cost of the Berlaflot flight between cities 3 and 4 will be 3, since the minimum cost of the S8 Airlines route between these cities is 3 — the route consists of a flight between cities 1 and 3 costing 2 and a flight between cities 1 and 4 costing 3, the maximum cost is 3. In the second test case S8 Airlines will have the following flights: between cities 1 and 4 costing 1, between cities 2 and 3 costing 1, between cities 2 and 5 costing 2, between cities 3 and 4 costing 1 and between cities 3 and 5 costing 2. | 34 31 2 12 3 24 3 35 51 2 11 3 12 4 14 5 25 1 36 61 2 32 3 13 6 53 4 24 5 42 4 2 | 3 3 3 1 1 1 2 2 4 4 5 3 4 4 | 3 seconds | 512 megabytes | ['data structures', 'dfs and similar', 'divide and conquer', 'dsu', 'graphs', 'implementation', 'trees', '*3200'] |
D. Serious Businesstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDima is taking part in a show organized by his friend Peter. In this show Dima is required to cross a 3 \times n rectangular field. Rows are numbered from 1 to 3 and columns are numbered from 1 to n.The cell in the intersection of the i-th row and the j-th column of the field contains an integer a_{i,j}. Initially Dima's score equals zero, and whenever Dima reaches a cell in the row i and the column j, his score changes by a_{i,j}. Note that the score can become negative.Initially all cells in the first and the third row are marked as available, and all cells in the second row are marked as unavailable. However, Peter offered Dima some help: there are q special offers in the show, the i-th special offer allows Dima to mark cells in the second row between l_i and r_i as available, though Dima's score reduces by k_i whenever he accepts a special offer. Dima is allowed to use as many special offers as he wants, and might mark the same cell as available multiple times.Dima starts his journey in the cell (1, 1) and would like to reach the cell (3, n). He can move either down to the next row or right to the next column (meaning he could increase the current row or column by 1), thus making n + 1 moves in total, out of which exactly n - 1 would be horizontal and 2 would be vertical.Peter promised Dima to pay him based on his final score, so the sum of all numbers of all visited cells minus the cost of all special offers used. Please help Dima to maximize his final score.InputThe first input line contains two integers n and q (1 \le n, q \le 500\,000) — the number of columns in the field and the number of special offers.The next three lines describe the field, i-th of them contains n integers a_{i1}, a_{i2}, ..., a_{in} (-10^9 \le a_{ij} \le 10^9) — the values in the i-th row.The next q lines describe special offers: the i-th offer is described by 3 integers l_i, r_i and k_i (1 \leq l_i \leq r_i \leq n, 1\leq k_i\leq 10^9) — the segment that becomes unblocked and the cost of this special offer.OutputOutput one integer — the maximum final score Dima can achieve.ExamplesInput
4 3
1 0 2 -1
-3 1 9 2
3 2 4 1
1 2 5
2 3 4
1 4 14
Output
13Input
5 4
-20 -10 -11 -10 1
1 3 3 6 3
14 -20 3 6 2
1 5 13
1 2 2
3 5 3
2 3 1
Output
-4NoteIn the first example, it is optimal to use Peter's second offer of 4 rubles and go through the cells (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), (3, 4), earning 1 + 0 + 2 + 9 + 4 + 1 - 4 = 13 rubles in total.In the second example, it is optimal to use Peter's second and third offers of 2 and 3 rubles, respectively, and go through the cells (1, 1), (2, 1), (2, 2), (2, 3), (2, 4), (3, 4), (3, 5), earning -20 + 1 + 3 + 3 + 6 + 6 + 2 - 2 - 3= -4 rubles. | 4 3
1 0 2 -1
-3 1 9 2
3 2 4 1
1 2 5
2 3 4
1 4 14
| 13 | 5 seconds | 512 megabytes | ['data structures', 'divide and conquer', 'dp', 'implementation', 'shortest paths', '*2800'] |
C. Tyler and Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile looking at the kitchen fridge, the little boy Tyler noticed magnets with symbols, that can be aligned into a string s.Tyler likes strings, and especially those that are lexicographically smaller than another string, t. After playing with magnets on the fridge, he is wondering, how many distinct strings can be composed out of letters of string s by rearranging them, so that the resulting string is lexicographically smaller than the string t? Tyler is too young, so he can't answer this question. The alphabet Tyler uses is very large, so for your convenience he has already replaced the same letters in s and t to the same integers, keeping that different letters have been replaced to different integers.We call a string x lexicographically smaller than a string y if one of the followings conditions is fulfilled: There exists such position of symbol m that is presented in both strings, so that before m-th symbol the strings are equal, and the m-th symbol of string x is smaller than m-th symbol of string y. String x is the prefix of string y and x \neq y. Because the answer can be too large, print it modulo 998\,244\,353.InputThe first line contains two integers n and m (1 \le n, m \le 200\,000) — the lengths of strings s and t respectively.The second line contains n integers s_1, s_2, s_3, \ldots, s_n (1 \le s_i \le 200\,000) — letters of the string s.The third line contains m integers t_1, t_2, t_3, \ldots, t_m (1 \le t_i \le 200\,000) — letters of the string t.OutputPrint a single number — the number of strings lexicographically smaller than t that can be obtained by rearranging the letters in s, modulo 998\,244\,353.ExamplesInput
3 4
1 2 2
2 1 2 1
Output
2
Input
4 4
1 2 3 4
4 3 2 1
Output
23
Input
4 3
1 1 1 2
1 1 2
Output
1
NoteIn the first example, the strings we are interested in are [1\, 2\, 2] and [2\, 1\, 2]. The string [2\, 2\, 1] is lexicographically larger than the string [2\, 1\, 2\, 1], so we don't count it.In the second example, all strings count except [4\, 3\, 2\, 1], so the answer is 4! - 1 = 23.In the third example, only the string [1\, 1\, 1\, 2] counts. | 3 4
1 2 2
2 1 2 1
| 2 | 2 seconds | 256 megabytes | ['combinatorics', 'data structures', 'implementation', '*1900'] |
B. Integral Arraytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a of n positive integers numbered from 1 to n. Let's call an array integral if for any two, not necessarily different, numbers x and y from this array, x \ge y, the number \left \lfloor \frac{x}{y} \right \rfloor (x divided by y with rounding down) is also in this array.You are guaranteed that all numbers in a do not exceed c. Your task is to check whether this array is integral.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains two integers n and c (1 \le n \le 10^6, 1 \le c \le 10^6) — the size of a and the limit for the numbers in the array.The second line of each test case contains n integers a_1, a_2, ..., a_n (1 \le a_i \le c) — the array a.Let N be the sum of n over all test cases and C be the sum of c over all test cases. It is guaranteed that N \le 10^6 and C \le 10^6.OutputFor each test case print Yes if the array is integral and No otherwise.ExamplesInput
4
3 5
1 2 5
4 10
1 3 3 7
1 2
2
1 1
1
Output
Yes
No
No
Yes
Input
1
1 1000000
1000000
Output
No
NoteIn the first test case it is easy to see that the array is integral: \left \lfloor \frac{1}{1} \right \rfloor = 1, a_1 = 1, this number occurs in the arry \left \lfloor \frac{2}{2} \right \rfloor = 1 \left \lfloor \frac{5}{5} \right \rfloor = 1 \left \lfloor \frac{2}{1} \right \rfloor = 2, a_2 = 2, this number occurs in the array \left \lfloor \frac{5}{1} \right \rfloor = 5, a_3 = 5, this number occurs in the array \left \lfloor \frac{5}{2} \right \rfloor = 2, a_2 = 2, this number occurs in the array Thus, the condition is met and the array is integral.In the second test case it is enough to see that\left \lfloor \frac{7}{3} \right \rfloor = \left \lfloor 2\frac{1}{3} \right \rfloor = 2, this number is not in a, that's why it is not integral.In the third test case \left \lfloor \frac{2}{2} \right \rfloor = 1, but there is only 2 in the array, that's why it is not integral. | 4
3 5
1 2 5
4 10
1 3 3 7
1 2
2
1 1
1
| Yes No No Yes | 2 seconds | 512 megabytes | ['brute force', 'constructive algorithms', 'data structures', 'math', '*1800'] |
A. Weird Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEgor has a table of size n \times m, with lines numbered from 1 to n and columns numbered from 1 to m. Each cell has a color that can be presented as an integer from 1 to 10^5.Let us denote the cell that lies in the intersection of the r-th row and the c-th column as (r, c). We define the manhattan distance between two cells (r_1, c_1) and (r_2, c_2) as the length of a shortest path between them where each consecutive cells in the path must have a common side. The path can go through cells of any color. For example, in the table 3 \times 4 the manhattan distance between (1, 2) and (3, 3) is 3, one of the shortest paths is the following: (1, 2) \to (2, 2) \to (2, 3) \to (3, 3). Egor decided to calculate the sum of manhattan distances between each pair of cells of the same color. Help him to calculate this sum.InputThe first line contains two integers n and m (1 \leq n \le m, n \cdot m \leq 100\,000) — number of rows and columns in the table.Each of next n lines describes a row of the table. The i-th line contains m integers c_{i1}, c_{i2}, \ldots, c_{im} (1 \le c_{ij} \le 100\,000) — colors of cells in the i-th row.OutputPrint one integer — the the sum of manhattan distances between each pair of cells of the same color.ExamplesInput
2 3
1 2 3
3 2 1
Output
7
Input
3 4
1 1 2 2
2 1 1 2
2 2 1 1
Output
76
Input
4 4
1 1 2 3
2 1 1 2
3 1 2 1
1 1 2 1
Output
129
NoteIn the first sample there are three pairs of cells of same color: in cells (1, 1) and (2, 3), in cells (1, 2) and (2, 2), in cells (1, 3) and (2, 1). The manhattan distances between them are 3, 1 and 3, the sum is 7. | 2 3
1 2 3
3 2 1
| 7 | 2 seconds | 256 megabytes | ['combinatorics', 'data structures', 'geometry', 'math', 'matrices', 'sortings', '*1400'] |
F. Madoka and Lazinesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMadoka has become too lazy to write a legend, so let's go straight to the formal description of the problem.An array of integers a_1, a_2, \ldots, a_n is called a hill if it is not empty and there is an index i in it, for which the following is true: a_1 < a_2 < \ldots < a_i > a_{i + 1} > a_{i + 2} > \ldots > a_n.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 keeping the order of the other elements. For example, for an array [69, 1000, 228, -7] the array [1000, -7] is a subsequence, while [1] and [-7, 1000] are not.Splitting an array into two subsequences is called good if each element belongs to exactly one subsequence, and also each of these subsequences is a hill.You are given an array of distinct positive integers a_1, a_2, \ldots a_n. It is required to find the number of different pairs of maxima of the first and second subsequences among all good splits. Two pairs that only differ in the order of elements are considered same.InputThe first line of input contains a single integer n (2 \le n \le 5 \cdot 10^5) — array size.The second line of input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the elements of the array. It is guaranteed that all a_i are pairwise distinct.OutputIn a single line, print exactly one number — the number of different pairs of maxima of the first and second subsequences among all good splits.ExamplesInput
4
1 2 4 3
Output
3
Input
8
2 12 13 7 14 6 11 8
Output
4
Input
7
9 5 3 10 2 6 8
Output
0
Input
8
8 6 10 9 1 5 2 14
Output
0
NoteIn the first test case there are 3 possible pairs: (3, 4), (2, 4), (1, 4). And they are achieved with the following partitions: [1, 2, 3], [4]; [4, 3], [1, 2]; [1], [2, 4, 3] | 4
1 2 4 3
| 3 | 2 seconds | 256 megabytes | ['dp', 'greedy', '*3100'] |
E. Madoka and the Sixth-graderstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter the most stunning success with the fifth-graders, Madoka has been trusted with teaching the sixth-graders.There's n single-place desks in her classroom. At the very beginning Madoka decided that the student number b_i (1 \le b_i \le n) will sit at the desk number i. Also there's an infinite line of students with numbers n + 1, n + 2, n + 3, \ldots waiting at the door with the hope of being able to learn something from the Madoka herself. Pay attention that each student has his unique number.After each lesson, the following happens in sequence. The student sitting at the desk i moves to the desk p_i. All students move simultaneously. If there is more than one student at a desk, the student with the lowest number keeps the place, and the others are removed from the class forever. For all empty desks in ascending order, the student from the lowest number from the outside line occupies the desk. Note that in the end there is exactly one student at each desk again. It is guaranteed that the numbers p are such that at least one student is removed after each lesson. Check out the explanation to the first example for a better understanding.After several (possibly, zero) lessons the desk i is occupied by student a_i. Given the values a_1, a_2, \ldots, a_n and p_1, p_2, \ldots, p_n, find the lexicographically smallest suitable initial seating permutation b_1, b_2, \ldots, b_n.The permutation is an array of n different integers from 1 up to n in any order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not (2 occurs twice). [1,3,4] is not a permutation either (n=3 but there's 4 in the array).For two different permutations a and b of the same length, a is lexicographically less than b if in the first position where a and b differ, the permutation a has a smaller element than the corresponding element in b.InputThe first line of input data contains an integer n (2 \le n \le 10^5) — a number of desks in the classroom.The second line contains n integers p_1, p_2, \ldots, p_n (1 \leq p_i \leq n) — desks where the students move. It is guaranteed that p has at least two equal elements.The third line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the final seating of the students. It is guaranteed that there is an initial permutation from which the seating a can be obtained.OutputIn the only line print n integers b_1, b_2, \ldots, b_n (1 \le b_i \le n) — lexicographically minimum permutation describing the initial seating of the sixth-graders that can lead to the final seating a.ExamplesInput
5
5 5 3 3 1
1 8 2 9 4
Output
1 3 2 5 4
Input
5
1 3 2 5 2
3 2 5 4 1
Output
3 2 5 4 1
Input
10
10 8 5 3 7 8 6 6 1 1
5 26 24 27 21 4 18 2 28 1
Output
5 4 2 6 7 8 3 9 1 10
NoteThe description of the first test is below: The first picture shows the starting permutation, which is the answer. Then the students sitting at desks 1, 2 are transferred to a 5 desk. Also, a 1 student moved from a 5 desk, and a student from a 4 disk is transferred to a 3 desk.Thus, after all these transfers permutation shown in the second image is obtained. Then, at the desk with the number 5, the student with the number 3 is expelled, and at the desk with the number 3, the student with the number 5 is expelled. (Since their numbers are not the smallest) Then new students with numbers 6, 7 sit at desks numbered 2, 4. And this permutation (after the end of the first lesson) is shown in the third image.The 4 image shows the seating arrangement, after the second lesson before all the extra ones were kicked out. And the fifth shows the final seating after 2 lesson. | 5
5 5 3 3 1
1 8 2 9 4
| 1 3 2 5 4 | 2 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'greedy', '*2500'] |
D. Madoka and the Best School in Russiatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMadoka is going to enroll in "TSUNS PTU". But she stumbled upon a difficult task during the entrance computer science exam: A number is called good if it is a multiple of d. A number is called beatiful if it is good and it cannot be represented as a product of two good numbers. Notice that a beautiful number must be good.Given a good number x, determine whether it can be represented in at least two different ways as a product of several (possibly, one) beautiful numbers. Two ways are different if the sets of numbers used are different.Solve this problem for Madoka and help her to enroll in the best school in Russia!InputThe first line contains a single integer t (1 \leq t \leq 100) — number of test cases. Below comes their description.Each test case consists of two integers x and d, separated by a space (2 \leq x, d \leq 10^9). It is guaranteed that x is a multiple of d.OutputFor each set of input data, output "NO" if the number cannot be represented in at least two ways. Otherwise, output "YES".You can output each letter in any case (for example, "YES", "Yes", "yes", "yEs", "yEs" will be recognized as a positive answer).ExampleInput
8
6 2
12 2
36 2
8 2
1000 10
2376 6
128 4
16384 4
Output
NO
NO
YES
NO
YES
YES
NO
YES
NoteIn the first example, 6 can be represented as 6, 1 \cdot 6, 2 \cdot 3. But 3 and 1 are not a good numbers because they are not divisible by 2, so there is only one way.In the second example, 12 can be represented as 6 \cdot 2, 12, 3 \cdot 4, or 3 \cdot 2 \cdot 2. The first option is suitable. The second is— no, because 12 is not beautiful number (12 = 6 \cdot 2). The third and fourth are also not suitable, because 3 is not good number.In the third example, 36 can be represented as 18 \cdot 2 and 6 \cdot 6. Therefore it can be decomposed in at least two ways. | 8
6 2
12 2
36 2
8 2
1000 10
2376 6
128 4
16384 4
| NO NO YES NO YES YES NO YES | 2 seconds | 256 megabytes | ['constructive algorithms', 'dp', 'math', 'number theory', '*1900'] |
C. Madoka and Childish Prankstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMadoka as a child was an extremely capricious girl, and one of her favorite pranks was drawing on her wall. According to Madoka's memories, the wall was a table of n rows and m columns, consisting only of zeroes and ones. The coordinate of the cell in the i-th row and the j-th column (1 \le i \le n, 1 \le j \le m) is (i, j).One day she saw a picture "Mahou Shoujo Madoka Magica" and decided to draw it on her wall. Initially, the Madoka's table is a table of size n \times m filled with zeroes. Then she applies the following operation any number of times:Madoka selects any rectangular subtable of the table and paints it in a chess coloring (the upper left corner of the subtable always has the color 0). Note that some cells may be colored several times. In this case, the final color of the cell is equal to the color obtained during the last repainting. White color means 0, black means 1. So, for example, the table in the first picture is painted in a chess coloring, and the others are not. For better understanding of the statement, we recommend you to read the explanation of the first test.Help Madoka and find some sequence of no more than n \cdot m operations that allows you to obtain the picture she wants, or determine that this is impossible.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10) — the number of test cases. Description of the test cases follows.The first line of each test case contains two integers n and m (1 \leq n, m \leq 100) — the size of the table. Each of the following n lines contains a string of length m consisting only of 1 and 0 — description of the picture that Madoka wants to obtain.OutputIf it is impossible to obtain the given picture, print -1.Otherwise, print in the first line a single integer q (0 \leq q \leq n \cdot m) — the number of operations you need to obtain the picture. Note that you do not need to minimize the number of operations.Then for each operation (in the order of execution) print a single line containing four numbers — the coordinates of the upper-left corner and the lower-right corner of the rectangle.ExampleInput
4
4 5
01000
10100
01010
00110
2 3
001
010
3 3
110
101
000
1 1
0
Output
4
1 1 3 3
3 3 4 4
4 3 4 4
4 2 4 3
1
1 2 2 3
-1
0
NoteThe description of the first test case is below. In the third test case, it is impossible to paint the desired picture.In the fourth test case, the initial table is already the desired picture. | 4
4 5
01000
10100
01010
00110
2 3
001
010
3 3
110
101
000
1 1
0
| 4 1 1 3 3 3 3 4 4 4 3 4 4 4 2 4 3 1 1 2 2 3 -1 0 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*1300'] |
B. Madoka and the Elegant Gifttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMadoka's father just reached 1 million subscribers on Mathub! So the website decided to send him a personalized award — The Mathhub's Bit Button! The Bit Button is a rectangular table with n rows and m columns with 0 or 1 in each cell. After exploring the table Madoka found out that: A subrectangle A is contained in a subrectangle B if there's no cell contained in A but not contained in B. Two subrectangles intersect if there is a cell contained in both of them. A subrectangle is called black if there's no cell with value 0 inside it. A subrectangle is called nice if it's black and it's not contained in another black subrectangle. The table is called elegant if there are no two nice intersecting subrectangles.For example, in the first illustration the red subrectangle is nice, but in the second one it's not, because it's contained in the purple subrectangle. Help Madoka to determine whether the table is elegant.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 200) — the number of test cases. Description of the test cases follows.The first line of each test case contains two positive integers n, m (1 \le n, m \le 100).The next n lines contain strings of length m consisting of zeros and ones — the description of the table.It is guaranteed that the sum of the values of n and the sum of the values of m for all test cases do not exceed 777.OutputFor each test case print "YES" if its table is elegant or print "NO" otherwise.You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).ExampleInput
5
3 3
100
011
011
3 3
110
111
110
1 5
01111
4 5
11111
01010
01000
01000
3 2
11
00
11
Output
YES
NO
YES
NO
YES
NoteIn the second test case the table is not elegant, because the red and the purple subrectangles are nice and intersect. In the fourth test case the table is not elegant, because the red and the purple subrectangles are nice and intersect. | 5
3 3
100
011
011
3 3
110
111
110
1 5
01111
4 5
11111
01010
01000
01000
3 2
11
00
11
| YES NO YES NO YES | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'graphs', 'implementation', '*1200'] |
A. Madoka and Math Dadtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMadoka finally found the administrator password for her computer. Her father is a well-known popularizer of mathematics, so the password is the answer to the following problem.Find the maximum decimal number without zeroes and with no equal digits in a row, such that the sum of its digits is n.Madoka is too tired of math to solve it herself, so help her to solve this problem!InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Description of the test cases follows.The only line of each test case contains an integer n (1 \le n \le 1000) — the required sum of the digits.OutputFor each test case print the maximum number you can obtain.ExampleInput
5
1
2
3
4
5
Output
1
2
21
121
212
NoteThe only numbers with the sum of digits equal to 2 without zeros are 2 and 11. But the last one has two ones in a row, so it's not valid. That's why the answer is 2.The only numbers with the sum of digits equal to 3 without zeros are 111, 12, 21, and 3. The first one has 2 ones in a row, so it's not valid. So the maximum valid number is 21.The only numbers with the sum of digits equals to 4 without zeros are 1111, 211, 121, 112, 13, 31, 22, and 4. Numbers 1111, 211, 112, 22 aren't valid, because they have some identical digits in a row. So the maximum valid number is 121. | 5
1
2
3
4
5
| 1 2 21 121 212 | 1 second | 256 megabytes | ['implementation', 'math', '*800'] |
F. Playing Around the Tabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n players, numbered from 1 to n sitting around a round table. The (i+1)-th player sits to the right of the i-th player for 1 \le i < n, and the 1-st player sits to the right of the n-th player.There are n^2 cards, each of which has an integer between 1 and n written on it. For each integer from 1 to n, there are exactly n cards having this number.Initially, all these cards are distributed among all the players, in such a way that each of them has exactly n cards. In one operation, each player chooses one of his cards and passes it to the player to his right. All these actions are performed simultaneously. Player i is called solid if all his cards have the integer i written on them. Their objective is to reach a configuration in which everyone is solid. Find a way to do it using at most (n^2-n) operations. You do not need to minimize the number of operations.InputThe first line contains a single integer n (2\le n\le 100).Then n lines follow. The i-th of them contains n integers c_1, c_2, \ldots, c_n (1\le c_j\le n) — the initial cards of the i-th player.It is guaranteed that for each integer i from 1 to n, there are exactly n cards having the number i.OutputIn the first line print an integer k (0\le k\le (n^2-n)) — the numbers of operations you want to make.Then k lines should follow. In the i-th of them print n integers d_1, d_2, \ldots, d_n (1\le d_j\le n) where d_j is the number written on the card which j-th player passes to the player to his right in the i-th operation.We can show that an answer always exists under the given constraints. If there are multiple answers, print any.ExamplesInput
2
2 1
1 2
Output
1
2 1
Input
3
1 1 1
2 2 2
3 3 3
Output
6
1 2 3
3 1 2
2 3 1
1 2 3
3 1 2
2 3 1
NoteIn the first test case, if the first player passes a card with number 2 and the second player passes a card with number 1, then the first player has two cards with number 1 and the second player has two cards with number 2. Then, after making this operation, both players are solid.In the second test case, 0 operations would be enough too. Note that you do not need to minimize the number of operations. | 2
2 1
1 2
| 1 2 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', '*2900'] |
E. Power Boardtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a rectangular board of size n\times m (n rows, m columns). The n rows are numbered from 1 to n from top to bottom, and the m columns are numbered from 1 to m from left to right. The cell at the intersection of row i and column j contains the number i^j (i raised to the power of j). For example, if n=3 and m=3 the board is as follows: Find the number of distinct integers written on the board.InputThe only line contains two integers n and m (1\le n,m\le 10^6) — the number of rows and columns of the board.OutputPrint one integer, the number of distinct integers on the board.ExamplesInput
3 3
Output
7
Input
2 4
Output
5
Input
4 2
Output
6
NoteThe statement shows the board for the first test case. In this case there are 7 distinct integers: 1, 2, 3, 4, 8, 9, and 27.In the second test case, the board is as follows: There are 5 distinct numbers: 1, 2, 4, 8 and 16.In the third test case, the board is as follows: There are 6 distinct numbers: 1, 2, 3, 4, 9 and 16. | 3 3
| 7 | 1.5 seconds | 256 megabytes | ['brute force', 'dp', 'math', 'number theory', '*2200'] |
D. Weight the Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree of n vertices numbered from 1 to n. A tree is a connected undirected graph without cycles. For each i=1,2, \ldots, n, let w_i be the weight of the i-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree.InputThe first line contains one integer n (2\le n\le 2\cdot 10^5) — the number of vertices in the tree.Then, n−1 lines follow. Each of them contains two integers u and v (1\le u,v\le n) denoting an edge between vertices u and v. It is guaranteed that the edges form a tree.OutputIn the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum.In the second line print n integers w_1, w_2, \ldots, w_n (1\le w_i\le 10^9) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints.If there are multiple optimal solutions, you may print any.ExamplesInput
4
1 2
2 3
2 4
Output
3 4
1 1 1 1
Input
3
1 2
1 3
Output
2 3
1 1 1
Input
2
1 2
Output
2 2
1 1
Input
9
3 4
7 6
2 1
8 3
5 6
1 8
8 6
9 6
Output
6 11
1 1 1 1 1 1 1 3 1
NoteThis is the tree for the first test case: In this case, if you assign a weight of 1 to each vertex, then the good vertices (which are painted black) are 1, 3 and 4. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is 1+1+1+1=4, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of 1 to each vertex, then the good vertices (which are painted black) are 2 and 3. It can be proven that this is an optimal assignment. | 4
1 2
2 3
2 4
| 3 4 1 1 1 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'dp', 'implementation', 'trees', '*2000'] |
C. Factorials and Powers of Twotime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA number is called powerful if it is a power of two or a factorial. In other words, the number m is powerful if there exists a non-negative integer d such that m=2^d or m=d!, where d!=1\cdot 2\cdot \ldots \cdot d (in particular, 0! = 1). For example 1, 4, and 6 are powerful numbers, because 1=1!, 4=2^2, and 6=3! but 7, 10, or 18 are not.You are given a positive integer n. Find the minimum number k such that n can be represented as the sum of k distinct powerful numbers, or say that there is no such k.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.A test case consists of only one line, containing one integer n (1\le n\le 10^{12}).OutputFor each test case print the answer on a separate line.If n can not be represented as the sum of distinct powerful numbers, print -1.Otherwise, print a single positive integer — the minimum possible value of k.ExampleInput
4
7
11
240
17179869184
Output
2
3
4
1
NoteIn the first test case, 7 can be represented as 7=1+6, where 1 and 6 are powerful numbers. Because 7 is not a powerful number, we know that the minimum possible value of k in this case is k=2.In the second test case, a possible way to represent 11 as the sum of three powerful numbers is 11=1+4+6. We can show that there is no way to represent 11 as the sum of two or less powerful numbers. In the third test case, 240 can be represented as 240=24+32+64+120. Observe that 240=120+120 is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, 17179869184=2^{34}, so 17179869184 is a powerful number and the minimum k in this case is k=1. | 4
7
11
240
17179869184
| 2 3 4 1 | 3 seconds | 256 megabytes | ['bitmasks', 'brute force', 'constructive algorithms', 'dp', 'math', '*1500'] |
B. Quality vs Quantitytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output \def\myred#1{\color{red}{\underline{\bf{#1}}}} \def\myblue#1{\color{blue}{\overline{\bf{#1}}}} \def\RED{\myred{Red}} \def\BLUE{\myblue{Blue}}You are given a sequence of n non-negative integers a_1, a_2, \ldots, a_n. Initially, all the elements of the sequence are unpainted. You can paint each number \RED or \BLUE (but not both), or leave it unpainted. For a color c, \text{Count}(c) is the number of elements in the sequence painted with that color and \text{Sum}(c) is the sum of the elements in the sequence painted with that color.For example, if the given sequence is [2, 8, 6, 3, 1] and it is painted this way: [\myblue{2}, 8, \myred{6}, \myblue{3}, 1] (where 6 is painted red, 2 and 3 are painted blue, 1 and 8 are unpainted) then \text{Sum}(\RED)=6, \text{Sum}(\BLUE)=2+3=5, \text{Count}(\RED)=1, and \text{Count}(\BLUE)=2.Determine if it is possible to paint the sequence so that \text{Sum}(\RED) > \text{Sum}(\BLUE) and \text{Count}(\RED) < \text{Count}(\BLUE).InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). Description of the test cases follows.The first line of each test case contains an integer n (3\le n\le 2\cdot 10^5) — the length of the given sequence. The second line of each test case contains n integers a_1,a_2,\ldots,a_n (0\le a_i\le 10^9) — the given sequence.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, print YES if it is possible to paint the given sequence satisfying the above requirements, and NO otherwise.You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).ExampleInput
4
3
1 2 3
5
2 8 6 3 1
4
3 5 4 2
5
1000000000 1000000000 1000000000 1000000000 1000000000
Output
NO
YES
NO
NO
NoteIn the first test case, there is no possible way to paint the sequence. For example, if you paint the sequence this way: [\myblue{1},\myblue{2},\myred{3}] (where 3 is painted red, 1 and 2 are painted blue) then \text{Count}(\RED)=1 < \text{Count}(\BLUE)=2, but \text{Sum}(\RED)=3 \ngtr \text{Sum}(\BLUE)=3. So, this is not a possible way to paint the sequence.In the second test case, a possible way to paint the sequence is described in the statement. We can see that \text{Sum}(\RED)=6 > \text{Sum}(\BLUE)=5 and \text{Count}(\RED)=1 < \text{Count}(\BLUE)=2.In the third test case, there is no possible way to paint the sequence. For example, if you paint the sequence this way: [\myred{3},\myred{5},\myblue{4}, \myblue{2}] (where 3 and 5 are painted red, 4 and 2 are painted blue) then \text{Sum}(\RED) = 8 > \text{Sum}(\BLUE) = 6 but \text{Count}(\RED) = 2 \nless \text{Count}(\BLUE) = 2. So, this is not a possible way to paint the sequence.In the fourth test case, it can be proven that there is no possible way to paint the sequence satisfying sum and count constraints. | 4
3
1 2 3
5
2 8 6 3 1
4
3 5 4 2
5
1000000000 1000000000 1000000000 1000000000 1000000000
| NO YES NO NO | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', 'sortings', 'two pointers', '*800'] |
A. Square Countingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuis has a sequence of n+1 integers a_1, a_2, \ldots, a_{n+1}. For each i = 1, 2, \ldots, n+1 it is guaranteed that 0\leq a_i < n, or a_i=n^2. He has calculated the sum of all the elements of the sequence, and called this value s. Luis has lost his sequence, but he remembers the values of n and s. Can you find the number of elements in the sequence that are equal to n^2?We can show that the answer is unique under the given constraints.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 2\cdot 10^4). Description of the test cases follows.The only line of each test case contains two integers n and s (1\le n< 10^6, 0\le s \le 10^{18}). It is guaranteed that the value of s is a valid sum for some sequence satisfying the above constraints.OutputFor each test case, print one integer — the number of elements in the sequence which are equal to n^2.ExampleInput
4
7 0
1 1
2 12
3 12
Output
0
1
3
1
NoteIn the first test case, we have s=0 so all numbers are equal to 0 and there isn't any number equal to 49.In the second test case, we have s=1. There are two possible sequences: [0, 1] or [1, 0]. In both cases, the number 1 appears just once. In the third test case, we have s=12, which is the maximum possible value of s for this case. Thus, the number 4 appears 3 times in the sequence. | 4
7 0
1 1
2 12
3 12
| 0 1 3 1 | 1 second | 256 megabytes | ['math', '*800'] |
F. Basistime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputFor an array of integers a, let's define |a| as the number of elements in it.Let's denote two functions: F(a, k) is a function that takes an array of integers a and a positive integer k. The result of this function is the array containing |a| first elements of the array that you get by replacing each element of a with exactly k copies of that element.For example, F([2, 2, 1, 3, 5, 6, 8], 2) is calculated as follows: first, you replace each element of the array with 2 copies of it, so you obtain [2, 2, 2, 2, 1, 1, 3, 3, 5, 5, 6, 6, 8, 8]. Then, you take the first 7 elements of the array you obtained, so the result of the function is [2, 2, 2, 2, 1, 1, 3]. G(a, x, y) is a function that takes an array of integers a and two different integers x and y. The result of this function is the array a with every element equal to x replaced by y, and every element equal to y replaced by x.For example, G([1, 1, 2, 3, 5], 3, 1) = [3, 3, 2, 1, 5].An array a is a parent of the array b if: either there exists a positive integer k such that F(a, k) = b; or there exist two different integers x and y such that G(a, x, y) = b. An array a is an ancestor of the array b if there exists a finite sequence of arrays c_0, c_1, \dots, c_m (m \ge 0) such that c_0 is a, c_m is b, and for every i \in [1, m], c_{i-1} is a parent of c_i.And now, the problem itself.You are given two integers n and k. Your goal is to construct a sequence of arrays s_1, s_2, \dots, s_m in such a way that: every array s_i contains exactly n elements, and all elements are integers from 1 to k; for every array a consisting of exactly n integers from 1 to k, the sequence contains at least one array s_i such that s_i is an ancestor of a. Print the minimum number of arrays in such sequence.InputThe only line contains two integers n and k (1 \le n, k \le 2 \cdot 10^5).OutputPrint one integer — the minimum number of elements in a sequence of arrays meeting the constraints. Since the answer can be large, output it modulo 998244353.ExamplesInput
3 2
Output
2
Input
4 10
Output
12
Input
13 37
Output
27643508
Input
1337 42
Output
211887828
Input
198756 123456
Output
159489391
Input
123456 198756
Output
460526614
NoteLet's analyze the first example.One of the possible answers for the first example is the sequence [[2, 1, 2], [1, 2, 2]]. Every array of size 3 consisting of elements from 1 to 2 has an ancestor in this sequence: for the array [1, 1, 1], the ancestor is [1, 2, 2]: F([1, 2, 2], 13) = [1, 1, 1]; for the array [1, 1, 2], the ancestor is [1, 2, 2]: F([1, 2, 2], 2) = [1, 1, 2]; for the array [1, 2, 1], the ancestor is [2, 1, 2]: G([2, 1, 2], 1, 2) = [1, 2, 1]; for the array [1, 2, 2], the ancestor is [1, 2, 2]; for the array [2, 1, 1], the ancestor is [1, 2, 2]: G([1, 2, 2], 1, 2) = [2, 1, 1]; for the array [2, 1, 2], the ancestor is [2, 1, 2]; for the array [2, 2, 1], the ancestor is [2, 1, 2]: F([2, 1, 2], 2) = [2, 2, 1]; for the array [2, 2, 2], the ancestor is [1, 2, 2]: G(F([1, 2, 2], 4), 1, 2) = G([1, 1, 1], 1, 2) = [2, 2, 2]. | 3 2
| 2 | 6 seconds | 512 megabytes | ['combinatorics', 'fft', 'math', 'number theory', '*2900'] |
E. Expand the Pathtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a grid of size n \times n. The rows are numbered top to bottom from 1 to n, the columns are numbered left to right from 1 to n.The robot is positioned in a cell (1, 1). It can perform two types of moves: D — move one cell down; R — move one cell right. The robot is not allowed to move outside the grid.You are given a sequence of moves s — the initial path of the robot. This path doesn't lead the robot outside the grid.You are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.Count the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains the single integer n (2 \le n \le 10^8) — the number of rows and columns in the grid.The second line of each testcase contains a non-empty string s, consisting only of characters D and R, — the initial path of the robot. This path doesn't lead the robot outside the grid.The total length of strings s over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.ExampleInput
34RD5DRDRDRDR3DOutput
13
9
3
NoteIn the first testcase, it's enough to consider the following modified paths: RD \rightarrow RRD \rightarrow RRRD \rightarrow RRRDD \rightarrow RRRDDD — this path visits cells (1, 1), (1, 2), (1, 3), (1, 4), (2, 4), (3, 4) and (4, 4); RD \rightarrow RRD \rightarrow RRDD \rightarrow RRDDD — this path visits cells (1, 1), (1, 2), (1, 3), (2, 3), (3, 3) and (4, 3); RD \rightarrow RDD \rightarrow RDDD — this path visits cells (1, 1), (1, 2), (2, 2), (3, 2) and (4, 2). Thus, the cells that are visited on at least one modified path are: (1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 2), (3, 3), (3, 4), (4, 2), (4, 3) and (4, 4).In the second testcase, there is no way to modify the sequence without moving the robot outside the grid. So the only visited cells are the ones that are visited on the path DRDRDRDR.In the third testcase, the cells that are visited on at least one modified path are: (1, 1), (2, 1) and (3, 1).Here are the cells for all testcases: | 34RD5DRDRDRDR3D | 13 9 3 | 2 seconds | 256 megabytes | ['brute force', 'combinatorics', 'data structures', 'implementation', 'math', '*1900'] |
D. Cross Coloringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a sheet of paper that can be represented with a grid of size n \times m: n rows and m columns of cells. All cells are colored in white initially.q operations have been applied to the sheet. The i-th of them can be described as follows: x_i y_i — choose one of k non-white colors and color the entire row x_i and the entire column y_i in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all q operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo 998\,244\,353.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of the testcase contains four integers n, m, k and q (1 \le n, m, k, q \le 2 \cdot 10^5) — the size of the sheet, the number of non-white colors and the number of operations.The i-th of the following q lines contains a description of the i-th operation — two integers x_i and y_i (1 \le x_i \le n; 1 \le y_i \le m) — the row and the column the operation is applied to.The sum of q over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the number of different colorings modulo 998\,244\,353.ExampleInput
2
1 1 3 2
1 1
1 1
2 2 2 3
2 1
1 1
2 2
Output
3
4
| 2
1 1 3 2
1 1
1 1
2 2 2 3
2 1
1 1
2 2
| 3 4 | 2 seconds | 256 megabytes | ['data structures', 'implementation', 'math', '*1700'] |
C. Increase Subarray Sumstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots, a_n, consisting of n integers. You are also given an integer value x.Let f(k) be the maximum sum of a contiguous subarray of a after applying the following operation: add x to the elements on exactly k distinct positions. An empty subarray should also be considered, it has sum 0.Note that the subarray doesn't have to include all of the increased elements.Calculate the maximum value of f(k) for all k from 0 to n independently.InputThe first line contains a single integer t (1 \le t \le 5000) — the number of testcases.The first line of the testcase contains two integers n and x (1 \le n \le 5000; 0 \le x \le 10^5) — the number of elements in the array and the value to add.The second line contains n integers a_1, a_2, \dots, a_n (-10^5 \le a_i \le 10^5).The sum of n over all testcases doesn't exceed 5000.OutputFor each testcase, print n + 1 integers — the maximum value of f(k) for all k from 0 to n independently.ExampleInput
3
4 2
4 1 3 2
3 5
-2 -7 -1
10 2
-6 -1 -2 4 -6 -1 -4 4 -5 -4
Output
10 12 14 16 18
0 4 4 5
4 6 6 7 7 7 7 8 8 8 8
NoteIn the first testcase, it doesn't matter which elements you add x to. The subarray with the maximum sum will always be the entire array. If you increase k elements by x, k \cdot x will be added to the sum.In the second testcase: For k = 0, the empty subarray is the best option. For k = 1, it's optimal to increase the element at position 3. The best sum becomes -1 + 5 = 4 for a subarray [3, 3]. For k = 2, it's optimal to increase the element at position 3 and any other element. The best sum is still 4 for a subarray [3, 3]. For k = 3, you have to increase all elements. The best sum becomes (-2 + 5) + (-7 + 5) + (-1 + 5) = 5 for a subarray [1, 3]. | 3
4 2
4 1 3 2
3 5
-2 -7 -1
10 2
-6 -1 -2 4 -6 -1 -4 4 -5 -4
| 10 12 14 16 18 0 4 4 5 4 6 6 7 7 7 7 8 8 8 8 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'greedy', 'implementation', '*1400'] |
B. Anti-Fibonacci Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a permutation p of length n anti-Fibonacci if the condition p_{i-2} + p_{i-1} \ne p_i holds for all i (3 \le i \le n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.Your task is for a given number n print n distinct anti-Fibonacci permutations of length n.InputThe first line contains a single integer t (1 \le t \le 48) — the number of test cases. The single line of each test case contains a single integer n (3 \le n \le 50).OutputFor each test case, print n lines. Each line should contain an anti-Fibonacci permutation of length n. In each test case, you cannot print any permutation more than once.If there are multiple answers, print any of them. It can be shown that it is always possible to find n different anti-Fibonacci permutations of size n under the constraints of the problem.ExampleInput
2
4
3
Output
4 1 3 2
1 2 4 3
3 4 1 2
2 4 1 3
3 2 1
1 3 2
3 1 2
| 2
4
3
| 4 1 3 2 1 2 4 3 3 4 1 2 2 4 1 3 3 2 1 1 3 2 3 1 2 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', '*800'] |
A. Doors and Keystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway.InputThe first line contains a single integer t (1 \le t \le 720) — the number of testcases.Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once.OutputFor each testcase, print YES if the knight can open all doors. Otherwise, print NO.ExampleInput
4
rgbBRG
RgbrBG
bBrRgG
rgRGBb
Output
YES
NO
YES
NO
NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door. | 4
rgbBRG
RgbrBG
bBrRgG
rgRGBb
| YES NO YES NO | 2 seconds | 256 megabytes | ['implementation', '*800'] |
B. Power Walkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSam is a kindergartener, and there are n children in his group. He decided to create a team with some of his children to play "brawl:go 2".Sam has n power-ups, the i-th has type a_i. A child's strength is equal to the number of different types among power-ups he has.For a team of size k, Sam will distribute all n power-ups to k children in such a way that each of the k children receives at least one power-up, and each power-up is given to someone.For each integer k from 1 to n, find the minimum sum of strengths of a team of k children Sam can get.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 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 \le n \le 3 \cdot 10^5). The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — types of Sam's power-ups.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor every test case print n integers.The k-th integer should be equal to the minimum sum of strengths of children in the team of size k that Sam can get.ExampleInput
2
3
1 1 2
6
5 1 2 2 2 4
Output
2 2 3
4 4 4 4 5 6
NoteOne of the ways to give power-ups to minimise the sum of strengths in the first test case: k = 1: \{1, 1, 2\} k = 2: \{1, 1\}, \{2\} k = 3: \{1\}, \{1\}, \{2\} One of the ways to give power-ups to minimise the sum of strengths in the second test case: k = 1: \{1, 2, 2, 2, 4, 5\} k = 2: \{2, 2, 2, 4, 5\}, \{1\} k = 3: \{2, 2, 2, 5\}, \{1\}, \{4\} k = 4: \{2, 2, 2\}, \{1\}, \{4\}, \{5\} k = 5: \{2, 2\}, \{1\}, \{2\}, \{4\}, \{5\} k = 6: \{1\}, \{2\}, \{2\}, \{2\}, \{4\}, \{5\} | 2
3
1 1 2
6
5 1 2 2 2 4
| 2 2 3 4 4 4 4 5 6 | 2 seconds | 256 megabytes | ['greedy', '*900'] |
A. Hard Waytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSam lives in Awesomeburg, its downtown has a triangular shape. Also, the following is true about the triangle: its vertices have integer coordinates, the coordinates of vertices are non-negative, and its vertices are not on a single line. He calls a point on the downtown's border (that is the border of the triangle) safe if he can reach this point from at least one point of the line y = 0 walking along some straight line, without crossing the interior of the triangle. In the picture the downtown is marked with grey color. The first path is invalid because it does not go along a straight line. The second path is invalid because it intersects with the interior of the downtown. The third and fourth paths are correct. Find the total length of the unsafe parts of the downtown border. It can be proven that these parts are segments and their number is finite.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Description of the test cases follows.Each test case contains three lines, each of them contains two integers x_i, y_i (0 \le x_i, y_i \le 10^9) — coordinates of the vertices of the downtown's border.OutputFor each test case print a single number — the answer to the problem.Your answer will be considered correct if its absolute or relative error does not exceed 10^{-9}. Formally let your answer be a, jury answer be b. Your answer will be considered correct if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-9}.ExampleInput
5
8 10
10 4
6 2
4 6
0 1
4 2
14 1
11 2
13 2
0 0
4 0
2 4
0 1
1 1
0 0
Output
0.0000000
0
2.0000
0.00
1
NoteIn the picture, the downtowns of the first three test cases are illustrated. Triangles are enumerated according to the indices of test cases they belong to. In the first two test cases, all points on the borders of the downtowns are safe, thus the answers are 0.In the following picture unsafe points for the third test case are marked with black color: In the fourth test case, all points on the border of the downtown are safe. | 5
8 10
10 4
6 2
4 6
0 1
4 2
14 1
11 2
13 2
0 0
4 0
2 4
0 1
1 1
0 0
| 0.0000000 0 2.0000 0.00 1 | 1 second | 256 megabytes | ['geometry', '*800'] |
F. Covering Circletime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSam started playing with round buckets in the sandbox, while also scattering pebbles. His mom decided to buy him a new bucket, so she needs to solve the following task.You are given n distinct points with integer coordinates A_1, A_2, \ldots, A_n. All points were generated from the square [-10^8, 10^8] \times [-10^8, 10^8] uniformly and independently.You are given positive integers k, l, such that k \leq l \leq n. You want to select a subsegment A_i, A_{i+1}, \ldots, A_{i+l-1} of the points array (for some 1 \leq i \leq n + 1 - l), and some circle on the plane, containing \geq k points of the selected subsegment (inside or on the border).What is the smallest possible radius of that circle?InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. Descriptions of test cases follow.The first line of each test case contains three integers n, l, k (2 \leq k \leq l \leq n \leq 50\,000, k \leq 20).Each of the next n lines contains two integers x_i, y_i (-10^8 \leq x_i, y_i \leq 10^8) — the coordinates of the point A_i. It is guaranteed that all points are distinct and were generated independently from uniform distribution on [-10^8, 10^8] \times [-10^8, 10^8].It is guaranteed that the sum of n for all test cases does not exceed 50\,000.In the first test, points were not generated from the uniform distribution on [-10^8, 10^8] \times [-10^8, 10^8] for simplicity. It is the only such test and your solution must pass it.Hacks are disabled in this problem.OutputFor each test case print a single real number — the answer to the problem.Your answer will be considered correct if its absolute or relative error does not exceed 10^{-9}. Formally let your answer be a, jury answer be b. Your answer will be considered correct if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-9}.ExampleInput
4
3 2 2
0 0
0 4
3 0
5 4 3
1 1
0 0
2 2
0 2
2 0
8 3 2
0 3
1 0
0 2
1 1
0 1
1 2
0 0
1 3
5 4 4
1 1
-3 3
2 2
5 3
5 5
Output
2.00000000000000000000
1.00000000000000000000
0.50000000000000000000
4.00000000000000000000
NoteIn the first test case, we can select subsegment A_1, A_2 and a circle with center (0, 2) and radius 2.In the second test case, we can select subsegment A_1, A_2, A_3, A_4 and a circle with center (1, 2) and radius 1. | 4
3 2 2
0 0
0 4
3 0
5 4 3
1 1
0 0
2 2
0 2
2 0
8 3 2
0 3
1 0
0 2
1 1
0 1
1 2
0 0
1 3
5 4 4
1 1
-3 3
2 2
5 3
5 5
| 2.00000000000000000000 1.00000000000000000000 0.50000000000000000000 4.00000000000000000000 | 6 seconds | 256 megabytes | ['geometry', '*3500'] |
E. Special Positionstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n. Also you are given m distinct positions p_1, p_2, \ldots, p_m (1 \leq p_i \leq n).A non-empty subset of these positions T is randomly selected with equal probability and the following value is calculated: \sum_{i=1}^{n} (a_i \cdot \min_{j \in T} \left|i - j\right|). In other word, for each index of the array, a_i and the distance to the closest chosen position are multiplied, and then these values are summed up.Find the expected value of this sum.This value must be found modulo 998\,244\,353. More formally, let M = 998\,244\,353. It can be shown that the answer can be represented as an irreducible fraction \frac{p}{q}, where p and q are integers and q \neq 0 (mod M). Output the integer equal to p \cdot q^{-1} (mod M). In other words, output such integer x that 0 \leq x < M and x \cdot q = p (mod M).InputThe first line contains two integers n and m (1 \leq m \leq n \leq 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i < 998\,244\,353).The third line contains m distinct integers p_1, p_2, \ldots, p_m (1 \leq p_i \le n).For every 1 \leq i < m it is guaranteed that p_i < p_{i+1}.OutputPrint a single integer — the answer to the problem.ExamplesInput
4 2
1 2 3 4
1 4
Output
665496247
Input
6 6
4 2 4 2 4 2
1 2 3 4 5 6
Output
855638030
NoteIn the first test: If only 1 is choosen, than the value equals to 1 \cdot 0 + 2 \cdot 1 + 3 \cdot 2 + 4 \cdot 3 = 20. If only 4 is choosen, than the value equals to 1 \cdot 3 + 2 \cdot 2 + 3 \cdot 1 + 4 \cdot 0 = 10. If both positions are chosen, than the value equals to 1 \cdot 0 + 2 \cdot 1 + 3 \cdot 1 + 4 \cdot 0 = 5. The answer to the problem is \frac{20 + 10 + 5}{3} = \frac{35}{3} = 665\,496\,247 (modulo 998\,244\,353). | 4 2
1 2 3 4
1 4
| 665496247 | 5 seconds | 512 megabytes | ['combinatorics', 'divide and conquer', 'fft', 'math', '*3300'] |
D. Two Arraystime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSam changed his school and on the first biology lesson he got a very interesting task about genes.You are given n arrays, the i-th of them contains m different integers — a_{i,1}, a_{i,2},\ldots,a_{i,m}. Also you are given an array of integers w of length n.Find the minimum value of w_i + w_j among all pairs of integers (i, j) (1 \le i, j \le n), such that the numbers a_{i,1}, a_{i,2},\ldots,a_{i,m}, a_{j,1}, a_{j,2},\ldots,a_{j,m} are distinct.InputThe first line contains two integers n, m (2 \leq n \leq 10^5, 1 \le m \le 5).The i-th of the next n lines starts with m distinct integers a_{i,1}, a_{i,2}, \ldots, a_{i,m} and then w_i follows (1\leq a_{i,j} \leq 10^9, 1 \leq w_{i} \leq 10^9).OutputPrint a single number — the answer to the problem. If there are no suitable pairs (i, j), print -1.ExamplesInput
4 2
1 2 5
4 3 1
2 3 2
4 5 3
Output
5
Input
4 3
1 2 3 5
2 3 4 2
3 4 5 3
1 3 10 10
Output
-1
NoteIn the first test the minimum value is 5 = w_3 + w_4, because numbers \{2, 3, 4, 5\} are distinct.In the second test case, there are no suitable pair (i, j). | 4 2
1 2 5
4 3 1
2 3 2
4 5 3
| 5 | 3 seconds | 512 megabytes | ['bitmasks', 'brute force', 'combinatorics', 'greedy', 'hashing', 'math', 'two pointers', '*2700'] |
C. Anonymity Is Importanttime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the work of a doctor, it is important to maintain the anonymity of clients and the results of tests. The test results are sent to everyone personally by email, but people are very impatient and they want to know the results right away.That's why in the testing lab "De-vitro" doctors came up with an experimental way to report the results. Let's assume that n people took the tests in the order of the queue. Then the chief doctor Sam can make several statements, in each telling if there is a sick person among the people in the queue from l-th to r-th (inclusive), for some values l and r.During the process, Sam will check how well this scheme works and will be interested in whether it is possible to find out the test result of i-th person from the information he announced. And if it can be done, then is that patient sick or not.Help Sam to test his scheme.InputThe first line contains two integers n, q (1 \le n, q \le 2 \cdot 10^5) — the number of people and the number of queries.In each of the next q lines, the description of the query is given. The first number in the line is t (t = 0 or t = 1) — the type of the query.If t = 0, the line contains three more integers l, r, x (1 \le l \le r \le n, x = 0 or x = 1). This query means that Sam tells that among the people in the queue from l-th to r-th (inclusive): there was at least one sick person, if x=1, there is no sick people, if x=0. If t = 1, the line contains one more integer j (1 \le j \le n) — the position of the patient in the queue, for which Sam wants to know the status.All queries are correct, that means that there always exists an example of the queue of length n for which all reported results (statements from queries with t = 0) are true.OutputAfter each Sam question (query with t = 1) print: "NO", if the patient is definitely not sick, "YES", if the patient is definitely sick. "N/A", if it is impossible to definitely identify the status of patient having the given information. ExampleInput
6 9
0 4 5 0
1 5
1 6
0 4 6 1
1 6
0 2 5 1
0 2 2 0
1 3
1 2
Output
NO
N/A
YES
YES
NO
NoteIn the first test for the five first queries: Initially Sam tells that people 4, 5 are not sick. In the next query Sam asks the status of the patient 5. From the previous query, we know that the patient is definitely not sick. In the next query Sam asks the status of the patient 6. We don't know any information about that patient now. After that Sam tells that there exists a sick patient among 4, 5, 6. In the next query Sam asks the status of the patient 6. Now we can tell that this patient is definitely sick. | 6 9
0 4 5 0
1 5
1 6
0 4 6 1
1 6
0 2 5 1
0 2 2 0
1 3
1 2
| NO N/A YES YES NO | 1.5 seconds | 256 megabytes | ['binary search', 'brute force', 'data structures', 'dsu', 'greedy', 'sortings', '*2200'] |
B. Repetitions Decodingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOlya has an array of integers a_1, a_2, \ldots, a_n. She wants to split it into tandem repeats. Since it's rarely possible, before that she wants to perform the following operation several (possibly, zero) number of times: insert a pair of equal numbers into an arbitrary position. Help her!More formally: A tandem repeat is a sequence x of even length 2k such that for each 1 \le i \le k the condition x_i = x_{i + k} is satisfied. An array a could be split into tandem repeats if you can split it into several parts, each being a subsegment of the array, such that each part is a tandem repeat. In one operation you can choose an arbitrary letter c and insert [c, c] to any position in the array (at the beginning, between any two integers, or at the end). You are to perform several operations and split the array into tandem repeats or determine that it is impossible. Please note that you do not have to minimize the number of operations. InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 30\,000) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 500). The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the initial array. It is guaranteed that the sum of n^2 over all test cases does not exceed 250\,000.OutputFor each test case print answer in the following format.If you cannot turn the array into a concatenation of tandem repeats, print a single integer -1.Otherwise print the number of operations q (0 \le q \le 2 \cdot n^2) that you want to do. Then print the descriptions of operations.In each of the following q lines print two integers p and c (1 \le c \le 10^9), which mean that you insert the integer c twice after p elements of the array. If the length of the array is m before the operation, then the condition 0 \le p \le m should be satisfied.Then you should print any way to split the resulting array into tandem repeats. First, print a single integer d, and then print a sequence t_1, t_2, \ldots, t_d of even integers of size d (d, t_i \ge 1). These numbers are the lengths of the subsegments from left to right.Note that the size of the resulting array a is m = n + 2 \cdot q. The following statements must hold: m = \sum\limits_{i = 1}^{d}{t_i}. For all integer i such that 1 \le i \le d, the sequence a_l, a_{l+1}, \ldots, a_r is a tandem repeat, where l = \sum\limits_{j = 1}^{i - 1}{t_j} + 1, r = l + t_i - 1. It can be shown that if the array can be turned into a concatenation of tandem repeats, then there exists a solution satisfying all constraints. If there are multiple answers, you can print any.ExampleInput
4
2
5 7
2
5 5
6
1 3 1 2 2 3
6
3 2 1 1 2 3
Output
-1
0
1
2
4
1 3
5 3
5 3
10 3
2
8 6
5
0 3
8 3
5 3
6 2
7 1
4
2 6 6 2NoteIn the first test case, you cannot apply operations to the array to make it possible to split it into tandem repeats.In the second test case the array is already a tandem repeat [5, 5] = \underbrace{([5] + [5])}_{t_1 = 2}, thus we can do no operations at all.In the third test case, initially, we have the following array: [1, 3, 1, 2, 2, 3]. After the first insertion with p = 1, c = 3: [1, \textbf{3, 3}, 3, 1, 2, 2, 3]. After the second insertion with p = 5, c = 3: [1, 3, 3, 3, 1, \textbf{3, 3}, 2, 2, 3]. After the third insertion with p = 5, c = 3: [1, 3, 3, 3, 1, \textbf{3, 3}, 3, 3, 2, 2, 3]. After the fourth insertion with p = 10, c = 3: [1, 3, 3, 3, 1, 3, 3, 3, 3, 2, \textbf{3, 3}, 2, 3]. The resulting array can be represented as a concatenation of tandem repeats: \underbrace{([1, 3, 3, 3] + [1, 3, 3, 3])}_{t_1 = 8} + \underbrace{([3, 2, 3] + [3, 2, 3])}_{t_2 = 6}.In the fourth test case, initially, we have the following array: [3, 2, 1, 1, 2, 3]. After the first insertion with p = 0, c = 3: [\textbf{3, 3}, 3, 2, 1, 1, 2, 3]. After the second insertion with p = 8, c = 3: [3, 3, 3, 2, 1, 1, 2, 3, \textbf{3, 3}]. After the third insertion with p = 5, c = 3 [3, 3, 3, 2, 1, \textbf{3, 3}, 1, 2, 3, 3, 3]. After the fourth insertion with p = 6, c = 2: [3, 3, 3, 2, 1, 3, \textbf{2, 2}, 3, 1, 2, 3, 3, 3]. After the fifth insertion with p = 7, c = 1: [3, 3, 3, 2, 1, 3, 2, \textbf{1, 1}, 2, 3, 1, 2, 3, 3, 3]. The resulting array can be represented as a concatenation of tandem repeats: \underbrace{([3] + [3])}_{t_1 = 2} + \underbrace{([3, 2, 1] + [3, 2, 1])}_{t_2 = 6} + \underbrace{([1, 2, 3] + [1, 2, 3])}_{t_3 = 6} + \underbrace{([3] + [3])}_{t_4 = 2}. | 4
2
5 7
2
5 5
6
1 3 1 2 2 3
6
3 2 1 1 2 3
| -1 0 1 2 4 1 3 5 3 5 3 10 3 2 8 6 5 0 3 8 3 5 3 6 2 7 1 4 2 6 6 2 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', 'sortings', '*2000'] |
A. Great Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of positive integers is called great for a positive integer x, if we can split it into pairs in such a way that in each pair the first number multiplied by x is equal to the second number. More formally, a sequence a of size n is great for a positive integer x, if n is even and there exists a permutation p of size n, such that for each i (1 \le i \le \frac{n}{2}) a_{p_{2i-1}} \cdot x = a_{p_{2i}}. Sam has a sequence a and a positive integer x. Help him to make the sequence great: find the minimum possible number of positive integers that should be added to the sequence a to make it great for the number x.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 20\,000) — the number of test cases. Description of the test cases follows.The first line of each test case contains two integers n, x (1 \le n \le 2 \cdot 10^5, 2 \le x \le 10^6).The next line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print a single integer — the minimum number of integers that can be added to the end of a to make it a great sequence for the number x.ExampleInput
4
4 4
1 16 4 4
6 2
1 2 2 2 4 7
5 3
5 2 3 5 15
9 10
10 10 10 20 1 100 200 2000 3
Output
0
2
3
3
NoteIn the first test case, Sam got lucky and the sequence is already great for the number 4 because you can divide it into such pairs: (1, 4), (4, 16). Thus we can add 0 numbers.In the second test case, you can add numbers 1 and 14 to the sequence, then you can divide all 8 integers into such pairs: (1, 2), (1, 2), (2, 4), (7, 14). It is impossible to add less than 2 integers to fix the sequence. | 4
4 4
1 16 4 4
6 2
1 2 2 2 4 7
5 3
5 2 3 5 15
9 10
10 10 10 20 1 100 200 2000 3
| 0 2 3 3 | 1 second | 256 megabytes | ['brute force', 'greedy', 'sortings', '*1200'] |
F. Two Posterstime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou want to advertise your new business, so you are going to place two posters on a billboard in the city center. The billboard consists of n vertical panels of width 1 and varying integer heights, held together by a horizontal bar. The i-th of the n panels has height h_i. Initially, all panels hang down from the bar (their top edges lie on it), but before placing the two posters, you are allowed to move each panel up by any integer length, as long as it is still connected to the bar (its bottom edge lies below or on it).After the moves are done, you will place two posters: one below the bar and one above it. They are not allowed to go over the bar and they must be positioned completely inside of the panels.What is the maximum total area the two posters can cover together if you make the optimal moves? Note that you can also place a poster of 0 area. This case is equivalent to placing a single poster.InputThe first line of input contains one integer n (1 \le n \le 10^4) — the number of vertical panels.The second line of input contains n integers h_1, h_2, ..., h_n (1 \le h_i \le 10^{12}) — the heights of the n vertical panels.OutputPrint a single integer — the maximum total area the two posters can cover together.ExamplesInput
6
2 2 3 5 4 5
Output
18
Input
1
1
Output
1
NoteIn the first sample test, we can choose an upper poster with area 12 and a lower poster of area 6 as in the image below. In the second sample test, we can cover the whole billboard using a single poster. | 6
2 2 3 5 4 5
| 18 | 2 seconds | 1024 megabytes | ['brute force', 'data structures', 'greedy', 'two pointers', '*3200'] |
E. Colorful Operationstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a_1,a_2, \dots, a_n. Each element initially has value 0 and color 1. You are also given q queries to perform: Color l r c: Change the color of elements a_l,a_{l+1},\cdots,a_r to c (1 \le l \le r \le n, 1 \le c \le n). Add c x: Add x to values of all elements a_i (1 \le i \le n) of color c (1 \le c \le n, -10^9 \le x \le 10^9). Query i: Print a_i (1 \le i \le n). InputThe first line of input contains two integers n and q (1 \le n,q \le 10^6) — the length of array a and the number of queries you have to perform.Each of the next q lines contains the query given in the form described in the problem statement.OutputPrint the answers to the queries of the third type on separate lines.ExamplesInput
5 8
Color 2 4 2
Add 2 2
Query 3
Color 4 5 3
Color 2 2 3
Add 3 3
Query 2
Query 5
Output
2
5
3
Input
2 7
Add 1 7
Query 1
Add 2 4
Query 2
Color 1 1 1
Add 1 1
Query 2
Output
7
7
8
NoteThe first sample test is explained below. Blue, red and green represent colors 1, 2 and 3 respectively. | 5 8
Color 2 4 2
Add 2 2
Query 3
Color 4 5 3
Color 2 2 3
Add 3 3
Query 2
Query 5
| 2 5 3 | 4 seconds | 256 megabytes | ['brute force', 'data structures', 'implementation', '*2400'] |
D. Big Brushtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou found a painting on a canvas of size n \times m. The canvas can be represented as a grid with n rows and m columns. Each cell has some color. Cell (i, j) has color c_{i,j}.Near the painting you also found a brush in the shape of a 2 \times 2 square, so the canvas was surely painted in the following way: initially, no cell was painted. Then, the following painting operation has been performed some number of times: Choose two integers i and j (1 \le i < n, 1 \le j < m) and some color k (1 \le k \le nm). Paint cells (i, j), (i + 1, j), (i, j + 1), (i + 1, j + 1) in color k. All cells must be painted at least once. A cell can be painted multiple times. In this case, its final color will be the last one.Find any sequence of at most nm operations that could have led to the painting you found or state that it's impossible.InputThe first line of input contains two integers n and m (2 \le n, m \le 1000) — the dimensions of the canvas.On the i-th of the next n lines of input, there will be m integers. The j-th of them is a_{i,j} (1 \le a_{i,j} \le nm) — the color of cell (i, j).OutputIf there is no solution, print a single integer -1.Otherwise, on the first line, print one integer q (1 \le q \le nm) — the number of operations.Next, print the operations in order. On the k-th of the next q lines, print three integers i, j, c (1 \le i < n, 1 \le j < m, 1 \le c \le nm) — the description of the k-th operation.If there are multiple solutions, print any.ExamplesInput
4 4
5 5 3 3
1 1 5 3
2 2 5 4
2 2 4 4
Output
6
1 3 3
3 3 4
2 2 5
1 1 5
2 1 1
3 1 2
Input
3 4
1 1 1 1
2 2 3 1
2 2 1 1
Output
-1
NoteIn the first test case, the solution is not unique. Here's one of them: In the second test case, there is no way one could obtain the given painting, thus the answer is -1. | 4 4
5 5 3 3
1 1 5 3
2 2 5 4
2 2 4 4
| 6 1 3 3 3 3 4 2 2 5 1 1 5 2 1 1 3 1 2 | 3 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'greedy', 'implementation', '*2000'] |
C. Inversion Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p_1, p_2, \dots, p_n. Then, an undirected graph is constructed in the following way: add an edge between vertices i, j such that i < j if and only if p_i > p_j. Your task is to count the number of connected components in this graph.Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 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 \le n \le 10^5) — the length of the permutation.The second line of each test case contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n) — the elements of the permutation.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print one integer k — the number of connected components.ExampleInput
6
3
1 2 3
5
2 1 4 3 5
6
6 1 4 2 5 3
1
1
6
3 2 1 6 5 4
5
3 1 5 2 4
Output
3
3
1
1
2
1
NoteEach separate test case is depicted in the image below. The colored squares represent the elements of the permutation. For one permutation, each color represents some connected component. The number of distinct colors is the answer. | 6
3
1 2 3
5
2 1 4 3 5
6
6 1 4 2 5 3
1
1
6
3 2 1 6 5 4
5
3 1 5 2 4
| 3 3 1 1 2 1 | 1 second | 256 megabytes | ['data structures', 'dsu', 'graphs', 'math', '*1300'] |
B. Odd Swap Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots, a_n. You can perform operations on the array. In each operation you can choose an integer i (1 \le i < n), and swap elements a_i and a_{i+1} of the array, if a_i + a_{i+1} is odd.Determine whether it can be sorted in non-decreasing order using this operation any number of times.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 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 \le n \le 10^5) — the length of the array.The second line of each test case contains n integers a_1,a_2, \dots, a_n (1 \le a_i \le 10^9) — the elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print "Yes" or "No" depending on whether you can or can not sort the given array.You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).ExampleInput
4
4
1 6 31 14
2
4 2
5
2 9 6 7 10
3
6 6 6
Output
Yes
No
No
Yes
NoteIn the first test case, we can simply swap 31 and 14 (31 + 14 = 45 which is odd) and obtain the non-decreasing array [1,6,14,31].In the second test case, the only way we could sort the array is by swapping 4 and 2, but this is impossible, since their sum 4 + 2 = 6 is even.In the third test case, there is no way to make the array non-decreasing.In the fourth test case, the array is already non-decreasing. | 4
4
1 6 31 14
2
4 2
5
2 9 6 7 10
3
6 6 6
| Yes No No Yes | 1 second | 256 megabytes | ['data structures', 'math', 'sortings', '*1100'] |
A. Reversetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p_1, p_2, \ldots, p_n of length n. You have to choose two integers l,r (1 \le l \le r \le n) and reverse the subsegment [l,r] of the permutation. The permutation will become p_1,p_2, \dots, p_{l-1},p_r,p_{r-1}, \dots, p_l,p_{r+1},p_{r+2}, \dots ,p_n.Find the lexicographically smallest permutation that can be obtained by performing exactly one reverse operation on the initial permutation.Note that for two distinct permutations of equal length a and b, a is lexicographically smaller than b if at the first position they differ, a has the smaller element.A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 500) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 500) — the length of the permutation.The second line of each test case contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n) — the elements of the permutation.OutputFor each test case print the lexicographically smallest permutation you can obtain.ExampleInput
4
1
1
3
2 1 3
4
1 4 2 3
5
1 2 3 4 5
Output
1
1 2 3
1 2 4 3
1 2 3 4 5
NoteIn the first test case, the permutation has length 1, so the only possible segment is [1,1]. The resulting permutation is [1].In the second test case, we can obtain the identity permutation by reversing the segment [1,2]. The resulting permutation is [1,2,3].In the third test case, the best possible segment is [2,3]. The resulting permutation is [1,2,4,3].In the fourth test case, there is no lexicographically smaller permutation, so we can leave it unchanged by choosing the segment [1,1]. The resulting permutation is [1,2,3,4,5]. | 4
1
1
3
2 1 3
4
1 4 2 3
5
1 2 3 4 5
| 1 1 2 3 1 2 4 3 1 2 3 4 5 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*800'] |
H. Minimize Inversions Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p of length n.You can choose any subsequence, remove it from the permutation, and insert it at the beginning of the permutation keeping the same order.For every k from 0 to n, find the minimal possible number of inversions in the permutation after you choose a subsequence of length exactly k.InputThe first line contains a single integer t (1 \le t \le 50\,000) — the number of test cases.The first line of each test case contains one integer n (1 \le n \le 5 \cdot 10^5) — the length of the permutation.The second line of each test case contains the permutation p_1, p_2, \ldots, p_n (1 \le p_i \le n).It is guaranteed that the total sum of n doesn't exceed 5 \cdot 10^5.OutputFor each test case output n + 1 integers. The i-th of them must be the answer for the subsequence length of i - 1.ExampleInput
3
1
1
4
4 2 1 3
5
5 1 3 2 4
Output
0 0
4 2 2 1 4
5 4 2 2 1 5
NoteIn the second test case: For the length 0: [4, 2, 1, 3] \rightarrow [4, 2, 1, 3]: 4 inversions. For the length 1: [4, 2, \mathbf{1}, 3] \rightarrow [1, 4, 2, 3]: 2 inversions. For the length 2: [4, \mathbf{2}, \mathbf{1}, 3] \rightarrow [2, 1, 4, 3], or [4, 2, \mathbf{1}, \textbf{3}] \rightarrow [1, 3, 4, 2]: 2 inversions. For the length 3: [4, \mathbf{2}, \mathbf{1}, \mathbf{3}] \rightarrow [2, 1, 3, 4]: 1 inversion. For the length 4: [\mathbf{4}, \mathbf{2}, \mathbf{1}, \mathbf{3}] \rightarrow [4, 2, 1, 3]: 4 inversions. | 3
1
1
4
4 2 1 3
5
5 1 3 2 4
| 0 0 4 2 2 1 4 5 4 2 2 1 5 | 2 seconds | 256 megabytes | ['data structures', 'greedy', 'math', 'sortings', '*3500'] |
G. Birthdaytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVitaly gave Maxim n numbers 1, 2, \ldots, n for his 16-th birthday. Maxim was tired of playing board games during the celebration, so he decided to play with these numbers. In one step Maxim can choose two numbers x and y from the numbers he has, throw them away, and add two numbers x + y and |x - y| instead. He wants all his numbers to be equal after several steps and the sum of the numbers to be minimal.Help Maxim to find a solution. Maxim's friends don't want to wait long, so the number of steps in the solution should not exceed 20n. It is guaranteed that under the given constraints, if a solution exists, then there exists a solution that makes all numbers equal, minimizes their sum, and spends no more than 20n moves.InputThe first line contains a single integer t (1 \le t \le 25\,000) — the number of test cases.Each test case contains a single integer n (2 \le n \le 5 \cdot 10^4) — the number of integers given to Maxim.It is guaranteed that the total sum of n doesn't exceed 5 \cdot 10^4.OutputFor each test case print -1 if it's impossible to make all numbers equal.Otherwise print a single integer s (0 \le s \le 20n) — the number of steps. Then print s lines. The i-th line must contain two integers x_i and y_i — numbers that Maxim chooses on the i-th step. The numbers must become equal after all operations.Don't forget that you not only need to make all numbers equal, but also minimize their sum. It is guaranteed that under the given constraints, if a solution exists, then there exists a solution that makes all numbers equal, minimizes their sum, and spends no more than 20n moves.ExampleInput
2
2
3
Output
-1
3
1 3
2 2
4 0
| 2
2
3
| -1 3 1 3 2 2 4 0 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*3000'] |
F. Towerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree with n vertices numbered from 1 to n. The height of the i-th vertex is h_i. You can place any number of towers into vertices, for each tower you can choose which vertex to put it in, as well as choose its efficiency. Setting up a tower with efficiency e costs e coins, where e > 0.It is considered that a vertex x gets a signal if for some pair of towers at the vertices u and v (u \neq v, but it is allowed that x = u or x = v) with efficiencies e_u and e_v, respectively, it is satisfied that \min(e_u, e_v) \geq h_x and x lies on the path between u and v.Find the minimum number of coins required to set up towers so that you can get a signal at all vertices.InputThe first line contains an integer n (2 \le n \le 200\,000) — the number of vertices in the tree.The second line contains n integers h_i (1 \le h_i \le 10^9) — the heights of the vertices.Each of the next n - 1 lines contain a pair of numbers v_i, u_i (1 \le v_i, u_i \le n) — an edge of the tree. It is guaranteed that the given edges form a tree.OutputPrint one integer — the minimum required number of coins.ExamplesInput
3
1 2 1
1 2
2 3
Output
4Input
5
1 3 3 1 3
1 3
5 4
4 3
2 3
Output
7Input
2
6 1
1 2
Output
12NoteIn the first test case it's optimal to install two towers with efficiencies 2 at vertices 1 and 3.In the second test case it's optimal to install a tower with efficiency 1 at vertex 1 and two towers with efficiencies 3 at vertices 2 and 5.In the third test case it's optimal to install two towers with efficiencies 6 at vertices 1 and 2. | 3
1 2 1
1 2
2 3
| 4 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'dp', 'greedy', 'trees', '*2500'] |
E. Best Pairtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n. Let cnt_x be the number of elements from the array which are equal to x. Let's also define f(x, y) as (cnt_x + cnt_y) \cdot (x + y).Also you are given m bad pairs (x_i, y_i). Note that if (x, y) is a bad pair, then (y, x) is also bad.Your task is to find the maximum value of f(u, v) over all pairs (u, v), such that u \neq v, that this pair is not bad, and also that u and v each occur in the array a. It is guaranteed that such a pair exists.InputThe first line contains a single integer t (1 \le t \le 10\,000) — the number of test cases.The first line of each test case contains two integers n and m (2 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5) — the length of the array and the number of bad pairs.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — elements of the array.The i-th of the next m lines contains two integers x_i and y_i (1 \le x_i < y_i \le 10^9), which represent a bad pair. It is guaranteed that no bad pair occurs twice in the input. It is also guaranteed that cnt_{x_i} > 0 and cnt_{y_i} > 0.It is guaranteed that for each test case there is a pair of integers (u, v), u \ne v, that is not bad, and such that both of these numbers occur in a.It is guaranteed that the total sum of n and the total sum of m don't exceed 3 \cdot 10^5.OutputFor each test case print a single integer — the answer to the problem.ExampleInput
3
6 1
6 3 6 7 3 3
3 6
2 0
3 4
7 4
1 2 2 3 1 5 1
1 5
3 5
1 3
2 5
Output
40
14
15
NoteIn the first test case 3, 6, 7 occur in the array. f(3, 6) = (cnt_3 + cnt_6) \cdot (3 + 6) = (3 + 2) \cdot (3 + 6) = 45. But (3, 6) is bad so we ignore it. f(3, 7) = (cnt_3 + cnt_7) \cdot (3 + 7) = (3 + 1) \cdot (3 + 7) = 40. f(6, 7) = (cnt_6 + cnt_7) \cdot (6 + 7) = (2 + 1) \cdot (6 + 7) = 39. The answer to the problem is \max(40, 39) = 40. | 3
6 1
6 3 6 7 3 3
3 6
2 0
3 4
7 4
1 2 2 3 1 5 1
1 5
3 5
1 3
2 5
| 40 14 15 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'implementation', '*2100'] |
D. Yet Another Minimization Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b, both of length n.You can perform the following operation any number of times (possibly zero): select an index i (1 \leq i \leq n) and swap a_i and b_i.Let's define the cost of the array a as \sum_{i=1}^{n} \sum_{j=i + 1}^{n} (a_i + a_j)^2. Similarly, the cost of the array b is \sum_{i=1}^{n} \sum_{j=i + 1}^{n} (b_i + b_j)^2.Your task is to minimize the total cost of two arrays.InputEach test case consists of several test cases. The first line contains a single integer t (1 \leq t \leq 40) — the number of test cases. The following is a description of the input data sets.The first line of each test case contains an integer n (1 \leq n \leq 100) — the length of both arrays.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 100) — elements of the first array.The third line of each test case contains n integers b_1, b_2, \ldots, b_n (1 \leq b_i \leq 100) — elements of the second array.It is guaranteed that the sum of n over all test cases does not exceed 100.OutputFor each test case, print the minimum possible total cost.ExampleInput
3
1
3
6
4
3 6 6 6
2 7 4 1
4
6 7 2 4
2 5 3 5
Output
0
987
914
NoteIn the second test case, in one of the optimal answers after all operations a = [2, 6, 4, 6], b = [3, 7, 6, 1].The cost of the array a equals to (2 + 6)^2 + (2 + 4)^2 + (2 + 6)^2 + (6 + 4)^2 + (6 + 6)^2 + (4 + 6)^2 = 508.The cost of the array b equals to (3 + 7)^2 + (3 + 6)^2 + (3 + 1)^2 + (7 + 6)^2 + (7 + 1)^2 + (6 + 1)^2 = 479.The total cost of two arrays equals to 508 + 479 = 987. | 3
1
3
6
4
3 6 6 6
2 7 4 1
4
6 7 2 4
2 5 3 5
| 0 987 914 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'math', '*1800'] |
C. Andrew and Stonestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrew has n piles with stones. The i-th pile contains a_i stones. He wants to make his table clean so he decided to put every stone either to the 1-st or the n-th pile.Andrew can perform the following operation any number of times: choose 3 indices 1 \le i < j < k \le n, such that the j-th pile contains at least 2 stones, then he takes 2 stones from the pile j and puts one stone into pile i and one stone into pile k. Tell Andrew what is the minimum number of operations needed to move all the stones to piles 1 and n, or determine if it's impossible.InputThe input contains several test cases. The first line contains one integer t (1 \leq t \leq 10\,000) — the number of test cases.The first line for each test case contains one integer n (3 \leq n \leq 10^5) — the length of the array.The second line contains a sequence of integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the array elements.It is guaranteed that the sum of the values n over all test cases does not exceed 10^5.OutputFor each test case print the minimum number of operations needed to move stones to piles 1 and n, or print -1 if it's impossible.ExampleInput
4
5
1 2 2 3 6
3
1 3 1
3
1 2 1
4
3 1 1 2
Output
4
-1
1
-1
NoteIn the first test case, it is optimal to do the following: Select (i, j, k) = (1, 2, 5). The array becomes equal to [2, 0, 2, 3, 7]. Select (i, j, k) = (1, 3, 4). The array becomes equal to [3, 0, 0, 4, 7]. Twice select (i, j, k) = (1, 4, 5). The array becomes equal to [5, 0, 0, 0, 9]. This array satisfy the statement, because every stone is moved to piles 1 and 5. There are 4 operations in total.In the second test case, it's impossible to put all stones into piles with numbers 1 and 3: At the beginning there's only one possible operation with (i, j, k) = (1, 2, 3). The array becomes equal to [2, 1, 2]. Now there is no possible operation and the array doesn't satisfy the statement, so the answer is -1. In the third test case, it's optimal to do the following: Select (i, j, k) = (1, 2, 3). The array becomes equal to [2, 0, 2]. This array satisfies the statement, because every stone is moved to piles 1 and 3. The is 1 operation in total.In the fourth test case, it's impossible to do any operation, and the array doesn't satisfy the statement, so the answer is -1. | 4
5
1 2 2 3 6
3
1 3 1
3
1 2 1
4
3 1 1 2
| 4 -1 1 -1 | 1 second | 256 megabytes | ['greedy', 'implementation', '*1200'] |
B. MEX and Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet there be an array b_1, b_2, \ldots, b_k. Let there be a partition of this array into segments [l_1; r_1], [l_2; r_2], \ldots, [l_c; r_c], where l_1 = 1, r_c = k, and for any 2 \leq i \leq c holds that r_{i-1} + 1 = l_i. In other words, each element of the array belongs to exactly one segment.Let's define the cost of a partition as c + \sum_{i = 1}^{c} \operatorname{mex}(\{b_{l_i}, b_{l_i + 1}, \ldots, b_{r_i}\}), where \operatorname{mex} of a set of numbers S is the smallest non-negative integer that does not occur in the set S. In other words, the cost of a partition is the number of segments plus the sum of MEX over all segments. Let's define the value of an array b_1, b_2, \ldots, b_k as the maximum possible cost over all partitions of this array.You are given an array a of size n. Find the sum of values of all its subsegments.An array x is a subsegment of an array y if x can be obtained from y by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputThe input contains several test cases. The first line contains one integer t (1 \leq t \leq 30) — the number of test cases.The first line for each test case contains one integer n (1 \leq n \leq 100) — the length of the array.The second line contains a sequence of integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 10^9) — the array elements.It is guaranteed that the sum of the values n over all test cases does not exceed 100.OutputFor each test case print a single integer — the answer to the problem.ExampleInput
4
2
1 2
3
2 0 1
4
2 0 5 1
5
0 1 1 0 1
Output
4
14
26
48
NoteIn the second test case: The best partition for the subsegment [2, 0, 1]: [2], [0, 1]. The cost of this partition equals to 2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0, 1\}) = 2 + 0 + 2 = 4. The best partition for the subsegment [2, 0]: [2], [0]. The cost of this partition equals to 2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0\}) = 2 + 0 + 1 = 3 The best partition for the subsegment [2]: [2]. The cost of this partition equals to 1 + \operatorname{mex}(\{2\}) = 1 + 0 = 1. The best partition for the subsegment [0, 1]: [0, 1]. The cost of this partition equals to 1 + \operatorname{mex}(\{0, 1\}) = 1 + 2 = 3. The best partition for the subsegment [0]: [0]. The cost of this partition equals to 1 + \operatorname{mex}(\{0\}) = 1 + 1 = 2. The best partition for the subsegment [1]: [1]. The cost of this partition equals to 1 + \operatorname{mex}(\{1\}) = 1 + 0 = 1. The sum of values over all subsegments equals to 4 + 3 + 1 + 3 + 2 + 1 = 14. | 4
2
1 2
3
2 0 1
4
2 0 5 1
5
0 1 1 0 1
| 4 14 26 48 | 1 second | 256 megabytes | ['brute force', 'dp', 'greedy', 'math', '*1100'] |
A. Sorting Partstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a of length n. You can exactly once select an integer len between 1 and n - 1 inclusively, and then sort in non-decreasing order the prefix of the array of length len and the suffix of the array of length n - len independently.For example, if the array is a = [3, 1, 4, 5, 2], and you choose len = 2, then after that the array will be equal to [1, 3, 2, 4, 5].Could it be that after performing this operation, the array will not be sorted in non-decreasing order?InputThere are several test cases in the input data. The first line contains a single integer t (1 \leq t \leq 100) — the number of test cases. This is followed by the test cases description.The first line of each test case contains one integer n (2 \leq n \leq 10^4) — the length of the array.The second line of the test case contains a sequence of integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the array elements.It is guaranteed that the sum of n over all test cases does not exceed 10^4.OutputFor each test case of input data, output "YES" (without quotes), if the array may be not sorted in non-decreasing order, output "NO" (without quotes) otherwise. You can output each letter in any case (uppercase or lowercase).ExampleInput
3
3
2 2 1
4
3 1 2 1
5
1 2 2 4 4
Output
YES
YES
NO
NoteIn the first test case, it's possible to select len = 1, then after operation, the array will not be sorted in non-decreasing order and will be equal to [2, 1, 2].In the second test case, it's possible to select len = 3, then after operation, the array will not be sorted in non-decreasing order and will be equal to [1, 2, 3, 1].In the third test case, the array will be sorted in non-decreasing order for every possible len. | 3
3
2 2 1
4
3 1 2 1
5
1 2 2 4 4
| YES YES NO | 1 second | 256 megabytes | ['brute force', 'sortings', '*800'] |
F. Closest Pair time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n weighted points on the OX-axis. The coordinate and the weight of the i-th point is x_i and w_i, respectively. All points have distinct coordinates and positive weights. Also, x_i < x_{i + 1} holds for any 1 \leq i < n. The weighted distance between i-th point and j-th point is defined as |x_i - x_j| \cdot (w_i + w_j), where |val| denotes the absolute value of val.You should answer q queries, where the i-th query asks the following: Find the minimum weighted distance among all pairs of distinct points among the points in subarray [l_i,r_i].InputThe first line contains 2 integers n and q (2 \leq n \leq 3 \cdot 10^5; 1 \leq q \leq 3 \cdot 10^5) — the number of points and the number of queries.Then, n lines follows, the i-th of them contains two integers x_i and w_i (-10^9 \leq x_i \leq 10^9; 1 \leq w_i \leq 10^9) — the coordinate and the weight of the i-th point.It is guaranteed that the points are given in the increasing order of x.Then, q lines follows, the i-th of them contains two integers l_i and r_i (1 \leq l_i < r_i \leq n) — the given subarray of the i-th query.OutputFor each query output one integer, the minimum weighted distance among all pair of distinct points in the given subarray.ExampleInput
5 5
-2 2
0 10
1 1
9 2
12 7
1 3
2 3
1 5
3 5
2 4
Output
9
11
9
24
11
NoteFor the first query, the minimum weighted distance is between points 1 and 3, which is equal to |x_1 - x_3| \cdot (w_1 + w_3) = |-2 - 1| \cdot (2 + 1) = 9.For the second query, the minimum weighted distance is between points 2 and 3, which is equal to |x_2 - x_3| \cdot (w_2 + w_3) = |0 - 1| \cdot (10 + 1) = 11.For the fourth query, the minimum weighted distance is between points 3 and 4, which is equal to |x_3 - x_4| \cdot (w_3 + w_4) = |1 - 9| \cdot (1 + 2) = 24. | 5 5
-2 2
0 10
1 1
9 2
12 7
1 3
2 3
1 5
3 5
2 4
| 9 11 9 24 11 | 3 seconds | 256 megabytes | ['data structures', 'greedy', '*2800'] |
E. Cars time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n cars on a coordinate axis OX. Each car is located at an integer point initially and no two cars are located at the same point. Also, each car is oriented either left or right, and they can move at any constant positive speed in that direction at any moment.More formally, we can describe the i-th car with a letter and an integer: its orientation ori_i and its location x_i. If ori_i = L, then x_i is decreasing at a constant rate with respect to time. Similarly, if ori_i = R, then x_i is increasing at a constant rate with respect to time. We call two cars irrelevant if they never end up in the same point regardless of their speed. In other words, they won't share the same coordinate at any moment.We call two cars destined if they always end up in the same point regardless of their speed. In other words, they must share the same coordinate at some moment.Unfortunately, we lost all information about our cars, but we do remember m relationships. There are two types of relationships:1 i j —i-th car and j-th car are irrelevant.2 i j —i-th car and j-th car are destined.Restore the orientations and the locations of the cars satisfying the relationships, or report that it is impossible. If there are multiple solutions, you can output any.Note that if two cars share the same coordinate, they will intersect, but at the same moment they will continue their movement in their directions.InputThe first line contains two integers, n and m (2 \leq n \leq 2 \cdot 10^5; 1 \leq m \leq min(2 \cdot 10^5, \frac{n(n-1)}{2}) — the number of cars and the number of restrictions respectively.Each of the next m lines contains three integers, type, i, and j (1 \leq type \leq 2; 1 \leq i,j \leq n; i≠j).If type = 1, i-th car and j-th car are irrelevant. Otherwise, i-th car and j-th car are destined.It is guaranteed that for each pair of cars, there are at most 1 relationship between.OutputIn the first line, print either "YES" or "NO" (in any case), whether it is possible to restore the orientations and the locations of the cars satisfying the relationships.If the answer is "YES", print n lines each containing a symbol and an integer: ori_i and x_i (ori_i \in \{L, R\}; -10^9 \leq x_i \leq 10^9) — representing the information of the i-th car.If the orientation is left, then ori_i = L. Otherwise ori_i = R.x_i is the where the i-th car is located. Note that all x_i should be distinct. We can prove that if there exists a solution, then there must be a solution satisfying the constraints on x_i.ExamplesInput
4 4
1 1 2
1 2 3
2 3 4
2 4 1
Output
YES
R 0
L -3
R 5
L 6
Input
3 3
1 1 2
1 2 3
1 1 3
Output
NO
| 4 4
1 1 2
1 2 3
2 3 4
2 4 1
| YES R 0 L -3 R 5 L 6 | 2 seconds | 512 megabytes | ['2-sat', 'constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'sortings', '*2200'] |
D. Infinite Settime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n distinct positive integers.Let's consider an infinite integer set S which contains all integers x that satisfy at least one of the following conditions: x = a_i for some 1 \leq i \leq n. x = 2y + 1 and y is in S. x = 4y and y is in S.For example, if a = [1,2] then the 10 smallest elements in S will be \{1,2,3,4,5,7,8,9,11,12\}.Find the number of elements in S that are strictly smaller than 2^p. Since this number may be too large, print it modulo 10^9 + 7.InputThe first line contains two integers n and p (1 \leq n, p \leq 2 \cdot 10^5).The second line contains n integers a_1,a_2,\ldots,a_n (1 \leq a_i \leq 10^9).It is guaranteed that all the numbers in a are distinct.OutputPrint a single integer, the number of elements in S that are strictly smaller than 2^p. Remember to print it modulo 10^9 + 7. ExamplesInput
2 4
6 1
Output
9
Input
4 7
20 39 5 200
Output
14
Input
2 200000
48763 1000000000
Output
448201910
NoteIn the first example, the elements smaller than 2^4 are \{1, 3, 4, 6, 7, 9, 12, 13, 15\}.In the second example, the elements smaller than 2^7 are \{5,11,20,23,39,41,44,47,79,80,83,89,92,95\}. | 2 4
6 1
| 9 | 2 seconds | 256 megabytes | ['bitmasks', 'dp', 'math', 'matrices', 'number theory', 'strings', '*1800'] |
C. Differential Sortingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n elements. Your can perform the following operation no more than n times: Select three indices x,y,z (1 \leq x < y < z \leq n) and replace a_x with a_y - a_z. After the operation, |a_x| need to be less than 10^{18}.Your goal is to make the resulting array non-decreasing. If there are multiple solutions, you can output any. If it is impossible to achieve, you should report it as well.InputEach test contains multiple test cases. The first line will contain a single integer t (1 \leq t \leq 10000) — the number of test cases. Then t test cases follow.The first line of each test case contains a single integer n (3 \leq n \leq 2 \cdot 10^5) — the size of the array a.The second line of each test case contains n integers a_1, a_2, \ldots ,a_n (-10^9 \leq a_i \leq 10^9), the elements of 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 -1 in a single line if there is no solution. Otherwise in the first line you should print a single integer m (0 \leq m \leq n) — number of operations you performed.Then the i-th of the following m lines should contain three integers x,y,z (1 \leq x < y < z \leq n)— description of the i-th operation.If there are multiple solutions, you can output any. Note that you don't have to minimize the number of operations in this task.ExampleInput
3
5
5 -4 2 -1 2
3
4 3 2
3
-3 -2 -1
Output
2
1 2 3
3 4 5
-1
0
NoteIn the first example, the array becomes [-6,-4,2,-1,2] after the first operation,[-6,-4,-3,-1,2] after the second operation.In the second example, it is impossible to make the array sorted after any sequence of operations.In the third example, the array is already sorted, so we don't need to perform any operations. | 3
5
5 -4 2 -1 2
3
4 3 2
3
-3 -2 -1
| 2 1 2 3 3 4 5 -1 0 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', '*1200'] |
B. Avoid Local Maximumstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of size n. Each element in this array is an integer between 1 and 10^9.You can perform several operations to this array. During an operation, you can replace an element in the array with any integer between 1 and 10^9. Output the minimum number of operations needed such that the resulting array doesn't contain any local maximums, and the resulting array after the operations.An element a_i is a local maximum if it is strictly larger than both of its neighbors (that is, a_i > a_{i - 1} and a_i > a_{i + 1}). Since a_1 and a_n have only one neighbor each, they will never be a local maximum.InputEach test contains multiple test cases. The first line will contain a single integer t (1 \leq t \leq 10000) — the number of test cases. Then t test cases follow.The first line of each test case contains a single integer n (2 \leq n \leq 2 \cdot 10^5) — the size of the array a.The second line of each test case contains n integers a_1, a_2, \ldots ,a_n (1 \leq a_i \leq 10^9), the elements of array.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, first output a line containing a single integer m — minimum number of operations required. Then ouput a line consist of n integers — the resulting array after the operations. Note that this array should differ in exactly m elements from the initial array.If there are multiple answers, print any.ExampleInput
5
3
2 1 2
4
1 2 3 1
5
1 2 1 2 1
9
1 2 1 3 2 3 1 2 1
9
2 1 3 1 3 1 3 1 3
Output
0
2 1 2
1
1 3 3 1
1
1 2 2 2 1
2
1 2 3 3 2 3 3 2 1
2
2 1 3 3 3 1 1 1 3
NoteIn the first example, the array contains no local maximum, so we don't need to perform operations.In the second example, we can change a_2 to 3, then the array don't have local maximums. | 5
3
2 1 2
4
1 2 3 1
5
1 2 1 2 1
9
1 2 1 3 2 3 1 2 1
9
2 1 3 1 3 1 3 1 3
| 0 2 1 2 1 1 3 3 1 1 1 2 2 2 1 2 1 2 3 3 2 3 3 2 1 2 2 1 3 3 3 1 1 1 3 | 2 seconds | 256 megabytes | ['greedy', '*800'] |
A. Min Or Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of size n.You can perform the following operation on the array: Choose two different integers i, j (1 \leq i < j \leq n), replace a_i with x and a_j with y. In order not to break the array, a_i | a_j = x | y must be held, where | denotes the bitwise OR operation. Notice that x and y are non-negative integers. Please output the minimum sum of the array you can get after using the operation above any number of times.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 1000). Description of the test cases follows.The first line of each test case contains an integer n (2 \leq n \leq 100) — the size of array a.The second line of each test case contains n integers a_1, a_2, \ldots ,a_n (0 \leq a_i < 2^{30}).OutputFor each test case, print one number in a line — the minimum possible sum of the array.ExampleInput
4
3
1 3 2
5
1 2 4 8 16
2
6 6
3
3 5 6
Output
3
31
6
7
NoteIn the first example, you can perform the following operations to obtain the array [1, 0, 2]:1. choose i = 1, j = 2, change a_1 = 1 and a_2 = 2, it's valid since 1 | 3 = 1 | 2. The array becomes [1, 2, 2].2. choose i = 2, j = 3, change a_2 = 0 and a_3 = 2, it's valid since 2 | 2 = 0 | 2. The array becomes [1, 0, 2].We can prove that the minimum sum is 1 + 0 + 2 = 3In the second example, We don't need any operations. | 4
3
1 3 2
5
1 2 4 8 16
2
6 6
3
3 5 6
| 3 31 6 7 | 1 second | 256 megabytes | ['bitmasks', 'greedy', '*800'] |
F. Fibonacci Additionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne of my most productive days was throwing away 1,000 lines of code.— Ken ThompsonFibonacci addition is an operation on an array X of integers, parametrized by indices l and r. Fibonacci addition increases X_l by F_1, increases X_{l + 1} by F_2, and so on up to X_r which is increased by F_{r - l + 1}.F_i denotes the i-th Fibonacci number (F_1 = 1, F_2 = 1, F_{i} = F_{i - 1} + F_{i - 2} for i > 2), and all operations are performed modulo MOD.You are given two arrays A and B of the same length. We will ask you to perform several Fibonacci additions on these arrays with different parameters, and after each operation you have to report whether arrays A and B are equal modulo MOD.InputThe first line contains 3 numbers n, q and MOD (1 \le n, q \le 3\cdot 10^5, 1 \le MOD \le 10^9+7) — the length of the arrays, the number of operations, and the number modulo which all operations are performed.The second line contains n numbers — array A (0 \le A_i < MOD).The third line also contains n numbers — array B (0 \le B_i < MOD).The next q lines contain character c and two numbers l and r (1 \le l \le r \le n) — operation parameters. If c is "A", Fibonacci addition is to be performed on array A, and if it is is "B", the operation is to be performed on B.OutputAfter each operation, print "YES" (without quotes) if the arrays are equal and "NO" otherwise. Letter case does not matter.ExamplesInput
3 5 3
2 2 1
0 0 0
A 1 3
A 1 3
B 1 1
B 2 2
A 3 3
Output
YES
NO
NO
NO
YES
Input
5 3 10
2 5 0 3 5
3 5 8 2 5
B 2 3
B 3 4
A 1 2
Output
NO
NO
YES
NoteExplanation of the test from the condition: Initially A=[2,2,1], B=[0,0,0]. After operation "A 1 3": A=[0,0,0], B=[0,0,0] (addition is modulo 3). After operation "A 1 3": A=[1,1,2], B=[0,0,0]. After operation "B 1 1": A=[1,1,2], B=[1,0,0]. After operation "B 2 2": A=[1,1,2], B=[1,1,0]. After operation "A 3 3": A=[1,1,0], B=[1,1,0]. | 3 5 3
2 2 1
0 0 0
A 1 3
A 1 3
B 1 1
B 2 2
A 3 3
| YES NO NO NO YES | 1 second | 256 megabytes | ['brute force', 'data structures', 'hashing', 'implementation', 'math', '*2700'] |
E. Fair Sharetime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEven a cat has things it can do that AI cannot.— Fei-Fei LiYou are given m arrays of positive integers. Each array is of even length.You need to split all these integers into two equal multisets L and R, that is, each element of each array should go into one of two multisets (but not both). Additionally, for each of the m arrays, exactly half of its elements should go into L, and the rest should go into R.Give an example of such a division or determine that no such division exists.InputThe first line contains an integer m (1 \le m \le 10 ^ 5) — the number of arrays.The next 2 \cdot m lines contain descriptions of the arrays.For each array, the first line contains an even integer n (2 \le n \le 2 \cdot 10 ^ 5) — the length of the array. The second line consists of n space-separated integers a_1, a_2, \dots, a_n (1 \le a_i \le 10 ^ 9) — array elements.It is guaranteed that the sum of n over all arrays does not exceed 2 \cdot 10^5.OutputIf the answer exists, print "YES", and then print m lines.On each line, for each element, print the letter "L" or "R" (capitalized, without spaces), depending on which multiset the element should go into.If there is no answer, print "NO" on the only line.ExampleInput
3
2
1 2
4
1 2 3 3
6
1 1 2 2 3 3
Output
YES
RL
LRLR
RLLRRL
NoteIn the first array, we add the first element to R and the second to L. Now L = \{2\}, and R = \{1\}.In the second array, we add the first and third elements to L and the rest to R. Now L = \{1, 2, 3\} and R = \{1, 2, 3\}.In the third array, we add elements 2, 3, and 6 to L, and others — to R. As a result, L = R = \{1, 1, 2, 2, 3, 3\}. | 3
2
1 2
4
1 2 3 3
6
1 1 2 2 3 3
| YES RL LRLR RLLRRL | 1.5 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'dfs and similar', 'graph matchings', 'graphs', '*2400'] |
D. Finding Zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output This is an interactive problem.We picked an array of whole numbers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) and concealed exactly one zero in it! Your goal is to find the location of this zero, that is, to find i such that a_i = 0.You are allowed to make several queries to guess the answer. For each query, you can think up three distinct indices i, j, k, and we will tell you the value of \max(a_i, a_j, a_k) - \min(a_i, a_j, a_k). In other words, we will tell you the difference between the maximum and the minimum number among a_i, a_j and a_k.You are allowed to make no more than 2 \cdot n - 2 queries, and after that you have two tries to guess where the zero is. That is, you have to tell us two numbers i and j and you win if a_i = 0 or a_j = 0.Can you guess where we hid the zero?Note that the array in each test case is fixed beforehand and will not change during the game. In other words, the interactor is not adaptive.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 500). Description of the test cases follows.The first and only line of each test case contains an integer n (4 \le n \le 1000) — the length of the array that we picked.It is guaranteed that the sum of n over all test cases does not exceed 3000.InteractionFor each test case, the interaction starts with reading n.To make a query, print "? i j k" (without quotes, 1 \le i, j, k \le n, indices must be distinct). Then you should read our response from standard input, that is, \max(a_i, a_j, a_k) - \min(a_i, a_j, a_k).If the response is -1, it means your program has made an invalid query or has run out of tries. Your program must terminate immediately after reading -1, and you will get a verdict Wrong answer. Otherwise you may get any verdict, because the program will continue reading from the closed stream. Note that if the query is correct, the answer will never be -1 because \max(a_i, a_j, a_k) - \min(a_i, a_j, a_k) \geq 0.To give the final answer, print "! i j" (without the quotes). Printing the same number twice (that is, i = j) is allowed. Note that giving this answer is not counted towards the limit of 2 \cdot n - 2 queries. After that, your program must continue to solve the remaining test cases, or exit if all test cases have been solved.After printing a query, don't forget to output line feed and flush the output buffer. Otherwise you will get the verdict Idleness limit exceeded. To flush the buffer, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; Read documentation for other languages.HacksThe first line must contain an integer t (1 \le t \le 500) — the count of test cases.The first line of each test case must contain an integer n (4 \le n \le 1000) — the length of the hidden array.The second line of each test case must contain n integers separated by spaces — a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9). There must also be exactly one zero in this array.The sum of n over all test cases must not exceed 3000.ExampleInput
1
4
2
3
3
2
Output
? 1 2 3
? 2 3 4
? 3 4 1
? 4 1 2
! 2 3NoteArray from sample: [1, 2, 0, 3]. | 1
4
2
3
3
2
| ? 1 2 3 ? 2 3 4 ? 3 4 1 ? 4 1 2 ! 2 3 | 1 second | 256 megabytes | ['constructive algorithms', 'interactive', 'math', '*2000'] |
C. OKEAtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPeople worry that computers will get too smart and take over the world, but the real problem is that they're too stupid and they've already taken over the world.— Pedro DomingosYou work for a well-known department store that uses leading technologies and employs mechanistic work — that is, robots!The department you work in sells n \cdot k items. The first item costs 1 dollar, the second item costs 2 dollars, and so on: i-th item costs i dollars. The items are situated on shelves. The items form a rectangular grid: there are n shelves in total, and each shelf contains exactly k items. We will denote by a_{i,j} the price of j-th item (counting from the left) on the i-th shelf, 1 \le i \le n, 1 \le j \le k.Occasionally robots get curious and ponder on the following question: what is the mean price (arithmetic average) of items a_{i,l}, a_{i,l+1}, \ldots, a_{i,r} for some shelf i and indices l \le r? Unfortunately, the old robots can only work with whole numbers. If the mean price turns out not to be an integer, they break down.You care about robots' welfare. You want to arrange the items in such a way that the robots cannot theoretically break. Formally, you want to choose such a two-dimensional array a that: Every number from 1 to n \cdot k (inclusively) occurs exactly once. For each i, l, r, the mean price of items from l to r on i-th shelf is an integer. Find out if such an arrangement is possible, and if it is, give any example of such arrangement.InputThe first line contains a single integer t (1 \le t \le 500) — the number of test cases.The first and only line of each test case contains two integers n and k (1 \le n, k \le 500) — the number of shelves and length of each shelf, respectively.It is guaranteed that the sum n over all test cases does not exceed 500 and the sum k over all test cases does not exceed 500.OutputPrint the answer for each test case.If such an arrangement exists, print "YES" on a single line. After that, print any example on n lines of k numbers each, one line per shelf. Each number from 1 to n \cdot k must occur exactly once in the output.If no good arrangement exists, print a single word "NO" on its own line.ExampleInput
4
1 1
2 2
3 3
3 1
Output
YES
1
YES
1 3
2 4
NO
YES
1
2
3
| 4
1 1
2 2
3 3
3 1
| YES 1 YES 1 3 2 4 NO YES 1 2 3 | 1 second | 256 megabytes | ['constructive algorithms', '*1000'] |
B. Fortune Tellingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHaha, try to solve this, SelectorUnlimited!— antontrygubO_oYour friends Alice and Bob practice fortune telling.Fortune telling is performed as follows. There is a well-known array a of n non-negative integers indexed from 1 to n. The tellee starts with some non-negative number d and performs one of the two operations for each i = 1, 2, \ldots, n, in the increasing order of i. The possible operations are: replace their current number d with d + a_i replace their current number d with d \oplus a_i (hereinafter \oplus denotes the bitwise XOR operation)Notice that the chosen operation may be different for different i and for different tellees.One time, Alice decided to start with d = x and Bob started with d = x + 3. Each of them performed fortune telling and got a particular number in the end. Notice that the friends chose operations independently of each other, that is, they could apply different operations for the same i.You learnt that either Alice or Bob ended up with number y in the end, but you don't know whose of the two it was. Given the numbers Alice and Bob started with and y, find out who (Alice or Bob) could get the number y after performing the operations. It is guaranteed that on the jury tests, exactly one of your friends could have actually gotten that number.HacksYou cannot make hacks in this problem.InputOn the first line of the input, you are given one number t (1 \le t \le 10^4) — the number of test cases. The following 2 \cdot t lines contain test cases.The first line of each test case contains three numbers n, x, y (1 \le n \le 10^5, 0 \le x \le 10^9, 0 \le y \le 10^{15}) — the length of array a, Alice's initial number (Bob's initial number is therefore x+3), and the number that one of the two friends got in the end.The second line of each test case contains n numbers — the array a (0 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print the name of the friend who could get the number y: "Alice" or "Bob".ExampleInput
4
1 7 9
2
2 0 2
1 3
4 0 1
1 2 3 4
2 1000000000 3000000000
1000000000 1000000000
Output
Alice
Alice
Bob
Alice
NoteIn the first test case, Alice could get 9 using the following operations: 7 + 2 = 9.In the second test case, Alice could get 2 using this operations: (0 + 1) \oplus 3 = 2.In the third test case, Bob started with x+3 = 0+3=3 and could get 1 this way: (((3 + 1) + 2) \oplus 3) \oplus 4 = 1. | 4
1 7 9
2
2 0 2
1 3
4 0 1
1 2 3 4
2 1000000000 3000000000
1000000000 1000000000
| Alice Alice Bob Alice | 1 second | 256 megabytes | ['bitmasks', 'math', '*1400'] |
A. Reverse and Concatenatetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReal stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string s of length n and a number k. Let's denote by rev(s) the reversed string s (i.e. rev(s) = s_n s_{n-1} ... s_1). You can apply one of the two kinds of operations to the string: replace the string s with s + rev(s) replace the string s with rev(s) + sHow many different strings can you get as a result of performing exactly k operations (possibly of different kinds) on the original string s?In this statement we denoted the concatenation of strings s and t as s + t. In other words, s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m, where n and m are the lengths of strings s and t respectively.InputThe first line contains one integer t (1 \le t \le 100) — number of test cases. Next 2 \cdot t lines contain t test cases:The first line of a test case contains two integers n and k (1 \le n \le 100, 0 \le k \le 1000) — the length of the string and the number of operations respectively.The second string of a test case contains one string s of length n consisting of lowercase Latin letters.OutputFor each test case, print the answer (that is, the number of different strings that you can get after exactly k operations) on a separate line.It can be shown that the answer does not exceed 10^9 under the given constraints.ExampleInput
4
3 2
aab
3 3
aab
7 1
abacaba
2 0
ab
Output
2
2
1
1
NoteIn the first test case of the example:After the first operation the string s can become either aabbaa or baaaab. After the second operation there are 2 possibilities for s: aabbaaaabbaa and baaaabbaaaab. | 4
3 2
aab
3 3
aab
7 1
abacaba
2 0
ab
| 2 2 1 1 | 1 second | 256 megabytes | ['greedy', 'strings', '*800'] |
F. Perfect Matchingtime limit per test12 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices (numbered from 1 to n) and n-1 edges (numbered from 1 to n-1). Initially, all vertices except vertex 1 are inactive.You have to process queries of three types: 1 v — activate the vertex v. It is guaranteed that the vertex v is inactive before this query, and one of its neighbors is active. After activating the vertex, you have to choose a subset of edges of the tree such that each active vertex is incident to exactly one chosen edge, and each inactive vertex is not incident to any of the chosen edges — in other words, this subset should represent a perfect matching on the active part of the tree. If any such subset of edges exists, print the sum of indices of edges in it; otherwise, print 0. 2 — queries of this type will be asked only right after a query of type 1, and there will be at most 10 such queries. If your answer to the previous query was 0, simply print 0; otherwise, print the subset of edges for the previous query as follows: first, print the number of edges in the subset, then print the indices of the chosen edges in ascending order. The sum of indices should be equal to your answer to the previous query. 3 — terminate the program. Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.InputThe first line contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of vertices of the tree.Then n-1 lines follow. The i-th line contains two integers u_i and v_i (1 \le u_i, v_i \le n; u_i \ne v_i) — the endpoints of the i-th edge. These edges form a tree.Then the queries follow in the format described in the statement, one line per query. There will be at least 2 and at most n+10 queries. The last query (and only the last one) will be of type 3. Note that you can read the i-th query only if you have already given the answer for the query i-1 (except for i = 1).If your answer for one of the queries is incorrect and the judging program recognizes it, instead of the next query, you may receive the integer 0 on a separate line. After receiving it, your program should terminate gracefully, and you will receive "Wrong Answer" verdict. If your program doesn't terminate, your solution may receive some other verdict, like "Time Limit Exceeded", "Idleness Limit Exceeded", etc. Note that the fact that your solution doesn't receive the integer 0, it does not mean that all your answers are correct, some of them will be checked only after your program is terminated.OutputFor each query of type 1 or 2, print the answer on a separate line as described in the statement. Don't forget to flush the output.ExampleInput
6
1 4
6 1
3 2
1 2
5 1
1 4
2
1 2
2
1 3
2
1 5
1 6
2
3
Output
1
1 1
0
0
4
2 1 3
0
0
0
| 6
1 4
6 1
3 2
1 2
5 1
1 4
2
1 2
2
1 3
2
1 5
1 6
2
3
| 1 1 1 0 0 4 2 1 3 0 0 0 | 12 seconds | 512 megabytes | ['data structures', 'divide and conquer', 'interactive', 'trees', '*2800'] |
E. Spanning Tree Queriestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a connected weighted undirected graph, consisting of n vertices and m edges.You are asked k queries about it. Each query consists of a single integer x. For each query, you select a spanning tree in the graph. Let the weights of its edges be w_1, w_2, \dots, w_{n-1}. The cost of a spanning tree is \sum \limits_{i=1}^{n-1} |w_i - x| (the sum of absolute differences between the weights and x). The answer to a query is the lowest cost of a spanning tree.The queries are given in a compressed format. The first p (1 \le p \le k) queries q_1, q_2, \dots, q_p are provided explicitly. For queries from p+1 to k, q_j = (q_{j-1} \cdot a + b) \mod c.Print the xor of answers to all queries.InputThe first line contains two integers n and m (2 \le n \le 50; n - 1 \le m \le 300) — the number of vertices and the number of edges in the graph.Each of the next m lines contains a description of an undirected edge: three integers v, u and w (1 \le v, u \le n; v \neq u; 0 \le w \le 10^8) — the vertices the edge connects and its weight. Note that there might be multiple edges between a pair of vertices. The edges form a connected graph.The next line contains five integers p, k, a, b and c (1 \le p \le 10^5; p \le k \le 10^7; 0 \le a, b \le 10^8; 1 \le c \le 10^8) — the number of queries provided explicitly, the total number of queries and parameters to generate the queries.The next line contains p integers q_1, q_2, \dots, q_p (0 \le q_j < c) — the first p queries.OutputPrint a single integer — the xor of answers to all queries.ExamplesInput
5 8
4 1 4
3 1 0
3 5 3
2 5 4
3 4 8
4 3 4
4 2 8
5 3 9
3 11 1 1 10
0 1 2
Output
4
Input
6 7
2 4 0
5 4 7
2 4 0
2 1 7
2 6 1
3 4 4
1 4 8
4 10 3 3 7
3 0 2 1
Output
5
Input
3 3
1 2 50
2 3 100
1 3 150
1 10000000 0 0 100000000
75
Output
164
NoteThe queries in the first example are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0. The answers are 11, 9, 7, 3, 1, 5, 8, 7, 5, 7, 11. The queries in the second example are 3, 0, 2, 1, 6, 0, 3, 5, 4, 1. The answers are 14, 19, 15, 16, 11, 19, 14, 12, 13, 16. The queries in the third example are 75, 0, 0, \dots. The answers are 50, 150, 150, \dots. | 5 8
4 1 4
3 1 0
3 5 3
2 5 4
3 4 8
4 3 4
4 2 8
5 3 9
3 11 1 1 10
0 1 2
| 4 | 4 seconds | 256 megabytes | ['binary search', 'data structures', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'math', 'sortings', 'trees', '*2400'] |
D. Make Them Equaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array of integers a of size n. Initially, all elements of the array are equal to 1. You can perform the following operation: choose two integers i (1 \le i \le n) and x (x > 0), and then increase the value of a_i by \left\lfloor\frac{a_i}{x}\right\rfloor (i.e. make a_i = a_i + \left\lfloor\frac{a_i}{x}\right\rfloor).After performing all operations, you will receive c_i coins for all such i that a_i = b_i.Your task is to determine the maximum number of coins that you can receive by performing no more than k operations.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains two integers n and k (1 \le n \le 10^3; 0 \le k \le 10^6) — the size of the array and the maximum number of operations, respectively.The second line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^3).The third line contains n integers c_1, c_2, \dots, c_n (1 \le c_i \le 10^6).The sum of n over all test cases does not exceed 10^3.OutputFor each test case, print one integer — the maximum number of coins that you can get by performing no more than k operations.ExampleInput
4
4 4
1 7 5 2
2 6 5 2
3 0
3 5 2
5 4 7
5 9
5 2 5 6 3
5 9 1 9 7
6 14
11 4 6 2 8 16
43 45 9 41 15 38
Output
9
0
30
167
| 4
4 4
1 7 5 2
2 6 5 2
3 0
3 5 2
5 4 7
5 9
5 2 5 6 3
5 9 1 9 7
6 14
11 4 6 2 8 16
43 45 9 41 15 38
| 9 0 30 167 | 2 seconds | 256 megabytes | ['dp', 'greedy', '*1600'] |
C. Kill the Monstertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is playing a computer game. In this game, his character fights different monsters.A fight between a character and a monster goes as follows. Suppose the character initially has health h_C and attack d_C; the monster initially has health h_M and attack d_M. The fight consists of several steps: the character attacks the monster, decreasing the monster's health by d_C; the monster attacks the character, decreasing the character's health by d_M; the character attacks the monster, decreasing the monster's health by d_C; the monster attacks the character, decreasing the character's health by d_M; and so on, until the end of the fight. The fight ends when someone's health becomes non-positive (i. e. 0 or less). If the monster's health becomes non-positive, the character wins, otherwise the monster wins.Monocarp's character currently has health equal to h_C and attack equal to d_C. He wants to slay a monster with health equal to h_M and attack equal to d_M. Before the fight, Monocarp can spend up to k coins to upgrade his character's weapon and/or armor; each upgrade costs exactly one coin, each weapon upgrade increases the character's attack by w, and each armor upgrade increases the character's health by a.Can Monocarp's character slay the monster if Monocarp spends coins on upgrades optimally?InputThe first line contains one integer t (1 \le t \le 5 \cdot 10^4) — the number of test cases. Each test case consists of three lines:The first line contains two integers h_C and d_C (1 \le h_C \le 10^{15}; 1 \le d_C \le 10^9) — the character's health and attack;The second line contains two integers h_M and d_M (1 \le h_M \le 10^{15}; 1 \le d_M \le 10^9) — the monster's health and attack;The third line contains three integers k, w and a (0 \le k \le 2 \cdot 10^5; 0 \le w \le 10^4; 0 \le a \le 10^{10}) — the maximum number of coins that Monocarp can spend, the amount added to the character's attack with each weapon upgrade, and the amount added to the character's health with each armor upgrade, respectively.The sum of k over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print YES if it is possible to slay the monster by optimally choosing the upgrades. Otherwise, print NO.ExampleInput
4
25 4
9 20
1 1 10
25 4
12 20
1 1 10
100 1
45 2
0 4 10
9 2
69 2
4 2 7
Output
YES
NO
YES
YES
NoteIn the first example, Monocarp can spend one coin to upgrade weapon (damage will be equal to 5), then health during battle will change as follows: (h_C, h_M) = (25, 9) \rightarrow (25, 4) \rightarrow (5, 4) \rightarrow (5, -1). The battle ended with Monocarp's victory.In the second example, Monocarp has no way to defeat the monster.In the third example, Monocarp has no coins, so he can't buy upgrades. However, the initial characteristics are enough for Monocarp to win.In the fourth example, Monocarp has 4 coins. To defeat the monster, he has to spend 2 coins to upgrade weapon and 2 coins to upgrade armor. | 4
25 4
9 20
1 1 10
25 4
12 20
1 1 10
100 1
45 2
0 4 10
9 2
69 2
4 2 7
| YES NO YES YES | 2 seconds | 256 megabytes | ['brute force', 'math', '*1100'] |
B. Minoritytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting only of characters '0' and '1'.You have to choose a contiguous substring of s and remove all occurrences of the character, which is a strict minority in it, from the substring.That is, if the amount of '0's in the substring is strictly smaller than the amount of '1's, remove all occurrences of '0' from the substring. If the amount of '1's is strictly smaller than the amount of '0's, remove all occurrences of '1'. If the amounts are the same, do nothing.You have to apply the operation exactly once. What is the maximum amount of characters that can be removed?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The only line of each testcase contains a non-empty string s, consisting only of characters '0' and '1'. The length of s doesn't exceed 2 \cdot 10^5.The total length of strings s over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the maximum amount of characters that can be removed after applying the operation exactly once.ExampleInput
4
01
1010101010111
00110001000
1
Output
0
5
3
0
NoteIn the first testcase, you can choose substrings "0", "1" or "01". In "0" the amount of '0' is 1, the amount of '1' is 0. '1' is a strict minority, thus all occurrences of it are removed from the substring. However, since there were 0 of them, nothing changes. Same for "1". And in "01" neither of '0' or '1' is a strict minority. Thus, nothing changes. So there is no way to remove any characters.In the second testcase, you can choose substring "10101010101". It contains 5 characters '0' and 6 characters '1'. '0' is a strict minority. Thus, you can remove all its occurrences. There exist other substrings that produce the same answer.In the third testcase, you can choose substring "011000100". It contains 6 characters '0' and 3 characters '1'. '1' is a strict minority. Thus, you can remove all its occurrences. | 4
01
1010101010111
00110001000
1
| 0 5 3 0 | 2 seconds | 256 megabytes | ['greedy', '*800'] |
A. Div. 7time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an integer n. You have to change the minimum number of digits in it in such a way that the resulting number does not have any leading zeroes and is divisible by 7.If there are multiple ways to do it, print any of them. If the given number is already divisible by 7, leave it unchanged.InputThe first line contains one integer t (1 \le t \le 990) — the number of test cases.Then the test cases follow, each test case consists of one line containing one integer n (10 \le n \le 999).OutputFor each test case, print one integer without any leading zeroes — the result of your changes (i. e. the integer that is divisible by 7 and can be obtained by changing the minimum possible number of digits in n).If there are multiple ways to apply changes, print any resulting number. If the given number is already divisible by 7, just print it.ExampleInput
3
42
23
377
Output
42
28
777
NoteIn the first test case of the example, 42 is already divisible by 7, so there's no need to change it.In the second test case of the example, there are multiple answers — 28, 21 or 63.In the third test case of the example, other possible answers are 357, 371 and 378. Note that you cannot print 077 or 77. | 3
42
23
377
| 42 28 777 | 2 seconds | 512 megabytes | ['brute force', '*800'] |
E2. Distance Tree (hard version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis version of the problem differs from the previous one only in the constraint on n.A tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The distance between two vertices is the minimum sum of weights on the path connecting them.You are given a weighted tree with n vertices, each edge has a weight of 1. Denote d(v) as the distance between vertex 1 and vertex v.Let f(x) be the minimum possible value of \max\limits_{1 \leq v \leq n} \ {d(v)} if you can temporarily add an edge with weight x between any two vertices a and b (1 \le a, b \le n). Note that after this operation, the graph is no longer a tree.For each integer x from 1 to n, find f(x).InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 3 \cdot 10^5).Each of the next n−1 lines contains two integers u and v (1 \le u,v \le n) indicating that there is an edge between vertices u and v. It is guaranteed that the given edges form a tree.It is guaranteed that the sum of n over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case, print n integers in a single line, x-th of which is equal to f(x) for all x from 1 to n.ExampleInput
341 22 31 421 271 21 33 43 53 65 7Output
1 2 2 2
1 1
2 2 3 3 3 3 3
Note In the first testcase: For x = 1, we can an edge between vertices 1 and 3, then d(1) = 0 and d(2) = d(3) = d(4) = 1, so f(1) = 1. For x \ge 2, no matter which edge we add, d(1) = 0, d(2) = d(4) = 1 and d(3) = 2, so f(x) = 2. | 341 22 31 421 271 21 33 43 53 65 7 | 1 2 2 2 1 1 2 2 3 3 3 3 3 | 2 seconds | 512 megabytes | ['binary search', 'dfs and similar', 'shortest paths', 'trees', '*2700'] |
E1. Distance Tree (easy version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis version of the problem differs from the next one only in the constraint on n.A tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The distance between two vertices is the minimum sum of weights on the path connecting them.You are given a weighted tree with n vertices, each edge has a weight of 1. Denote d(v) as the distance between vertex 1 and vertex v.Let f(x) be the minimum possible value of \max\limits_{1 \leq v \leq n} \ {d(v)} if you can temporarily add an edge with weight x between any two vertices a and b (1 \le a, b \le n). Note that after this operation, the graph is no longer a tree.For each integer x from 1 to n, find f(x).InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 3000).Each of the next n−1 lines contains two integers u and v (1 \le u,v \le n) indicating that there is an edge between vertices u and v. It is guaranteed that the given edges form a tree.It is guaranteed that the sum of n over all test cases doesn't exceed 3000.OutputFor each test case, print n integers in a single line, x-th of which is equal to f(x) for all x from 1 to n.ExampleInput
341 22 31 421 271 21 33 43 53 65 7Output
1 2 2 2
1 1
2 2 3 3 3 3 3
Note In the first testcase: For x = 1, we can an edge between vertices 1 and 3, then d(1) = 0 and d(2) = d(3) = d(4) = 1, so f(1) = 1. For x \ge 2, no matter which edge we add, d(1) = 0, d(2) = d(4) = 1 and d(3) = 2, so f(x) = 2. | 341 22 31 421 271 21 33 43 53 65 7 | 1 2 2 2 1 1 2 2 3 3 3 3 3 | 2 seconds | 512 megabytes | ['binary search', 'data structures', 'dfs and similar', 'graphs', 'shortest paths', 'trees', '*2400'] |
D. New Year Concerttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNew Year is just around the corner, which means that in School 179, preparations for the concert are in full swing.There are n classes in the school, numbered from 1 to n, the i-th class has prepared a scene of length a_i minutes.As the main one responsible for holding the concert, Idnar knows that if a concert has k scenes of lengths b_1, b_2, \ldots, b_k minutes, then the audience will get bored if there exist two integers l and r such that 1 \le l \le r \le k and \gcd(b_l, b_{l + 1}, \ldots, b_{r - 1}, b_r) = r - l + 1, where \gcd(b_l, b_{l + 1}, \ldots, b_{r - 1}, b_r) is equal to the greatest common divisor (GCD) of the numbers b_l, b_{l + 1}, \ldots, b_{r - 1}, b_r.To avoid boring the audience, Idnar can ask any number of times (possibly zero) for the t-th class (1 \le t \le k) to make a new scene d minutes in length, where d can be any positive integer. Thus, after this operation, b_t is equal to d. Note that t and d can be different for each operation.For a sequence of scene lengths b_1, b_2, \ldots, b_{k}, let f(b) be the minimum number of classes Idnar has to ask to change their scene if he wants to avoid boring the audience.Idnar hasn't decided which scenes will be allowed for the concert, so he wants to know the value of f for each non-empty prefix of a. In other words, Idnar wants to know the values of f(a_1), f(a_1,a_2), \ldots, f(a_1,a_2,\ldots,a_n).InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of classes in the school.The second line contains n positive integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the lengths of the class scenes.OutputPrint a sequence of n integers in a single line — f(a_1), f(a_1,a_2), \ldots, f(a_1,a_2,\ldots,a_n).ExamplesInput
1
1
Output
1 Input
3
1 4 2
Output
1 1 2 Input
7
2 12 4 8 18 3 6
Output
0 1 1 1 2 2 2 NoteIn the first test we can change 1 to 2, so the answer is 1.In the second test: [1] can be changed into [2], [1, 4] can be changed into [3, 4], [1, 4, 2] can be changed into [2, 3, 2]. | 1
1
| 1 | 3 seconds | 256 megabytes | ['binary search', 'data structures', 'greedy', 'math', 'number theory', 'two pointers', '*2000'] |
C. Strange Testtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor is in 11th grade. Tomorrow he will have to write an informatics test by the strictest teacher in the school, Pavel Denisovich. Igor knows how the test will be conducted: first of all, the teacher will give each student two positive integers a and b (a < b). After that, the student can apply any of the following operations any number of times: a := a + 1 (increase a by 1), b := b + 1 (increase b by 1), a := a \ | \ b (replace a with the bitwise OR of a and b). To get full marks on the test, the student has to tell the teacher the minimum required number of operations to make a and b equal.Igor already knows which numbers the teacher will give him. Help him figure out what is the minimum number of operations needed to make a equal to b.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). Description of the test cases follows.The only line for each test case contains two integers a and b (1 \le a < b \le 10^6).It is guaranteed that the sum of b over all test cases does not exceed 10^6.OutputFor each test case print one integer — the minimum required number of operations to make a and b equal.ExampleInput
5
1 3
5 8
2 5
3 19
56678 164422
Output
1
3
2
1
23329
NoteIn the first test case, it is optimal to apply the third operation.In the second test case, it is optimal to apply the first operation three times.In the third test case, it is optimal to apply the second operation and then the third operation. | 5
1 3
5 8
2 5
3 19
56678 164422
| 1 3 2 1 23329 | 1 second | 256 megabytes | ['binary search', 'bitmasks', 'brute force', 'dp', 'math', '*1600'] |
B. Roof Constructiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt has finally been decided to build a roof over the football field in School 179. Its construction will require placing n consecutive vertical pillars. Furthermore, the headmaster wants the heights of all the pillars to form a permutation p of integers from 0 to n - 1, where p_i is the height of the i-th pillar from the left (1 \le i \le n).As the chief, you know that the cost of construction of consecutive pillars is equal to the maximum value of the bitwise XOR of heights of all pairs of adjacent pillars. In other words, the cost of construction is equal to \max\limits_{1 \le i \le n - 1}{p_i \oplus p_{i + 1}}, where \oplus denotes the bitwise XOR operation.Find any sequence of pillar heights p of length n with the smallest construction cost.In this problem, a permutation is an array consisting of n distinct integers from 0 to n - 1 in arbitrary order. For example, [2,3,1,0,4] is a permutation, but [1,0,1] is not a permutation (1 appears twice in the array) and [1,0,3] is also not a permutation (n=3, but 3 is in the array).InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). Description of the test cases follows.The only line for each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of pillars for the construction of the roof.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 p_1, p_2, \ldots, p_n — the sequence of pillar heights with the smallest construction cost.If there are multiple answers, print any of them.ExampleInput
423510Output
0 1
2 0 1
3 2 1 0 4
4 6 3 2 0 8 9 1 7 5
NoteFor n = 2 there are 2 sequences of pillar heights: [0, 1] — cost of construction is 0 \oplus 1 = 1. [1, 0] — cost of construction is 1 \oplus 0 = 1. For n = 3 there are 6 sequences of pillar heights: [0, 1, 2] — cost of construction is \max(0 \oplus 1, 1 \oplus 2) = \max(1, 3) = 3. [0, 2, 1] — cost of construction is \max(0 \oplus 2, 2 \oplus 1) = \max(2, 3) = 3. [1, 0, 2] — cost of construction is \max(1 \oplus 0, 0 \oplus 2) = \max(1, 2) = 2. [1, 2, 0] — cost of construction is \max(1 \oplus 2, 2 \oplus 0) = \max(3, 2) = 3. [2, 0, 1] — cost of construction is \max(2 \oplus 0, 0 \oplus 1) = \max(2, 1) = 2. [2, 1, 0] — cost of construction is \max(2 \oplus 1, 1 \oplus 0) = \max(3, 1) = 3. | 423510 | 0 1 2 0 1 3 2 1 0 4 4 6 3 2 0 8 9 1 7 5 | 1 second | 256 megabytes | ['bitmasks', 'constructive algorithms', '*1000'] |
A. ABCtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, the students of School 179 have developed a unique algorithm, which takes in a binary string s as input. However, they soon found out that if some substring t of s is a palindrome of length greater than 1, the algorithm will work incorrectly. Can the students somehow reorder the characters of s so that the algorithm will work correctly on the string?A binary string is a string where each character is either 0 or 1.A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.A palindrome is a string that reads the same backwards as forwards.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 a single integer n (1 \le n \le 100) — the length of the string s.The second line of each test case contains the string s of length n consisting only of the characters 0 and 1.OutputFor each test case, print YES (case-insensitive) if it is possible to reorder the characters of s so that there are no substrings that are a palindrome of length greater than 1, or NO (case-insensitive) otherwise.ExampleInput
41121020141010Output
YES
YES
YES
NO
NoteIn the first three test cases, the given strings do not contain palindromes of length greater than 1, so the answers are YES.In the last test case, it is impossible to reorder the characters so that the string does not contain palindromes of length greater than 1, so the answer is NO. | 41121020141010 | YES YES YES NO | 1 second | 256 megabytes | ['implementation', '*800'] |
B. Fun with Even Subarraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n elements. You can apply the following operation to it any number of times: Select some subarray from a of even size 2k that begins at position l (1\le l \le l+2\cdot{k}-1\le n, k \ge 1) and for each i between 0 and k-1 (inclusive), assign the value a_{l+k+i} to a_{l+i}. For example, if a = [2, 1, 3, 4, 5, 3], then choose l = 1 and k = 2, applying this operation the array will become a = [3, 4, 3, 4, 5, 3].Find the minimum number of operations (possibly zero) needed to make all the elements of the array equal.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 2 \cdot 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the array.The second line of each test case consists of n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq n) — 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.OutputPrint t lines, each line containing the answer to the corresponding test case — the minimum number of operations needed to make equal all the elements of the array with the given operation.ExampleInput
531 1 122 154 4 4 2 444 2 1 311Output
0
1
1
2
0
NoteIn the first test, all elements are equal, therefore no operations are needed.In the second test, you can apply one operation with k=1 and l=1, set a_1 := a_2, and the array becomes [1, 1] with 1 operation.In the third test, you can apply one operation with k=1 and l=4, set a_4 := a_5, and the array becomes [4, 4, 4, 4, 4].In the fourth test, you can apply one operation with k=1 and l=3, set a_3 := a_4, and the array becomes [4, 2, 3, 3], then you can apply another operation with k=2 and l=1, set a_1 := a_3, a_2 := a_4, and the array becomes [3, 3, 3, 3].In the fifth test, there is only one element, therefore no operations are needed. | 531 1 122 154 4 4 2 444 2 1 311 | 0 1 1 2 0 | 1 second | 256 megabytes | ['dp', 'greedy', '*1100'] |
A. Min Max Swaptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b of n positive integers each. You can apply the following operation to them any number of times: Select an index i (1\leq i\leq n) and swap a_i with b_i (i. e. a_i becomes b_i and vice versa). Find the minimum possible value of \max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n) you can get after applying such operation any number of times (possibly zero). InputThe input 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 first line of each test case contains an integer n (1\le n\le 100) — the length of the arrays.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10\,000) where a_i is the i-th element of the array a.The third line of each test case contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le 10\,000) where b_i is the i-th element of the array b.OutputFor each test case, print a single integer, the minimum possible value of \max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n) you can get after applying such operation any number of times.ExampleInput
361 2 6 5 1 23 4 3 2 2 533 3 33 3 321 22 1Output
18
9
2
NoteIn the first test, you can apply the operations at indices 2 and 6, then a = [1, 4, 6, 5, 1, 5] and b = [3, 2, 3, 2, 2, 2], \max(1, 4, 6, 5, 1, 5) \cdot \max(3, 2, 3, 2, 2, 2) = 6 \cdot 3 = 18.In the second test, no matter how you apply the operations, a = [3, 3, 3] and b = [3, 3, 3] will always hold, so the answer is \max(3, 3, 3) \cdot \max(3, 3, 3) = 3 \cdot 3 = 9.In the third test, you can apply the operation at index 1, then a = [2, 2], b = [1, 1], so the answer is \max(2, 2) \cdot \max(1, 1) = 2 \cdot 1 = 2. | 361 2 6 5 1 23 4 3 2 2 533 3 33 3 321 22 1 | 18 9 2 | 1 second | 256 megabytes | ['greedy', '*800'] |
F. Making It Bipartitetime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph of n vertices indexed from 1 to n, where vertex i has a value a_i assigned to it and all values a_i are different. There is an edge between two vertices u and v if either a_u divides a_v or a_v divides a_u.Find the minimum number of vertices to remove such that the remaining graph is bipartite, when you remove a vertex you remove all the edges incident to it.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 5\cdot10^4) — the number of vertices in the graph.The second line of each test case contains n integers, the i-th of them is the value a_i (1 \le a_i \le 5\cdot10^4) assigned to the i-th vertex, all values a_i are different.It is guaranteed that the sum of n over all test cases does not exceed 5\cdot10^4.OutputFor each test case print a single integer — the minimum number of vertices to remove such that the remaining graph is bipartite.ExampleInput
448 4 2 1430 2 3 5512 4 6 2 31085 195 5 39 3 13 266 154 14 2Output
2
0
1
2
NoteIn the first test case if we remove the vertices with values 1 and 2 we will obtain a bipartite graph, so the answer is 2, it is impossible to remove less than 2 vertices and still obtain a bipartite graph. BeforeAfter test case #1 In the second test case we do not have to remove any vertex because the graph is already bipartite, so the answer is 0. BeforeAfter test case #2 In the third test case we only have to remove the vertex with value 12, so the answer is 1. BeforeAfter test case #3 In the fourth test case we remove the vertices with values 2 and 195, so the answer is 2. BeforeAfter test case #4 | 448 4 2 1430 2 3 5512 4 6 2 31085 195 5 39 3 13 266 154 14 2 | 2 0 1 2 | 4 seconds | 512 megabytes | ['flows', 'graph matchings', 'graphs', 'number theory', '*3400'] |
E. Expected Componentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a cyclic array a of size n, where a_i is the value of a in the i-th position, there may be repeated values. Let us define that a permutation of a is equal to another permutation of a if and only if their values are the same for each position i or we can transform them to each other by performing some cyclic rotation. Let us define for a cyclic array b its number of components as the number of connected components in a graph, where the vertices are the positions of b and we add an edge between each pair of adjacent positions of b with equal values (note that in a cyclic array the first and last position are also adjacents).Find the expected value of components of a permutation of a if we select it equiprobably over the set of all the different permutations of a.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^5) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^6) — the size of the cyclic array a.The second line of each test case contains n integers, the i-th of them is the value a_i (1 \le a_i \le n).It is guaranteed that the sum of n over all test cases does not exceed 10^6.It is guaranteed that the total number of different permutations of a is not divisible by MOutputFor each test case print a single integer — the expected value of components of a permutation of a if we select it equiprobably over the set of all the different permutations of a modulo 998\,244\,353. Formally, let M = 998\,244\,353. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.ExampleInput
541 1 1 141 1 2 141 2 1 254 3 2 5 1121 3 2 3 2 1 3 3 1 3 3 2Output
1
2
3
5
358642921
NoteIn the first test case there is only 1 different permutation of a: [1, 1, 1, 1] has 1 component. Therefore the expected value of components is \frac{1}{1} = 1 In the second test case there are 4 ways to permute the cyclic array a, but there is only 1 different permutation of a: [1, 1, 1, 2], [1, 1, 2, 1], [1, 2, 1, 1] and [2, 1, 1, 1] are the same permutation and have 2 components. Therefore the expected value of components is \frac{2}{1} = 2 In the third test case there are 6 ways to permute the cyclic array a, but there are only 2 different permutations of a: [1, 1, 2, 2], [2, 1, 1, 2], [2, 2, 1, 1] and [1, 2, 2, 1] are the same permutation and have 2 components. [1, 2, 1, 2] and [2, 1, 2, 1] are the same permutation and have 4 components. Therefore the expected value of components is \frac{2+4}{2} = \frac{6}{2} = 3 In the fourth test case there are 120 ways to permute the cyclic array a, but there are only 24 different permutations of a: Any permutation of a has 5 components. Therefore the expected value of components is \frac{24\cdot 5}{24} = \frac{120}{24} = 5 | 541 1 1 141 1 2 141 2 1 254 3 2 5 1121 3 2 3 2 1 3 3 1 3 3 2 | 1 2 3 5 358642921 | 2 seconds | 256 megabytes | ['combinatorics', 'math', 'number theory', 'probabilities', '*2900'] |
D. Flipping Rangetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers and a set B of m positive integers such that 1 \leq b_i \leq \lfloor \frac{n}{2} \rfloor for 1\le i\le m, where b_i is the i-th element of B. You can make the following operation on a: Select some x such that x appears in B. Select an interval from array a of size x and multiply by -1 every element in the interval. Formally, select l and r such that 1\leq l\leq r \leq n and r-l+1=x, then assign a_i:=-a_i for every i such that l\leq i\leq r. Consider the following example, let a=[0,6,-2,1,-4,5] and B=\{1,2\}: [0,6,-2,-1,4,5] is obtained after choosing size 2 and l=4, r=5. [0,6,2,-1,4,5] is obtained after choosing size 1 and l=3, r=3. Find the maximum \sum\limits_{i=1}^n {a_i} you can get after applying such operation any number of times (possibly zero).InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^5) — the number of test cases. Description of the test cases follows.The first line of each test case contains two integers n and m (2\leq n \leq 10^6, 1 \leq m \leq \lfloor \frac{n}{2} \rfloor) — the number of elements of a and B respectively. The second line of each test case contains n integers a_1,a_2,\ldots,a_n (-10^9\leq a_i \leq 10^9). The third line of each test case contains m distinct positive integers b_1,b_2,\ldots,b_m (1 \leq b_i \leq \lfloor \frac{n}{2} \rfloor) — the elements in the set B.It's guaranteed that the sum of n over all test cases does not exceed 10^6.OutputFor each test case print a single integer — the maximum possible sum of all a_i after applying such operation any number of times. ExampleInput
36 20 6 -2 1 -4 51 27 11 -1 1 -1 1 -1 125 1-1000000000 -1000000000 -1000000000 -1000000000 -10000000001Output
18
5
5000000000
NoteIn the first test, you can apply the operation x=1, l=3, r=3, and the operation x=1, l=5, r=5, then the array becomes [0, 6, 2, 1, 4, 5].In the second test, you can apply the operation x=2, l=2, r=3, and the array becomes [1, 1, -1, -1, 1, -1, 1], then apply the operation x=2, l=3, r=4, and the array becomes [1, 1, 1, 1, 1, -1, 1]. There is no way to achieve a sum bigger than 5. | 36 20 6 -2 1 -4 51 27 11 -1 1 -1 1 -1 125 1-1000000000 -1000000000 -1000000000 -1000000000 -10000000001 | 18 5 5000000000 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dp', 'greedy', 'number theory', '*2400'] |
C. Paint the Middletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n elements numbered from 1 to n, the element i has value a_i and color c_i, initially, c_i = 0 for all i.The following operation can be applied: Select three elements i, j and k (1 \leq i < j < k \leq n), such that c_i, c_j and c_k are all equal to 0 and a_i = a_k, then set c_j = 1. Find the maximum value of \sum\limits_{i=1}^n{c_i} that can be obtained after applying the given operation any number of times.InputThe first line contains an integer n (3 \leq n \leq 2 \cdot 10^5) — the number of elements.The second line consists of n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq n), where a_i is the value of the i-th element.OutputPrint a single integer in a line — the maximum value of \sum\limits_{i=1}^n{c_i} that can be obtained after applying the given operation any number of times.ExamplesInput
7
1 2 1 2 7 4 7
Output
2
Input
13
1 2 3 2 1 3 3 4 5 5 5 4 7
Output
7
NoteIn the first test, it is possible to apply the following operations in order: | 7
1 2 1 2 7 4 7
| 2 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'sortings', 'two pointers', '*2200'] |
B. Range and Partitiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array a of n integers, find a range of values [x, y] (x \le y), and split a into exactly k (1 \le k \le n) subarrays in such a way that: Each subarray is formed by several continuous elements of a, that is, it is equal to a_l, a_{l+1}, \ldots, a_r for some l and r (1 \leq l \leq r \leq n). Each element from a belongs to exactly one subarray. In each subarray the number of elements inside the range [x, y] (inclusive) is strictly greater than the number of elements outside the range. An element with index i is inside the range [x, y] if and only if x \le a_i \le y. Print any solution that minimizes y - x.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 3 \cdot 10^4) — the number of test cases. 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 length of the array a and the number of subarrays required in the partition.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) where a_i is the i-th element of the array.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot10^5.OutputFor each test case, print k+1 lines.In the first line, print x and y — the limits of the found range.Then print k lines, the i-th should contain l_i and r_i (1\leq l_i \leq r_i \leq n) — the limits of the i-th subarray.You can print the subarrays in any order.ExampleInput
32 11 24 21 2 2 211 35 5 5 1 5 5 1 5 5 5 1Output
1 2
1 2
2 2
1 3
4 4
5 5
1 1
2 2
3 11
NoteIn the first test, there should be only one subarray, which must be equal to the whole array. There are 2 elements inside the range [1, 2] and 0 elements outside, if the chosen range is [1, 1], there will be 1 element inside (a_1) and 1 element outside (a_2), and the answer will be invalid.In the second test, it is possible to choose the range [2, 2], and split the array in subarrays (1, 3) and (4, 4), in subarray (1, 3) there are 2 elements inside the range (a_2 and a_3) and 1 element outside (a_1), in subarray (4, 4) there is only 1 element (a_4), and it is inside the range.In the third test, it is possible to choose the range [5, 5], and split the array in subarrays (1, 4), (5, 7) and (8, 11), in the subarray (1, 4) there are 3 elements inside the range and 1 element outside, in the subarray (5, 7) there are 2 elements inside and 1 element outside and in the subarray (8, 11) there are 3 elements inside and 1 element outside. | 32 11 24 21 2 2 211 35 5 5 1 5 5 1 5 5 5 1 | 1 2 1 2 2 2 1 3 4 4 5 5 1 1 2 2 3 11 | 2 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'data structures', 'greedy', 'two pointers', '*1800'] |
A. And Matchingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of n (n is always a power of 2) elements containing all integers 0, 1, 2, \ldots, n-1 exactly once.Find \frac{n}{2} pairs of elements such that: Each element in the set is in exactly one pair. The sum over all pairs of the bitwise AND of its elements must be exactly equal to k. Formally, if a_i and b_i are the elements of the i-th pair, then the following must hold: \sum_{i=1}^{n/2}{a_i \& b_i} = k, where \& denotes the bitwise AND operation. If there are many solutions, print any of them, if there is no solution, print -1 instead.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 400) — the number of test cases. Description of the test cases follows.Each test case consists of a single line with two integers n and k (4 \leq n \leq 2^{16}, n is a power of 2, 0 \leq k \leq n-1).The sum of n over all test cases does not exceed 2^{16}. All test cases in each individual input will be pairwise different.OutputFor each test case, if there is no solution, print a single line with the integer -1.Otherwise, print \frac{n}{2} lines, the i-th of them must contain a_i and b_i, the elements in the i-th pair. If there are many solutions, print any of them. Print the pairs and the elements in the pairs in any order.ExampleInput
44 04 14 24 3Output
0 3
1 2
0 2
1 3
0 1
2 3
-1
NoteIn the first test, (0\&3)+(1\&2) = 0.In the second test, (0\&2)+(1\&3) = 1.In the third test, (0\&1)+(2\&3) = 2.In the fourth test, there is no solution. | 44 04 14 24 3 | 0 3 1 2 0 2 1 3 0 1 2 3 -1 | 1 second | 256 megabytes | ['bitmasks', 'constructive algorithms', '*1500'] |
B. GCD Arraystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider the array a composed of all the integers in the range [l, r]. For example, if l = 3 and r = 7, then a = [3, 4, 5, 6, 7].Given l, r, and k, is it possible for \gcd(a) to be greater than 1 after doing the following operation at most k times? Choose 2 numbers from a. Permanently remove one occurrence of each of them from the array. Insert their product back into a. \gcd(b) denotes the greatest common divisor (GCD) of the integers in b.InputThe first line of the input contains a single integer t (1 \le t \le 10^5) — the number of test cases. The description of test cases follows.The input for each test case consists of a single line containing 3 non-negative integers l, r, and k (1 \leq l \leq r \leq 10^9, \enspace 0 \leq k \leq r - l).OutputFor each test case, print "YES" if it is possible to have the GCD of the corresponding array greater than 1 by performing at most k operations, and "NO" otherwise (case insensitive).ExampleInput
91 1 03 5 113 13 04 4 03 7 44 10 32 4 01 7 31 5 3Output
NO
NO
YES
YES
YES
YES
NO
NO
YES
NoteFor the first test case, a = [1], so the answer is "NO", since the only element in the array is 1.For the second test case the array is a = [3, 4, 5] and we have 1 operation. After the first operation the array can change to: [3, 20], [4, 15] or [5, 12] all of which having their greatest common divisor equal to 1 so the answer is "NO".For the third test case, a = [13], so the answer is "YES", since the only element in the array is 13.For the fourth test case, a = [4], so the answer is "YES", since the only element in the array is 4. | 91 1 03 5 113 13 04 4 03 7 44 10 32 4 01 7 31 5 3 | NO NO YES YES YES YES NO NO YES | 2 seconds | 256 megabytes | ['greedy', 'math', 'number theory', '*800'] |
A. Download More RAMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDid you know you can download more RAM? There is a shop with n different pieces of software that increase your RAM. The i-th RAM increasing software takes a_i GB of memory to run (temporarily, once the program is done running, you get the RAM back), and gives you an additional b_i GB of RAM (permanently). Each software can only be used once. Your PC currently has k GB of RAM.Note that you can't use a RAM-increasing software if it takes more GB of RAM to use than what you currently have.Since RAM is the most important thing in the world, you wonder, what is the maximum possible amount of RAM achievable?InputThe first line of the input contains a single integer t (1 \le t \le 100) — the number of test cases. The description of test cases follows.The first line of each test case contains the integers n and k (1 \le n \le 100, 1 \le k \le 1000). Then two lines follow, each containing n integers describing the arrays a and b (1 \le a_i, b_i \le 1000).OutputFor each test case, output a single line containing the largest amount of RAM you can achieve.ExampleInput
43 1020 30 109 100 105 11 1 5 1 11 1 1 1 15 12 2 2 2 2100 100 100 100 1005 8128 64 32 16 8128 64 32 16 8Output
29
6
1
256
NoteIn the first test case, you only have enough RAM to run the third software initially, but that increases your RAM to 20 GB, which allows you to use the first software, increasing your RAM to 29 GB. The only software left needs 30 GB of RAM, so you have to stop here.In the second test case, you can use the first, second, fourth and fifth software that need only 1 GB of RAM per software to run to increase your RAM to 5 GB, and then use the last remaining one to increase your RAM to 6 GB.In the third test case, all the software need more than 1 GB of RAM to run, so the amount of RAM you have stays at 1 GB. | 43 1020 30 109 100 105 11 1 5 1 11 1 1 1 15 12 2 2 2 2100 100 100 100 1005 8128 64 32 16 8128 64 32 16 8 | 29 6 1 256 | 1 second | 256 megabytes | ['brute force', 'greedy', 'sortings', '*800'] |
F. Spaceship Crisis Managementtime limit per test8 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNASA (Norwegian Astronaut Stuff Association) is developing a new steering system for spaceships. But in its current state, it wouldn't be very safe if the spaceship would end up in a bunch of space junk. To make the steering system safe, they need to answer the following:Given the target position t = (0, 0), a set of n pieces of space junk l described by line segments l_i = ((a_{ix}, a_{iy}), (b_{ix}, b_{iy})), and a starting position s = (s_x, s_y), is there a direction such that floating in that direction from the starting position would lead to the target position?When the spaceship hits a piece of space junk, what happens depends on the absolute difference in angle between the floating direction and the line segment, \theta: If \theta < 45^{\circ}, the spaceship slides along the piece of space junk in the direction that minimizes the change in angle, and when the spaceship slides off the end of the space junk, it continues floating in the direction it came in (before hitting the space junk). If \theta \ge 45^{\circ}, the spaceship stops, because there is too much friction to slide along the space junk. You are only given the set of pieces of space junk once, and the target position is always (0, 0), but there are q queries, each with a starting position s_j = (s_{jx}, s_{jy}).Answer the above question for each query.InputThe first line contains the the integer n (1 \le n \le 1500).Then follows n lines, the i-th of which containing the 4 integers a_{ix}, a_{iy}, b_{ix}, and b_{iy} (|a_{ix}|, |a_{iy}|, |b_{ix}|, |b_{iy}| \le 1000).Then follows a line containing the integer q (1 \le q \le 1000).Then follows q lines, the j-th of which containing the 2 integers s_{jx} and s_{jy} (|s_{jx}|, |s_{jy}| \le 1000).It is guaranteed that none of the segments in l cross or touch, that t is not on any segment in l, that s_j is not on any segment in l, and that s \neq t.OutputFor each query s_j print an answer. If there exists a direction such that floating from s_j in that direction, possibly sliding along some pieces of space junk, leads to t, print "YES". Otherwise, print "NO" (case insensitive).ExampleInput
3
0 1 2 4
1 3 -1 6
0 -1 1 -1
14
-2 10
-1 10
0 10
1 10
2 10
3 10
4 10
5 10
6 10
-1 -2
0 -2
1 -2
2 -2
3 -2
Output
YES
YES
YES
YES
YES
NO
NO
NO
YES
YES
NO
NO
NO
YES
NoteThe blue cross represents the target location, and the other blue line segments represent the space junk.Green dots represent starting locations where the answer is yes, and red dots represent starting locations where the answer is no.The yellow lines are possible paths to the target location for the 3rd and 14th queries. The black line is a possible path from the starting location in the 6th query, but it barely misses the target location. | 3
0 1 2 4
1 3 -1 6
0 -1 1 -1
14
-2 10
-1 10
0 10
1 10
2 10
3 10
4 10
5 10
6 10
-1 -2
0 -2
1 -2
2 -2
3 -2
| YES YES YES YES YES NO NO NO YES YES NO NO NO YES | 8 seconds | 256 megabytes | ['binary search', 'data structures', 'geometry', 'sortings', '*3500'] |
E. Groceries in Meteor Towntime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMihai lives in a town where meteor storms are a common problem. It's annoying, because Mihai has to buy groceries sometimes, and getting hit by meteors isn't fun. Therefore, we ask you to find the most dangerous way to buy groceries so that we can trick him to go there.The town has n buildings numbered from 1 to n. Some buildings have roads between them, and there is exactly 1 simple path from any building to any other building. Each road has a certain meteor danger level. The buildings all have grocery stores, but Mihai only cares about the open ones, of course. Initially, all the grocery stores are closed.You are given q queries of three types: Given the integers l and r, the buildings numbered from l to r open their grocery stores (nothing happens to buildings in the range that already have an open grocery store). Given the integers l and r, the buildings numbered from l to r close their grocery stores (nothing happens to buildings in the range that didn't have an open grocery store). Given the integer x, find the maximum meteor danger level on the simple path from x to any open grocery store, or -1 if there is no edge on any simple path to an open store. InputThe first line contains the two integers n and q (2 \le n, q \le 3\cdot 10^5).Then follows n - 1 lines, the i-th of which containing the integers u_i, v_i, and w_i (1 \le u_i, v_i \le n, \enspace 1 \le w_i \le 10^9) meaning there is two way road between building u_i and v_i with meteor danger level w_i.It is guaranteed that the given edges form a tree.Then follows q lines, the j-th of which begin with the integer t_j (1 \le t_j \le 3), meaning the j-th query is of the t_j-th type.If t_j is 1 or 2 the rest of the line contains the integers l_j and r_j (1 \le l_j \le r_j \le n).If t_j is 3 the rest of the line contains the integer x_j (1 \le x_j \le n).OutputFor each query of the 3rd type (t_j = 3), output the maximum meteor danger level that is on some edge on the simple path from x_j to some open store, or -1 if there is no such edge.ExampleInput
6 9
1 3 1
2 3 2
4 5 3
4 6 4
3 4 5
3 1
1 1 1
3 1
2 1 1
1 5 6
3 4
2 6 6
3 4
3 1
Output
-1
-1
4
3
5
NoteThis is an illustration of the town given in the sample input.In the first query, there are no open stores, so obviously there are no edges on the simple path from 1 to any open store, so the answer is -1.After the second and third queries, the set of open stores is \{1\}. The simple path from 1 to 1 has no edges, so the answer for the 3rd query is -1.After the fourth query, there are no open stores.After the fifth and sixth queries, the set of open stores is \{5, 6\}. In the sixth query, there are two paths from x_j = 4 to some open grocery store: 4 to 5 and 4 to 6. The biggest meteor danger is found on the edge from 4 to 6, so the answer for the 6th query is 4. This path is marked with red in the illustration.After the rest of the queries, the set of open stores is \{5\}. In the eighth query, the only path from x_j = 4 to an open store is from 4 to 5, and the maximum weight on that path is 3. This path is marked with green in the illustration.In the ninth query, the only path from x_j = 1 to an open store is from 1 to 5, and the maximum weight on that path is 5. This path is marked with blue in the illustration. | 6 9
1 3 1
2 3 2
4 5 3
4 6 4
3 4 5
3 1
1 1 1
3 1
2 1 1
1 5 6
3 4
2 6 6
3 4
3 1
| -1 -1 4 3 5 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dsu', 'trees', '*3100'] |
D2. Game on Sum (Hard Version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference is the constraints on n, m and t. You can make hacks only if all versions of the problem are solved.Alice and Bob are given the numbers n, m and k, and play a game as follows:The game has a score that Alice tries to maximize, and Bob tries to minimize. The score is initially 0. The game consists of n turns. Each turn, Alice picks a real number from 0 to k (inclusive) which Bob either adds to or subtracts from the score of the game. But throughout the game, Bob has to choose to add at least m out of the n turns.Bob gets to know which number Alice picked before deciding whether to add or subtract the number from the score, and Alice gets to know whether Bob added or subtracted the number for the previous turn before picking the number for the current turn (except on the first turn since there was no previous turn).If Alice and Bob play optimally, what will the final score of the game be?InputThe first line of the input contains a single integer t (1 \le t \le 10^5) — the number of test cases. The description of test cases follows.Each test case consists of a single line containing the three integers, n, m, and k (1 \le m \le n \le 10^6, 0 \le k < 10^9 + 7) — the number of turns, how many of those turns Bob has to add, and the biggest number Alice can choose, respectively.It is guaranteed that the sum of n over all test cases does not exceed 10^6.OutputFor each test case output a single integer number — the score of the optimal game 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}.ExampleInput
73 3 22 1 106 3 106 4 10100 1 14 4 069 4 20Output
6
5
375000012
500000026
958557139
0
49735962
NoteIn the first test case, the entire game has 3 turns, and since m = 3, Bob has to add in each of them. Therefore Alice should pick the biggest number she can, which is k = 2, every turn.In the third test case, Alice has a strategy to guarantee a score of \frac{75}{8} \equiv 375000012 \pmod{10^9 + 7}.In the fourth test case, Alice has a strategy to guarantee a score of \frac{45}{2} \equiv 500000026 \pmod{10^9 + 7}. | 73 3 22 1 106 3 106 4 10100 1 14 4 069 4 20 | 6 5 375000012 500000026 958557139 0 49735962 | 3 seconds | 256 megabytes | ['combinatorics', 'dp', 'games', 'math', '*2400'] |
D1. Game on Sum (Easy Version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference is the constraints on n, m and t. You can make hacks only if all versions of the problem are solved.Alice and Bob are given the numbers n, m and k, and play a game as follows:The game has a score that Alice tries to maximize, and Bob tries to minimize. The score is initially 0. The game consists of n turns. Each turn, Alice picks a real number from 0 to k (inclusive) which Bob either adds to or subtracts from the score of the game. But throughout the game, Bob has to choose to add at least m out of the n turns.Bob gets to know which number Alice picked before deciding whether to add or subtract the number from the score, and Alice gets to know whether Bob added or subtracted the number for the previous turn before picking the number for the current turn (except on the first turn since there was no previous turn).If Alice and Bob play optimally, what will the final score of the game be?InputThe first line of the input contains a single integer t (1 \le t \le 1000) — the number of test cases. The description of test cases follows.Each test case consists of a single line containing the three integers, n, m, and k (1 \le m \le n \le 2000, 0 \le k < 10^9 + 7) — the number of turns, how many of those turns Bob has to add, and the biggest number Alice can choose, respectively.It is guaranteed that the sum of n over all test cases does not exceed 2000.OutputFor each test case output a single integer number — the score of the optimal game 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}.ExampleInput
73 3 22 1 106 3 106 4 10100 1 14 4 069 4 20Output
6
5
375000012
500000026
958557139
0
49735962
NoteIn the first test case, the entire game has 3 turns, and since m = 3, Bob has to add in each of them. Therefore Alice should pick the biggest number she can, which is k = 2, every turn.In the third test case, Alice has a strategy to guarantee a score of \frac{75}{8} \equiv 375000012 \pmod{10^9 + 7}.In the fourth test case, Alice has a strategy to guarantee a score of \frac{45}{2} \equiv 500000026 \pmod{10^9 + 7}. | 73 3 22 1 106 3 106 4 10100 1 14 4 069 4 20 | 6 5 375000012 500000026 958557139 0 49735962 | 3 seconds | 256 megabytes | ['combinatorics', 'dp', 'games', 'math', '*2100'] |
C. Grid Xortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNote: The XOR-sum of set \{s_1,s_2,\ldots,s_m\} is defined as s_1 \oplus s_2 \oplus \ldots \oplus s_m, where \oplus denotes the bitwise XOR operation.After almost winning IOI, Victor bought himself an n\times n grid containing integers in each cell. n is an even integer. The integer in the cell in the i-th row and j-th column is a_{i,j}.Sadly, Mihai stole the grid from Victor and told him he would return it with only one condition: Victor has to tell Mihai the XOR-sum of all the integers in the whole grid.Victor doesn't remember all the elements of the grid, but he remembers some information about it: For each cell, Victor remembers the XOR-sum of all its neighboring cells.Two cells are considered neighbors if they share an edge — in other words, for some integers 1 \le i, j, k, l \le n, the cell in the i-th row and j-th column is a neighbor of the cell in the k-th row and l-th column if |i - k| = 1 and j = l, or if i = k and |j - l| = 1.To get his grid back, Victor is asking you for your help. Can you use the information Victor remembers to find the XOR-sum of the whole grid?It can be proven that the answer is unique.InputThe first line of the input contains a single integer t (1 \le t \le 100) — the number of test cases. The description of test cases follows.The first line of each test case contains a single even integer n (2 \leq n \leq 1000) — the size of the grid.Then follows n lines, each containing n integers. The j-th integer in the i-th of these lines represents the XOR-sum of the integers in all the neighbors of the cell in the i-th row and j-th column.It is guaranteed that the sum of n over all test cases doesn't exceed 1000 and in the original grid 0 \leq a_{i, j} \leq 2^{30} - 1.Hack FormatTo hack a solution, use the following format:The first line should contain a single integer t (1 \le t \le 100) — the number of test cases.The first line of each test case should contain a single even integer n (2 \leq n \leq 1000) — the size of the grid.Then n lines should follow, each containing n integers. The j-th integer in the i-th of these lines is a_{i,j} in Victor's original grid. The values in the grid should be integers in the range [0, 2^{30}-1]The sum of n over all test cases must not exceed 1000.OutputFor each test case, output a single integer — the XOR-sum of the whole grid.ExampleInput
3
2
1 5
5 1
4
1 14 8 9
3 1 5 9
4 13 11 1
1 15 4 11
4
2 4 1 6
3 7 3 10
15 9 4 2
12 7 15 1
Output
4
9
5
NoteFor the first test case, one possibility for Victor's original grid is:1324For the second test case, one possibility for Victor's original grid is:3885955155998429For the third test case, one possibility for Victor's original grid is:4321123456788991 | 3
2
1 5
5 1
4
1 14 8 9
3 1 5 9
4 13 11 1
1 15 4 11
4
2 4 1 6
3 7 3 10
15 9 4 2
12 7 15 1
| 4 9 5 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', 'interactive', 'math', '*2300'] |
B. Peculiar Movie Preferencestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMihai plans to watch a movie. He only likes palindromic movies, so he wants to skip some (possibly zero) scenes to make the remaining parts of the movie palindromic.You are given a list s of n non-empty strings of length at most 3, representing the scenes of Mihai's movie.A subsequence of s is called awesome if it is non-empty and the concatenation of the strings in the subsequence, in order, is a palindrome.Can you help Mihai check if there is at least one awesome subsequence of s?A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.A sequence a is a non-empty subsequence of a non-empty sequence b if a can be obtained from b by deletion of several (possibly zero, but not all) elements.InputThe first line of the input contains a single integer t (1 \le t \le 100) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the number of scenes in the movie.Then follows n lines, the i-th of which containing a single non-empty string s_i of length at most 3, consisting of lowercase Latin letters.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print "YES" if there is an awesome subsequence of s, or "NO" otherwise (case insensitive).ExampleInput
65zxabcczxba2abbad4codeforces3abc3abcdcba2ababOutput
YES
NO
NO
YES
YES
NO
NoteIn the first test case, an awesome subsequence of s is [ab, cc, ba] | 65zxabcczxba2abbad4codeforces3abc3abcdcba2abab | YES NO NO YES YES NO | 2 seconds | 512 megabytes | ['greedy', 'strings', '*1700'] |
A. Meximum Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMihai has just learned about the MEX concept and since he liked it so much, he decided to use it right away.Given an array a of n non-negative integers, Mihai wants to create a new array b that is formed in the following way:While a is not empty: Choose an integer k (1 \leq k \leq |a|). Append the MEX of the first k numbers of the array a to the end of array b and erase them from the array a, shifting the positions of the remaining numbers in a. But, since Mihai loves big arrays as much as the MEX concept, he wants the new array b to be the lexicographically maximum. So, Mihai asks you to tell him what the maximum array b that can be created by constructing the array optimally is.An array x is lexicographically greater than an array y if in the first position where x and y differ x_i > y_i or if |x| > |y| and y is a prefix of x (where |x| denotes the size of the array x).The MEX of a set of non-negative integers is the minimal non-negative integer such that it is not in the set. For example, MEX({{1, 2, 3}}) = 0 and MEX({{0, 1, 2, 4, 5}}) = 3.InputThe first line of the input contains a single integer t (1 \le t \le 100) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the number of elements in the array a.The second line of each test case contains n non-negative integers a_1, \ldots, a_n (0 \leq a_i \leq n), where a_i is the i-th integer from 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 m — the length of the maximum array b Mihai can create, followed by m integers denoting the elements of the array b.ExampleInput
651 0 2 0 382 2 3 4 0 1 2 01150 1 2 3 440 1 1 0100 0 2 1 1 1 0 0 1 1Output
1
4
2
5 1
1
0
1
5
2
2 2
4
3 2 2 0
NoteIn the first test case, the lexicographically maximum array b is obtained by selecting k=5, resulting in the MEX of the whole array a. It is lexicographically maximum because an array starting with a smaller number than 4 is lexicographically smaller, and choosing a k<5 would result in an array starting with a number smaller than 4.In the second test case, there are two ways to obtain the maximum array: first selecting k=6, then k=2, or first selecting k=7 and then k=1. | 651 0 2 0 382 2 3 4 0 1 2 01150 1 2 3 440 1 1 0100 0 2 1 1 1 0 0 1 1 | 1 4 2 5 1 1 0 1 5 2 2 2 4 3 2 2 0 | 2 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'greedy', 'implementation', 'math', 'two pointers', '*1400'] |
F. Not Splittingtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is a k \times k grid, where k is even. The square in row r and column c is denoted by (r,c). Two squares (r_1, c_1) and (r_2, c_2) are considered adjacent if \lvert r_1 - r_2 \rvert + \lvert c_1 - c_2 \rvert = 1.An array of adjacent pairs of squares is called strong if it is possible to cut the grid along grid lines into two connected, congruent pieces so that each pair is part of the same piece. Two pieces are congruent if one can be matched with the other by translation, rotation, and reflection, or a combination of these. The picture above represents the first test case. Arrows indicate pairs of squares, and the thick black line represents the cut. You are given an array a of n pairs of adjacent squares. Find the size of the largest strong subsequence of a. An array p is a subsequence of an array q if p can be obtained from q by deletion of several (possibly, zero or all) elements.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains two space-separated integers n and k (1 \leq n \leq 10^5; 2 \leq k \leq 500, k is even) — the length of a and the size of the grid, respectively.Then n lines follow. The i-th of these lines contains four space-separated integers r_{i,1}, c_{i,1}, r_{i,2}, and c_{i,2} (1 \leq r_{i,1}, c_{i,1}, r_{i,2}, c_{i,2} \leq k) — the i-th element of a, represented by the row and column of the first square (r_{i,1}, c_{i,1}) and the row and column of the second square (r_{i,2}, c_{i,2}). These squares are adjacent.It is guaranteed that the sum of n over all test cases does not exceed 10^5, and the sum of k over all test cases does not exceed 500.OutputFor each test case, output a single integer — the size of the largest strong subsequence of a.ExampleInput
38 41 2 1 32 2 2 33 2 3 34 2 4 31 4 2 42 1 3 12 2 3 24 1 4 27 21 1 1 22 1 2 21 1 1 21 1 2 11 2 2 21 1 2 11 2 2 21 63 3 3 4Output
7
4
1
NoteIn the first test case, the array a is not good, but if we take the subsequence [a_1, a_2, a_3, a_4, a_5, a_6, a_8], then the square can be split as shown in the statement.In the second test case, we can take the subsequence consisting of the last four elements of a and cut the square with a horizontal line through its center. | 38 41 2 1 32 2 2 33 2 3 34 2 4 31 4 2 42 1 3 12 2 3 24 1 4 27 21 1 1 22 1 2 21 1 1 21 1 2 11 2 2 21 1 2 11 2 2 21 63 3 3 4 | 7 4 1 | 3 seconds | 512 megabytes | ['geometry', 'graphs', 'greedy', 'implementation', 'shortest paths', '*2700'] |
E. Not Escapingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMajor Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of n floors, each with m rooms each. Let (i, j) represent the j-th room on the i-th floor. Additionally, there are k ladders installed. The i-th ladder allows Ram to travel from (a_i, b_i) to (c_i, d_i), but not in the other direction. Ram also gains h_i health points if he uses the ladder i. It is guaranteed a_i < c_i for all ladders.If Ram is on the i-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from (i, j) to (i, k), he loses |j-k| \cdot x_i health points.Ram enters the building at (1, 1) while his helicopter is waiting at (n, m). What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav. InputThe first line of input contains t (1 \leq t \leq 5 \cdot 10^4) — the number of test cases.The first line of each test case consists of 3 integers n, m, k (2 \leq n, m \leq 10^5; 1 \leq k \leq 10^5) — the number of floors, the number of rooms on each floor and the number of ladders respectively.The second line of a test case consists of n integers x_1, x_2, \dots, x_n (1 \leq x_i \leq 10^6).The next k lines describe the ladders. Ladder i is denoted by a_i, b_i, c_i, d_i, h_i (1 \leq a_i < c_i \leq n; 1 \leq b_i, d_i \leq m; 1 \leq h_i \leq 10^6) — the rooms it connects and the health points gained from using it.It is guaranteed a_i < c_i for all ladders and there is at most one ladder between any 2 rooms in the building.The sum of n, the sum of m, and the sum of k over all test cases do not exceed 10^5.OutputOutput the minimum health Ram loses on the optimal path from (1, 1) to (n, m). If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).ExampleInput
45 3 35 17 8 1 41 3 3 3 43 1 5 2 53 2 5 1 66 3 35 17 8 1 4 21 3 3 3 43 1 5 2 53 2 5 1 65 3 15 17 8 1 41 3 5 3 1005 5 53 2 3 7 53 5 4 2 12 2 5 4 54 4 5 2 31 2 4 2 23 3 5 2 4Output
16
NO ESCAPE
-90
27
NoteThe figure for the first test case is in the statement. There are only 2 possible paths to (n, m): Ram travels to (1, 3), takes the ladder to (3, 3), travels to (3, 2), takes the ladder to (5, 1), travels to (5, 3) where he finally escapes via helicopter. The health lost would be \begin{align*} &\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &= 16. \end{align*} Ram travels to (1, 3), takes the ladder to (3, 3), travels to (3, 1), takes the ladder to (5, 2), travels to (5, 3) where he finally escapes via helicopter. The health lost would be \begin{align*} &\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &= 21. \end{align*} Therefore, the minimum health lost would be 16.In the second test case, there is no path to (n, m).In the third case case, Ram travels to (1, 3) and takes the only ladder to (5, 3). He loses 5 \cdot 2 health points and gains h_1 = 100 health points. Therefore the total loss is 10-100=-90 (negative implies he gains health after the path). | 45 3 35 17 8 1 41 3 3 3 43 1 5 2 53 2 5 1 66 3 35 17 8 1 4 21 3 3 3 43 1 5 2 53 2 5 1 65 3 15 17 8 1 41 3 5 3 1005 5 53 2 3 7 53 5 4 2 12 2 5 4 54 4 5 2 31 2 4 2 23 3 5 2 4 | 16 NO ESCAPE -90 27 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'implementation', 'shortest paths', 'two pointers', '*2200'] |
D. Not Addingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a_1, a_2, \dots, a_n consisting of n distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array a_i and a_j (i \ne j) such that \gcd(a_i, a_j) is not present in the array, and add \gcd(a_i, a_j) to the end of the array. Here \gcd(x, y) denotes greatest common divisor (GCD) of integers x and y. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?InputThe first line consists of a single integer n (2 \le n \le 10^6).The second line consists of n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^6). All a_i are distinct.OutputOutput a single line containing one integer — the maximum number of times the operation can be performed on the given array.ExamplesInput
5
4 20 1 25 30
Output
3Input
3
6 10 15
Output
4NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick i = 1, j= 5 and add \gcd(a_1, a_5) = \gcd(4, 30) = 2 to the array. Pick i = 2, j= 4 and add \gcd(a_2, a_4) = \gcd(20, 25) = 5 to the array. Pick i = 2, j= 5 and add \gcd(a_2, a_5) = \gcd(20, 30) = 10 to the array. It can be proved that there is no way to perform more than 3 operations on the original array.In the second example one can add 3, then 1, then 5, and 2. | 5
4 20 1 25 30
| 3 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'math', 'number theory', '*1900'] |
C. Not Assigningtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree of n vertices numbered from 1 to n, with edges numbered from 1 to n-1. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: 2 \to 1 \to 3 has a weight of 11 + 2 = 13, which is prime. Similarly, the path of one edge: 4 \to 3 has a weight of 5, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print -1. It can be proven that if a valid assignment exists, one exists with weights between 1 and 10^5 as well.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer n (2 \leq n \leq 10^5) — the number of vertices in the tree.Then, n-1 lines follow. The i-th line contains two integers u and v (1 \leq u, v \leq n) denoting that edge number i is between vertices u and v. It is guaranteed that the edges form a tree.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, if a valid assignment exists, then print a single line containing n-1 integers a_1, a_2, \dots, a_{n-1} (1 \leq a_i \le 10^5), where a_i denotes the weight assigned to the edge numbered i. Otherwise, print -1.If there are multiple solutions, you may print any.ExampleInput
321 241 34 32 171 21 33 43 56 27 2Output
17
2 5 11
-1NoteFor the first test case, there are only two paths having one edge each: 1 \to 2 and 2 \to 1, both having a weight of 17, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case. | 321 241 34 32 171 21 33 43 56 27 2 | 17 2 5 11 -1 | 1.5 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'number theory', 'trees', '*1400'] |
B. Not Sittingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRahul and Tina are looking forward to starting their new year at college. As they enter their new classroom, they observe the seats of students are arranged in a n \times m grid. The seat in row r and column c is denoted by (r, c), and the distance between two seats (a,b) and (c,d) is |a-c| + |b-d|. As the class president, Tina has access to exactly k buckets of pink paint. The following process occurs. First, Tina chooses exactly k seats in the classroom to paint with pink paint. One bucket of paint can paint exactly one seat. After Tina has painted k seats in the previous step, Rahul chooses where he sits. He will not choose a seat that has been painted pink due to his hatred of the colour pink. After Rahul has chosen his seat, Tina chooses a seat for herself. She can choose any of the seats, painted or not, other than the one chosen by Rahul. Rahul wants to choose a seat such that he sits as close to Tina as possible. However, Tina wants to sit as far away from Rahul as possible due to some complicated relationship history that we couldn't fit into the statement!Now, Rahul wonders for k = 0, 1, \dots, n \cdot m - 1, if Tina has k buckets of paint, how close can Rahul sit to Tina, if both Rahul and Tina are aware of each other's intentions and they both act as strategically as possible? Please help satisfy Rahul's curiosity! InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 5 \cdot 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n, m (2 \leq n \cdot m \leq 10^5) — the number of rows and columns of seats in the classroom.The sum of n \cdot m across all test cases does not exceed 10^5.OutputFor each test case, output n \cdot m ordered integers — the distance between Rahul and Tina if both of them act optimally for every k \in [0, n \cdot m - 1].ExampleInput
24 31 2Output
3 3 4 4 4 4 4 4 5 5 5 5
1 1
NoteOne possible sequence of choices for the first testcase where Tina has k=3 buckets of paints is as follows.Tina paints the seats at positions (1, 2), (2, 2), (3, 2) with pink paint. Rahul chooses the seat at (3, 1) after which Tina chooses to sit at (1, 3). Therefore, the distance between Tina and Rahul is |3-1| + |1-3| = 4, and we can prove that this is indeed the minimum possible distance under the given constraints. There may be other choices of seats which lead to the same answer as well.For k=0 in the first test case, Rahul can decide to sit at (2, 2) and Tina can decide to sit at (4, 3) so the distance between them would be |2 - 4| + |2 - 3| = 3.Below are pictorial representations of the k=3 and k=0 cases for the first test case. A possible seating arrangement for k=3. A possible seating arrangement for k=0. | 24 31 2 | 3 3 4 4 4 4 4 4 5 5 5 5 1 1 | 1 second | 256 megabytes | ['games', 'greedy', 'sortings', '*1300'] |
A. Not Shadingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a grid with n rows and m columns. Some cells are colored black, and the rest of the cells are colored white.In one operation, you can select some black cell and do exactly one of the following: color all cells in its row black, or color all cells in its column black. You are given two integers r and c. Find the minimum number of operations required to make the cell in row r and column c black, or determine that it is impossible.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains four integers n, m, r, and c (1 \leq n, m \leq 50; 1 \leq r \leq n; 1 \leq c \leq m) — the number of rows and the number of columns in the grid, and the row and column of the cell you need to turn black, respectively.Then n lines follow, each containing m characters. Each of these characters is either 'B' or 'W' — a black and a white cell, respectively.OutputFor each test case, if it is impossible to make the cell in row r and column c black, output -1. Otherwise, output a single integer — the minimum number of operations required to make the cell in row r and column c black. ExampleInput
93 5 1 4WBWWWBBBWBWWBBB4 3 2 1BWWBBWWBBWWB2 3 2 2WWWWWW2 2 1 1WWWB5 9 5 9WWWWWWWWWWBWBWBBBWWBBBWWBWWWBWBWBBBWWWWWWWWWW1 1 1 1B1 1 1 1W1 2 1 1WB2 1 1 1WBOutput
1
0
-1
2
2
0
-1
1
1
NoteThe first test case is pictured below. We can take the black cell in row 1 and column 2, and make all cells in its row black. Therefore, the cell in row 1 and column 4 will become black. In the second test case, the cell in row 2 and column 1 is already black.In the third test case, it is impossible to make the cell in row 2 and column 2 black.The fourth test case is pictured below. We can take the black cell in row 2 and column 2 and make its column black. Then, we can take the black cell in row 1 and column 2 and make its row black. Therefore, the cell in row 1 and column 1 will become black. | 93 5 1 4WBWWWBBBWBWWBBB4 3 2 1BWWBBWWBBWWB2 3 2 2WWWWWW2 2 1 1WWWB5 9 5 9WWWWWWWWWWBWBWBBBWWBBBWWBWWWBWBWBBBWWWWWWWWWW1 1 1 1B1 1 1 1W1 2 1 1WB2 1 1 1WB | 1 0 -1 2 2 0 -1 1 1 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*800'] |
F. A Random Code Problemtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an integer array a_0, a_1, \dots, a_{n - 1}, and an integer k. You perform the following code with it:long long ans = 0; // create a 64-bit signed variable which is initially equal to 0for(int i = 1; i <= k; i++){ int idx = rnd.next(0, n - 1); // generate a random integer between 0 and n - 1, both inclusive // each integer from 0 to n - 1 has the same probability of being chosen ans += a[idx]; a[idx] -= (a[idx] % i);}Your task is to calculate the expected value of the variable ans after performing this code.Note that the input is generated according to special rules (see the input format section).InputThe only line contains six integers n, a_0, x, y, k and M (1 \le n \le 10^7; 1 \le a_0, x, y < M \le 998244353; 1 \le k \le 17).The array a in the input is constructed as follows: a_0 is given in the input; for every i from 1 to n - 1, the value of a_i can be calculated as a_i = (a_{i - 1} \cdot x + y) \bmod M. OutputLet the expected value of the variable ans after performing the code be E. It can be shown that E \cdot n^k is an integer. You have to output this integer modulo 998244353.ExamplesInput
3 10 3 5 13 88
Output
382842030
Input
2 15363 270880 34698 17 2357023
Output
319392398
NoteThe array in the first example test is [10, 35, 22]. In the second example, it is [15363, 1418543]. | 3 10 3 5 13 88
| 382842030 | 3 seconds | 512 megabytes | ['combinatorics', 'dp', 'math', 'number theory', 'probabilities', '*2800'] |
E. Black and White Treetime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices. Some of the vertices (at least two) are black, all the other vertices are white.You place a chip on one of the vertices of the tree, and then perform the following operations: let the current vertex where the chip is located is x. You choose a black vertex y, and then move the chip along the first edge on the simple path from x to y. You are not allowed to choose the same black vertex y in two operations in a row (i. e., for every two consecutive operations, the chosen black vertex should be different).You end your operations when the chip moves to the black vertex (if it is initially placed in a black vertex, you don't perform the operations at all), or when the number of performed operations exceeds 100^{500}.For every vertex i, you have to determine if there exists a (possibly empty) sequence of operations that moves the chip to some black vertex, if the chip is initially placed on the vertex i.InputThe first line contains one integer n (3 \le n \le 3 \cdot 10^5) — the number of vertices in the tree.The second line contains n integers c_1, c_2, \dots, c_n (0 \le c_i \le 1), where c_i = 0 means that the i-th vertex is white, and c_i = 1 means that the i-th vertex is black. At least two values of c_i are equal to 1.Then n-1 lines follow, each of them contains two integers u_i and v_i (1 \le u_i, v_i \le n; u_i \ne v_i) — the endpoints of some edge. These edges form a tree.OutputPrint n integers. The i-th integer should be equal to 1 if there exists a (possibly empty) sequence of operations that moves the chip to some black vertex if it is placed on the vertex i, and 0 if no such sequence of operations exists.ExampleInput
8
0 1 0 0 0 0 1 0
8 6
2 5
7 8
6 5
4 5
6 1
7 3
Output
0 1 1 1 1 0 1 1
| 8
0 1 0 0 0 0 1 0
8 6
2 5
7 8
6 5
4 5
6 1
7 3
| 0 1 1 1 1 0 1 1 | 4 seconds | 512 megabytes | ['dfs and similar', 'greedy', 'trees', '*2400'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.