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
|
---|---|---|---|---|---|
G. Robot and Candiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has a rectangular field of n \times m cells (the size of the n \cdot m field does not exceed 10^6 cells, m \ge 2), in each cell of which there can be candy. There are n rows and m columns in the field.Let's denote a cell with coordinates x vertically and y horizontally by (x, y). Then the top-left cell will be denoted as (1, 1), and the bottom-right cell will be denoted as (n, m).If there is candy in the cell, then the cell is marked with the symbol '1', otherwise — with the symbol '0'.Polycarp made a Robot that can collect candy. The Robot can move from (x, y) either to (x+1, y+1), or to (x+1, y-1). If the Robot is in a cell that contains candy, it takes it.While there is at least one candy on the field, the following procedure is executed: Polycarp puts the Robot in an arbitrary cell on the topmost row of the field. He himself chooses in which cell to place the Robot. It is allowed to put the Robot in the same cell multiple times. The Robot moves across the field and collects candies. He controls the Robot. When the Robot leaves the field, Polycarp takes it. If there are still candies left, Polycarp repeats the procedure. Find the minimum number of times Polycarp needs to put the Robot on the topmost row of the field in order to collect all the candies. It is guaranteed that Polycarp can always collect all the candies.InputThe first line of input data contains an integer t (1 \le t \le 10^4) — the number of input data sets in the test.Before each input data, there is a blank line in the test. Next is a line that contains integers n and m (2 \le m, 2 \le n \cdot m \le 10^6) — field sizes. This is followed by n lines, i-th of which describes the i-th line of the field. Each of them is a string of size m characters: the symbol '1' corresponds to a cell with candy, the symbol '0' — an empty cell.It is guaranteed that the sum of n \cdot m values for all input data sets in the test does not exceed 10^6.OutputPrint t lines, each line should contain the answer to the corresponding set of input data: the minimum number of times Polycarpus needs to put the Robot on the topmost row of the field in order to collect all the candies.ExampleInput
4
2 2
00
00
3 3
100
000
101
4 5
01000
00001
00010
10000
3 3
111
111
111
Output
0
2
2
4
NoteIn the first set Polycarp may not put the Robot on the field at all, so the answer "0"In the second set, Polycarp will need to place the robot on the field twice. The Robot can collect candies like this: for the first time Polycarp puts the Robot in the cell (1, 1) and collects candies at the positions (1, 1) and (3, 3). The second time Polycarp can again put the Robot in (1, 1), and then the Robot will move first to (2,2), then to (3, 1) and collect the last candy.In the fourth set, you can show that the Robot cannot collect all the candies in three passes. | 4
2 2
00
00
3 3
100
000
101
4 5
01000
00001
00010
10000
3 3
111
111
111
| 0 2 2 4 | 2 seconds | 256 megabytes | ['data structures', 'graph matchings', 'greedy', '*2500'] |
F. ATM and Studentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp started working at a bank. He was assigned to monitor the ATM. The ATM initially contains s rubles.A queue of n students lined up to him. Each student wants to either withdraw a certain amount of money or deposit it into an account. If a_i is positive, then the student credits that amount of money via ATM. Otherwise, the student withdraws |a_i| rubles.In the beginning, the ATM is turned off and an arbitrary number of students are not served. At some point, Polycarp turns on the ATM, which has an initial amount of s rubles. Then, the remaining students start queueing at the ATM. If at some point in time there is less money in the ATM than the student wants to withdraw, then the student is not served and Polycarp turns off the ATM and does not turn it on anymore.More formally, the students that are served are forming a contiguous subsequence.Polycarp wants the ATM to serve the maximum number of students. Help him in this matter. Print the numbers of the first and last student, or determine that he will not be able to serve anyone.In other words, find such a longest continuous segment of students that, starting with the sum of s at the ATM, all these students will be served. ATM serves students consistently (i.e. one after another in the order of the queue).InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of two lines. The first one contains integers n and s (1 \le n \le 2\cdot10^5; 0 \le s \le 10^9) — the length of the a array and the initial amount of rubles in the ATM. The second contains n integers a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9) — elements of the a array. Note that a_i can be zero.It is guaranteed that the sum of the values n over all test cases does not exceed 2\cdot10^5.OutputPrint t lines, each line must contain the answer to the corresponding set of input data: if the answer exists, print the numbers of the first and last served student. If there is no solution, then print -1 on the line.If there are several possible answers, print any.ExampleInput
3
4 10
-16 2 -6 8
3 1000
-100000 -100000 -100000
6 0
2 6 -164 1 -1 -6543
Output
2 4
-1
1 2
NoteIn the first test case, the only correct answer is 2 4, since when serving students, the number of rubles at the ATM does not become negative, and this is the maximum number of students that can be served.In the second test case, the answer is -1, as there is not enough money for any student at the ATM.In the third test case, the answer can be either 1 2 or 4 5. | 3
4 10
-16 2 -6 8
3 1000
-100000 -100000 -100000
6 0
2 6 -164 1 -1 -6543
| 2 4 -1 1 2 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'two pointers', '*1800'] |
E2. Escape The Maze (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference with E1 is the question of the problem.Vlad built a maze out of n rooms and n-1 bidirectional corridors. From any room u any other room v can be reached through a sequence of corridors. Thus, the room system forms an undirected tree.Vlad invited k friends to play a game with them.Vlad starts the game in the room 1 and wins if he reaches a room other than 1, into which exactly one corridor leads. Friends are placed in the maze: the friend with number i is in the room x_i, and no two friends are in the same room (that is, x_i \neq x_j for all i \neq j). Friends win if one of them meets Vlad in any room or corridor before he wins.For one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time.Friends know the plan of a maze and intend to win. They don't want to waste too much energy. They ask you to determine if they can win and if they can, what minimum number of friends must remain in the maze so that they can always catch Vlad.In other words, you need to determine the size of the minimum (by the number of elements) subset of friends who can catch Vlad or say that such a subset does not exist.InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases in the input. The input contains an empty string before each test case.The first line of the test case contains two numbers n and k (1 \le k < n \le 2\cdot 10^5) — the number of rooms and friends, respectively.The next line of the test case contains k integers x_1, x_2, \dots, x_k (2 \le x_i \le n) — numbers of rooms with friends. All x_i are different.The next n-1 lines contain descriptions of the corridors, two numbers per line v_j and u_j (1 \le u_j, v_j \le n) — numbers of rooms that connect the j corridor. All corridors are bidirectional. From any room, you can go to any other by moving along the corridors.It is guaranteed that the sum of the values n over all test cases in the test is not greater than 2\cdot10^5.OutputPrint t lines, each line containing the answer to the corresponding test case. The answer to a test case should be -1 if Vlad wins anyway and a minimal number of friends otherwise.ExampleInput
4
8 2
5 3
4 7
2 5
1 6
3 6
7 2
1 7
6 8
8 4
6 5 7 3
4 7
2 5
1 6
3 6
7 2
1 7
6 8
3 1
2
1 2
2 3
3 2
2 3
3 1
1 2
Output
-1
2
1
2
NoteIn the first set of inputs, even if all the friends stay in the maze, Vlad can still win. Therefore, the answer is "-1".In the second set of inputs it is enough to leave friends from rooms 6 and 7. Then Vlad will not be able to win. The answer is "2".In the third and fourth sets of inputs Vlad cannot win only if all his friends stay in the maze. Therefore the answers are "1" and "2". | 4
8 2
5 3
4 7
2 5
1 6
3 6
7 2
1 7
6 8
8 4
6 5 7 3
4 7
2 5
1 6
3 6
7 2
1 7
6 8
3 1
2
1 2
2 3
3 2
2 3
3 1
1 2
| -1 2 1 2 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'greedy', 'shortest paths', 'trees', '*1900'] |
E1. Escape The Maze (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference with E2 is the question of the problem..Vlad built a maze out of n rooms and n-1 bidirectional corridors. From any room u any other room v can be reached through a sequence of corridors. Thus, the room system forms an undirected tree.Vlad invited k friends to play a game with them.Vlad starts the game in the room 1 and wins if he reaches a room other than 1, into which exactly one corridor leads.Friends are placed in the maze: the friend with number i is in the room x_i, and no two friends are in the same room (that is, x_i \neq x_j for all i \neq j). Friends win if one of them meets Vlad in any room or corridor before he wins.For one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time. Friends know the plan of a maze and intend to win. Vlad is a bit afraid of their ardor. Determine if he can guarantee victory (i.e. can he win in any way friends play).In other words, determine if there is such a sequence of Vlad's moves that lets Vlad win in any way friends play.InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases in the input. The input contains an empty string before each test case.The first line of the test case contains two numbers n and k (1 \le k < n \le 2\cdot 10^5) — the number of rooms and friends, respectively.The next line of the test case contains k integers x_1, x_2, \dots, x_k (2 \le x_i \le n) — numbers of rooms with friends. All x_i are different.The next n-1 lines contain descriptions of the corridors, two numbers per line v_j and u_j (1 \le u_j, v_j \le n) — numbers of rooms that connect the j corridor. All corridors are bidirectional. From any room, you can go to any other by moving along the corridors.It is guaranteed that the sum of the values n over all test cases in the test is not greater than 2\cdot10^5.OutputPrint t lines, each line containing the answer to the corresponding test case. The answer to a test case should be "YES" if Vlad can guarantee himself a victory and "NO" otherwise.You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes" and "YES" will all be recognized as positive answers).ExampleInput
4
8 2
5 3
4 7
2 5
1 6
3 6
7 2
1 7
6 8
3 1
2
1 2
2 3
3 1
2
1 2
1 3
3 2
2 3
3 1
1 2
Output
YES
NO
YES
NO
NoteIn the first test case, regardless of the strategy of his friends, Vlad can win by going to room 4. The game may look like this: The original locations of Vlad and friends. Vlad is marked in green, friends — in red. Locations after one unit of time. End of the game. Note that if Vlad tries to reach the exit at the room 8, then a friend from the 3 room will be able to catch him. | 4
8 2
5 3
4 7
2 5
1 6
3 6
7 2
1 7
6 8
3 1
2
1 2
2 3
3 1
2
1 2
1 3
3 2
2 3
3 1
1 2
| YES NO YES NO | 2 seconds | 256 megabytes | ['dfs and similar', 'greedy', 'shortest paths', 'trees', 'two pointers', '*1700'] |
D. Weights Assignment For Tree Edgestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree consisting of n vertices. Vertices are numbered from 1 to n. Any vertex can be the root of a tree.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.The tree is specified by an array of ancestors b containing n numbers: b_i is an ancestor of the vertex with the number i. The ancestor of a vertex u is a vertex that is the next vertex on a simple path from u to the root. For example, on the simple path from 5 to 3 (the root), the next vertex would be 1, so the ancestor of 5 is 1.The root has no ancestor, so for it, the value of b_i is i (the root is the only vertex for which b_i=i).For example, if n=5 and b=[3, 1, 3, 3, 1], then the tree looks like this. An example of a rooted tree for n=5, the root of the tree is a vertex number 3. You are given an array p — a permutation of the vertices of the tree. If it is possible, assign any positive integer weights on the edges, so that the vertices sorted by distance from the root would form the given permutation p.In other words, for a given permutation of vertices p, it is necessary to choose such edge weights so that the condition dist[p_i]<dist[p_{i+1}] is true for each i from 1 to n-1. dist[u] is a sum of the weights of the edges on the path from the root to u. In particular, dist[u]=0 if the vertex u is the root of the tree.For example, assume that p=[3, 1, 2, 5, 4]. In this case, the following edge weights satisfy this permutation: the edge (3, 4) has a weight of 102; the edge (3, 1) has weight of 1; the edge (1, 2) has a weight of 10; the edge (1, 5) has a weight of 100. The array of distances from the root looks like: dist=[1,11,0,102,101]. The vertices sorted by increasing the distance from the root form the given permutation p.Print the required edge weights or determine that there is no suitable way to assign weights. If there are several solutions, then print any of them.InputThe first line of input data contains an integer t (1 \le t \le 10^4) — the number of input data sets in the test.Each test case consists of three lines.The first of them contains an integer n (1 \le n \le 2 \cdot 10^5). It is the number of vertices in the tree.The second line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le n). It is guaranteed that the b array encodes some rooted tree.The third line contains the given permutation p: n of different integers p_1, p_2, \dots, p_n (1 \le p_i \le n).It is guaranteed that the sum of the values n over all test cases in the test does not exceed 2 \cdot 10^5.OutputFor each set of input data print the answer on a separate line.If the solution exists, print an array of n integers w_1, w_2, \dots, w_n, where w_i is the weight of the edge that leads from b_i to i. For the root there is no such edge, so use the value w_i=0. For all other vertices, the values of w_i must satisfy the inequality 1 \le w_i \le 10^9. There can be equal numbers among w_i values, but all sums of weights of edges from the root to vertices must be different and satisfy the given permutation.If there are several solutions, output any of them.If no solution exists, output -1.ExampleInput
4
5
3 1 3 3 1
3 1 2 5 4
3
1 1 2
3 1 2
7
1 1 2 3 4 5 6
1 2 3 4 5 6 7
6
4 4 4 4 1 1
4 2 1 5 6 3
Output
1 10 0 102 100
-1
0 3 100 1 1 2 4
6 5 10 0 2 3NoteThe first set of input data of the example is analyzed in the main part of the statement.In the second set of input data of the example, it is impossible to assign the positive weights to obtain a given permutation of vertices. | 4
5
3 1 3 3 1
3 1 2 5 4
3
1 1 2
3 1 2
7
1 1 2 3 4 5 6
1 2 3 4 5 6 7
6
4 4 4 4 1 1
4 2 1 5 6 3
| 1 10 0 102 100 -1 0 3 100 1 1 2 4 6 5 10 0 2 3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'trees', '*1500'] |
C. Polycarp Recovers the Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wrote on a whiteboard an array p of length n, which is a permutation of numbers from 1 to n. In other words, in p each number from 1 to n occurs exactly once.He also prepared a resulting array a, which is initially empty (that is, it has a length of 0).After that, he did exactly n steps. Each step looked like this: Look at the leftmost and rightmost elements of p, and pick the smaller of the two. If you picked the leftmost element of p, append it to the left of a; otherwise, if you picked the rightmost element of p, append it to the right of a. The picked element is erased from p. Note that on the last step, p has a length of 1 and its minimum element is both leftmost and rightmost. In this case, Polycarp can choose what role the minimum element plays. In other words, this element can be added to a both on the left and on the right (at the discretion of Polycarp).Let's look at an example. Let n=4, p=[3, 1, 4, 2]. Initially a=[]. Then: During the first step, the minimum is on the right (with a value of 2), so after this step, p=[3,1,4] and a=[2] (he added the value 2 to the right). During the second step, the minimum is on the left (with a value of 3), so after this step, p=[1,4] and a=[3,2] (he added the value 3 to the left). During the third step, the minimum is on the left (with a value of 1), so after this step, p=[4] and a=[1,3,2] (he added the value 1 to the left). During the fourth step, the minimum is both left and right (this value is 4). Let's say Polycarp chose the right option. After this step, p=[] and a=[1,3,2,4] (he added the value 4 to the right).Thus, a possible value of a after n steps could be a=[1,3,2,4].You are given the final value of the resulting array a. Find any possible initial value for p that can result the given a, or determine that there is no solution.InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases in the test.Each test case consists of two lines. The first of them contains an integer n (1 \le n \le 2\cdot10^5) — the length of the array a. The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — the elements of the array a. All elements of the a array are distinct numbers.It is guaranteed that the sum of the values n over all test cases in the test does not exceed 2\cdot10^5.OutputPrint t lines, each of the lines must contain the answer to the corresponding set of input data: numbers p_1, p_2, \dots, p_n — any of the possible initial values of the array p, which will lead to the given array a. All elements of p are distinct integers from 1 to n. Thus, if there are several solutions, print any. If there is no solution, then print -1 on the line.ExampleInput
4
4
1 3 2 4
1
1
5
1 3 5 4 2
3
3 2 1
Output
3 1 4 2
1
-1
2 3 1
NoteThe first test case in the example is clarified in the main section of the problem statement. There may be other correct answers for this test set.In the second test case, n=1. Thus, there is only one permutation that can be the answer: p=[1]. Indeed, this is the answer to this test case.In the third test case of the example, no matter what permutation you take as p, after applying the n steps, the result will differ from a=[1, 3, 5, 4, 2]. | 4
4
1 3 2 4
1
1
5
1 3 5 4 2
3
3 2 1
| 3 1 4 2 1 -1 2 3 1 | 2 seconds | 256 megabytes | ['constructive algorithms', '*1000'] |
B. Team Composition: Programmers and Mathematicianstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe All-Berland Team Programming Contest will take place very soon. This year, teams of four are allowed to participate.There are a programmers and b mathematicians at Berland State University. How many maximum teams can be made if: each team must consist of exactly 4 students, teams of 4 mathematicians or 4 programmers are unlikely to perform well, so the decision was made not to compose such teams. Thus, each team must have at least one programmer and at least one mathematician.Print the required maximum number of teams. Each person can be a member of no more than one team.InputThe first line contains an integer t (1 \le t \le 10^4) —the number of test cases.This is followed by descriptions of t sets, one per line. Each set is given by two integers a and b (0 \le a,b \le 10^9).OutputPrint t lines. Each line must contain the answer to the corresponding set of input data — the required maximum number of teams.ExampleInput
6
5 5
10 1
2 3
0 0
17 2
1000000000 1000000000
Output
2
1
1
0
2
500000000
NoteIn the first test case of the example, two teams can be composed. One way to compose two teams is to compose two teams of 2 programmers and 2 mathematicians.In the second test case of the example, only one team can be composed: 3 programmers and 1 mathematician in the team. | 6
5 5
10 1
2 3
0 0
17 2
1000000000 1000000000
| 2 1 1 0 2 500000000 | 1 second | 256 megabytes | ['binary search', 'constructive algorithms', 'math', '*800'] |
A. Make Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has an integer n that doesn't contain the digit 0. He can do the following operation with his number several (possibly zero) times: Reverse the prefix of length l (in other words, l leftmost digits) of n. So, the leftmost digit is swapped with the l-th digit from the left, the second digit from the left swapped with (l-1)-th left, etc. For example, if n=123456789 and l=5, then the new value of n will be 543216789.Note that for different operations, the values of l can be different. The number l can be equal to the length of the number n — in this case, the whole number n is reversed.Polycarp loves even numbers. Therefore, he wants to make his number even. At the same time, Polycarp is very impatient. He wants to do as few operations as possible.Help Polycarp. Determine the minimum number of operations he needs to perform with the number n to make it even or determine that this is impossible.You need to answer t independent test cases.InputThe first line contains the number t (1 \le t \le 10^4) — the number of test cases.Each of the following t lines contains one integer n (1 \le n < 10^9). It is guaranteed that the given number doesn't contain the digit 0.OutputPrint t lines. On each line print one integer — the answer to the corresponding test case. If it is impossible to make an even number, print -1.ExampleInput
4
3876
387
4489
3
Output
0
2
1
-1
NoteIn the first test case, n=3876, which is already an even number. Polycarp doesn't need to do anything, so the answer is 0.In the second test case, n=387. Polycarp needs to do 2 operations: Select l=2 and reverse the prefix \underline{38}7. The number n becomes 837. This number is odd. Select l=3 and reverse the prefix \underline{837}. The number n becomes 738. This number is even.It can be shown that 2 is the minimum possible number of operations that Polycarp needs to do with his number to make it even.In the third test case, n=4489. Polycarp can reverse the whole number (choose a prefix of length l=4). It will become 9844 and this is an even number.In the fourth test case, n=3. No matter how hard Polycarp tried, he would not be able to make an even number. | 4
3876
387
4489
3
| 0 2 1 -1 | 1 second | 256 megabytes | ['constructive algorithms', 'math', '*800'] |
I. Mashtali vs AtCodertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter many unsuccessful tries, Mashtali decided to copy modify an AtCoder problem. So here is his copied new problem:There is a tree with n vertices and some non-empty set of the vertices are pinned to the ground.Two players play a game against each other on the tree. They alternately perform the following action: Remove an edge from the tree, then remove every connected component that has no pinned vertex.The player who cannot move loses(every edge has been deleted already). You are given the tree, but not the set of the pinned vertices. Your task is to determine, for each k, the winner of the game, if only the vertices 1, 2, 3, \ldots, k are pinned and both players play optimally.InputThe first line of input contains an integer n — the number of vertices (1 \le n \le 3 \cdot 10^5).The i-th of the following n-1 lines contains two integers u_i, v_i (1 \le u_i, v_i \le n, u_i \ne v_i) — the endpoints of the i-th edge. It's guaranteed that these edges form a tree.OutputPrint a string of length n. The i-th character should be '1' if the first player wins the i-th scenario, and '2' otherwise.ExamplesInput
5
1 2
2 3
2 4
4 5
Output
11122
Input
5
1 2
2 3
1 4
4 5
Output
21122
Input
6
1 2
2 4
5 1
6 3
3 2
Output
111111
Input
7
1 2
3 7
4 6
2 3
2 4
1 5
Output
2212222
NoteBelow you can see the tree in the first sample : If k = 1 then the first player can cut the edge (1, 2).If k = 2 or k = 3, the first player can cut the edge (2, 4), after that only the edges (1, 2) and (2, 3) remain. After the second players move, there will be a single edge left for the first player to cut. So first player wins. | 5
1 2
2 3
2 4
4 5
| 11122 | 1 second | 256 megabytes | ['games', 'trees', '*3100'] |
H. Squid Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter watching the new over-rated series Squid Game, Mashtali and Soroush decided to hold their own Squid Games! Soroush agreed to be the host and will provide money for the winner's prize, and Mashtali became the Front Man!m players registered to play in the games to win the great prize, but when Mashtali found out how huge the winner's prize is going to be, he decided to kill eliminate all the players so he could take the money for himself!Here is how evil Mashtali is going to eliminate players:There is an unrooted tree with n vertices. Every player has 2 special vertices x_i and y_i.In one operation, Mashtali can choose any vertex v of the tree. Then, for each remaining player i he finds a vertex w on the simple path from x_i to y_i, which is the closest to v. If w\ne x_i and w\ne y_i, player i will be eliminated.Now Mashtali wondered: "What is the minimum number of operations I should perform so that I can remove every player from the game and take the money for myself?"Since he was only thinking about the money, he couldn't solve the problem by himself and asked for your help!InputThe first line contains 2 integer n and m (1 \le n, m \le 3 \cdot 10^5) — the number of vertices of the tree and the number of players.The second line contains n-1 integers par_2, par_3, \ldots, par_n (1 \le par_i < i) — denoting an edge between node i and par_i.The i-th of the following m lines contains two integers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i) — the special vertices of the i-th player.OutputPrint the minimum number of operations Mashtali has to perform.If there is no way for Mashtali to eliminate all the players, print -1.ExamplesInput
6 3
1 1 1 4 4
1 5
3 4
2 6
Output
2
Input
5 3
1 1 3 3
1 2
1 4
1 5
Output
-1
NoteExplanation for the first sample: In the first operation, Mashtali can choose vertex 1 and eliminate players with colors red and blue. In the second operation, he can choose vertex 6 and eliminate the player with orange color. In the second sample, Mashtali can't eliminate the first player. | 6 3
1 1 1 4 4
1 5
3 4
2 6
| 2 | 2 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'greedy', 'trees', '*3100'] |
G. AmShZ Wins a Bettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRight before the UEFA Euro 2020, AmShZ and Safar placed bets on who'd be the champion, AmShZ betting on Italy, and Safar betting on France.Of course, AmShZ won. Hence, Safar gave him a bracket sequence S. Note that a bracket sequence is a string made of '(' and ')' characters.AmShZ can perform the following operation any number of times: First, he cuts his string S into three (possibly empty) contiguous substrings A, B and C. Then, he glues them back by using a '(' and a ')' characters, resulting in a new string S = A + "(" + B + ")" + C.For example, if S = "))((" and AmShZ cuts it into A = "", B = "))", and C = "((", He will obtain S = "()))((" as a new string. After performing some (possibly none) operations, AmShZ gives his string to Keshi and asks him to find the initial string. Of course, Keshi might be able to come up with more than one possible initial string. Keshi is interested in finding the lexicographically smallest possible initial string.Your task is to help Keshi in achieving his goal.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.InputThe only line of input contains a single string S — the string after the operations (1\le |S|\le 3 \cdot 10^5).It is guaranteed that the first character of S is ')'.OutputPrint the lexicographically smallest possible initial string before operations.ExampleInput
)(()(())))
Output
)((())))
NoteIn the first sample, you can transform ")((())))" into ")(()(())))" by splitting it into ")(", empty string, and "(())))". It can be shown that this is the lexicographically smallest possible initial string | )(()(())))
| )((()))) | 1 second | 256 megabytes | ['data structures', 'greedy', 'hashing', '*3300'] |
F. Mashtali: a Space Oddyseytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLee was planning to get closer to Mashtali's heart to proceed with his evil plan(which we're not aware of, yet), so he decided to beautify Mashtali's graph. But he made several rules for himself. And also he was too busy with his plans that he didn't have time for such minor tasks, so he asked you for help.Mashtali's graph is an undirected weighted graph with n vertices and m edges with weights equal to either 1 or 2. Lee wants to direct the edges of Mashtali's graph so that it will be as beautiful as possible.Lee thinks that the beauty of a directed weighted graph is equal to the number of its Oddysey vertices. A vertex v is an Oddysey vertex if |d^+(v) - d^-(v)| = 1, where d^+(v) is the sum of weights of the outgoing from v edges, and d^-(v) is the sum of the weights of the incoming to v edges.Find the largest possible beauty of a graph that Lee can achieve by directing the edges of Mashtali's graph. In addition, find any way to achieve it.Note that you have to orient each edge.InputThe first line contains two integers n and m (1 \le n \le 10^5;\; 1 \le m \le 10^5) — the numbers of vertices and edges in the graph.The i-th line of the following m lines contains three integers u_i, v_i and w_i ( 1 \le u_i , v_i \le n;\; u_i \neq v_i;\; \bf{w_i \in \{1, 2\}} ) — the endpoints of the i-th edge and its weight.Note that the graph doesn't have to be connected, and it might contain multiple edges.OutputIn the first line print a single integer — the maximum beauty of the graph Lee can achieve.In the second line print a string of length m consisting of 1s and 2s — directions of the edges.If you decide to direct the i-th edge from vertex u_i to vertex v_i, i-th character of the string should be 1. Otherwise, it should be 2.ExamplesInput
6 7
1 2 1
1 3 2
2 3 2
1 4 1
4 5 1
2 5 2
2 6 2
Output
2
1212212
Input
6 7
1 2 2
1 3 2
2 3 2
1 4 2
4 5 2
2 5 2
2 6 2
Output
0
1212212
Input
6 7
1 2 1
1 3 1
2 3 1
1 4 1
4 5 1
2 5 1
2 6 1
Output
2
1212212
NoteExplanation for the first sample: vertices 2 and 5 are Oddyseys. Explanation for the third sample: vertices 1 and 6 are Oddyseys. | 6 7
1 2 1
1 3 2
2 3 2
1 4 1
4 5 1
2 5 2
2 6 2
| 2 1212212 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', '*3000'] |
E. AmShZ and G.O.A.T.time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call an array of k integers c_1, c_2, \ldots, c_k terrible, if the following condition holds:Let AVG be the \frac{c_1 + c_2 + \ldots + c_k}{k}(the average of all the elements of the array, it doesn't have to be integer). Then the number of elements of the array which are bigger than AVG should be strictly larger than the number of elements of the array which are smaller than AVG. Note that elements equal to AVG don't count.For example c = \{1, 4, 4, 5, 6\} is terrible because AVG = 4.0 and 5-th and 4-th elements are greater than AVG and 1-st element is smaller than AVG.Let's call an array of m integers b_1, b_2, \ldots, b_m bad, if at least one of its non-empty subsequences is terrible, and good otherwise.You are given an array of n integers a_1, a_2, \ldots, a_n. Find the minimum number of elements that you have to delete from it to obtain a good array.An array is a subsequence of another array if it can be obtained from it by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the size of a.The second line of each testcase contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — elements of array a.In each testcase for any 1 \le i \lt n it is guaranteed that a_i \le a_{i+1}.It is guaranteed that the sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print the minimum number of elements that you have to delete from it to obtain a good array.ExampleInput
4
3
1 2 3
5
1 4 4 5 6
6
7 8 197860736 212611869 360417095 837913434
8
6 10 56026534 405137099 550504063 784959015 802926648 967281024
Output
0
1
2
3
NoteIn the first sample, the array a is already good.In the second sample, it's enough to delete 1, obtaining array [4, 4, 5, 6], which is good. | 4
3
1 2 3
5
1 4 4 5 6
6
7 8 197860736 212611869 360417095 837913434
8
6 10 56026534 405137099 550504063 784959015 802926648 967281024
| 0 1 2 3 | 1 second | 256 megabytes | ['binary search', 'brute force', 'greedy', 'implementation', 'math', '*2300'] |
D. Not Quite Leetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLee couldn't sleep lately, because he had nightmares. In one of his nightmares (which was about an unbalanced global round), he decided to fight back and propose a problem below (which you should solve) to balance the round, hopefully setting him free from the nightmares.A non-empty array b_1, b_2, \ldots, b_m is called good, if there exist m integer sequences which satisfy the following properties: The i-th sequence consists of b_i consecutive integers (for example if b_i = 3 then the i-th sequence can be (-1, 0, 1) or (-5, -4, -3) but not (0, -1, 1) or (1, 2, 3, 4)). Assuming the sum of integers in the i-th sequence is sum_i, we want sum_1 + sum_2 + \ldots + sum_m to be equal to 0. You are given an array a_1, a_2, \ldots, a_n. It has 2^n - 1 nonempty subsequences. Find how many of them are good.As this number can be very large, output it modulo 10^9 + 7.An array c is a subsequence of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements.InputThe first line contains a single integer n (2 \le n \le 2 \cdot 10^5) — the size of array a.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — elements of the array.OutputPrint a single integer — the number of nonempty good subsequences of a, modulo 10^9 + 7.ExamplesInput
4
2 2 4 7
Output
10
Input
10
12391240 103904 1000000000 4142834 12039 142035823 1032840 49932183 230194823 984293123
Output
996
NoteFor the first test, two examples of good subsequences are [2, 7] and [2, 2, 4, 7]:For b = [2, 7] we can use (-3, -4) as the first sequence and (-2, -1, \ldots, 4) as the second. Note that subsequence [2, 7] appears twice in [2, 2, 4, 7], so we have to count it twice. Green circles denote (-3, -4) and orange squares denote (-2, -1, \ldots, 4). For b = [2, 2, 4, 7] the following sequences would satisfy the properties: (-1, 0), (-3, -2), (0, 1, 2, 3) and (-3, -2, \ldots, 3) | 4
2 2 4 7
| 10 | 1 second | 256 megabytes | ['combinatorics', 'dp', 'math', 'number theory', '*2000'] |
C. Keshi Is Throwing a Partytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKeshi is throwing a party and he wants everybody in the party to be happy.He has n friends. His i-th friend has i dollars. If you invite the i-th friend to the party, he will be happy only if at most a_i people in the party are strictly richer than him and at most b_i people are strictly poorer than him.Keshi wants to invite as many people as possible. Find the maximum number of people he can invite to the party so that every invited person would be happy.InputThe first line contains a single integer t (1\le t\le 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1\le n\le 2 \cdot 10^5) — the number of Keshi's friends.The i-th of the following n lines contains two integers a_i and b_i (0 \le a_i, b_i < n).It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case print the maximum number of people Keshi can invite.ExampleInput
3
3
1 2
2 1
1 1
2
0 0
0 1
2
1 0
0 1
Output
2
1
2
NoteIn the first test case, he invites the first and the second person. If he invites all of them, the third person won't be happy because there will be more than 1 person poorer than him. | 3
3
1 2
2 1
1 1
2
0 0
0 1
2
1 0
0 1
| 2 1 2 | 1 second | 256 megabytes | ['binary search', 'greedy', '*1600'] |
B. Kalindrome Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array [b_1, b_2, \ldots, b_m] is a palindrome, if b_i = b_{m+1-i} for each i from 1 to m. Empty array is also a palindrome.An array is called kalindrome, if the following condition holds: It's possible to select some integer x and delete some of the elements of the array equal to x, so that the remaining array (after gluing together the remaining parts) is a palindrome. Note that you don't have to delete all elements equal to x, and you don't have to delete at least one element equal to x.For example : [1, 2, 1] is kalindrome because you can simply not delete a single element. [3, 1, 2, 3, 1] is kalindrome because you can choose x = 3 and delete both elements equal to 3, obtaining array [1, 2, 1], which is a palindrome. [1, 2, 3] is not kalindrome. You are given an array [a_1, a_2, \ldots, a_n]. Determine if a is kalindrome or not.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the array.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — elements of the array.It's guaranteed that the sum of n over all test cases won't exceed 2 \cdot 10^5.OutputFor each test case, print YES if a is kalindrome and NO otherwise. You can print each letter in any case.ExampleInput
4
1
1
2
1 2
3
1 2 3
5
1 4 4 1 4
Output
YES
YES
NO
YES
NoteIn the first test case, array [1] is already a palindrome, so it's a kalindrome as well.In the second test case, we can choose x = 2, delete the second element, and obtain array [1], which is a palindrome.In the third test case, it's impossible to obtain a palindrome.In the fourth test case, you can choose x = 4 and delete the fifth element, obtaining [1, 4, 4, 1]. You also can choose x = 1, delete the first and the fourth elements, and obtain [4, 4, 4]. | 4
1
1
2
1 2
3
1 2 3
5
1 4 4 1 4
| YES YES NO YES | 1 second | 256 megabytes | ['greedy', 'two pointers', '*1100'] |
A. Anti Light's Cell Guessingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a game on a n \times m grid, in which the computer has selected some cell (x, y) of the grid, and you have to determine which one. To do so, you will choose some k and some k cells (x_1, y_1),\, (x_2, y_2), \ldots, (x_k, y_k), and give them to the computer. In response, you will get k numbers b_1,\, b_2, \ldots b_k, where b_i is the manhattan distance from (x_i, y_i) to the hidden cell (x, y) (so you know which distance corresponds to which of k input cells). After receiving these b_1,\, b_2, \ldots, b_k, you have to be able to determine the hidden cell. What is the smallest k for which is it possible to always guess the hidden cell correctly, no matter what cell computer chooses?As a reminder, the manhattan distance between cells (a_1, b_1) and (a_2, b_2) is equal to |a_1-a_2|+|b_1-b_2|.InputThe first line of the input contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows. The single line of each test case contains two integers n and m (1 \le n, m \le 10^9) — the number of rows and the number of columns in the grid.OutputFor each test case print a single integer — the minimum k for that test case.ExampleInput
2
2 3
3 1
Output
2
1
NoteIn the first test case, the smallest such k is 2, for which you can choose, for example, cells (1, 1) and (2, 1).Note that you can't choose cells (1, 1) and (2, 3) for k = 2, as both cells (1, 2) and (2, 1) would give b_1 = 1, b_2 = 2, so we wouldn't be able to determine which cell is hidden if computer selects one of those.In the second test case, you should choose k = 1, for it you can choose cell (3, 1) or (1, 1). | 2
2 3
3 1
| 2 1 | 1 second | 256 megabytes | ['math', '*900'] |
H. Pushing Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output There're n robots placed on a number line. Initially, i-th of them occupies unit segment [x_i, x_i + 1]. Each robot has a program, consisting of k instructions numbered from 1 to k. The robot performs instructions in a cycle. Each instruction is described by an integer number. Let's denote the number corresponding to the j-th instruction of the i-th robot as f_{i, j}.Initial placement of robots corresponds to the moment of time 0. During one second from moment of time t (0 \le t) until t + 1 the following process occurs: Each robot performs (t \bmod k + 1)-th instruction from its list of instructions. Robot number i takes number F = f_{i, (t \bmod k + 1)}. If this number is negative (less than zero), the robot is trying to move to the left with force |F|. If the number is positive (more than zero), the robot is trying to move to the right with force F. Otherwise, the robot does nothing. Let's imaginary divide robots into groups of consecutive, using the following algorithm: Initially, each robot belongs to its own group. Let's sum up numbers corresponding to the instructions of the robots from one group. Note that we are summing numbers without taking them by absolute value. Denote this sum as S. We say that the whole group moves together, and does it with force S by the same rules as a single robot. That is if S is negative, the group is trying to move to the left with force |S|. If S is positive, the group is trying to move to the right with force S. Otherwise, the group does nothing. If one group is trying to move, and in the direction of movement touches another group, let's unite them. One group is touching another if their outermost robots occupy adjacent unit segments. Continue this process until groups stop uniting. Each robot moves by 1 in the direction of movement of its group or stays in place if its group isn't moving. But there's one exception. The exception is if there're two groups of robots, divided by exactly one unit segment, such that the left group is trying to move to the right and the right group is trying to move to the left. Let's denote sum in the left group as S_l and sum in the right group as S_r. If |S_l| \le |S_r| only the right group will move. Otherwise, only the left group will move. Note that robots from one group don't glue together. They may separate in the future. The division into groups is imaginary and is needed only to understand how robots will move during one second [t, t + 1]. An illustration of the process happening during one second: Rectangles represent robots. Numbers inside rectangles correspond to instructions of robots. The final division into groups is marked with arcs. Below are the positions of the robots after moving. Only the left of the two rightmost groups moved. That's because these two groups tried to move towards each other, and were separated by exactly one unit segment.Look at the examples for a better understanding of the process.You need to answer several questions. What is the position of a_i-th robot at the moment of time t_i?InputThe first line contains two integer numbers n and k — the number of robots and the number of instructions in the program of one robot (1 \le n \le 100, 1 \le k \le 50).The next line contains n integer numbers x_i — positions of robots at moment of time 0 (-10^9 \le x_1 < x_2 < \dots < x_n < 10^9).The next n lines contain descriptions of robots' programs. The i-th of these lines contains k integer numbers f_{i, j} (|f_{i, j}| \le 10^6).The next line contains a single integer number q — the number of questions you to answer (1 \le q \le 1000).The next q lines contain two integer number a_i and t_i each, meaning that you should find a position of a_i-th robot at moment of time t_i (1 \le a_i \le n, 0 \le t_i \le 10^{18}).OutputFor every question output a single integer on the new line. Coordinate of the left border of unit segment occupied by the a_i-th robot at the moment of time t_i.ExamplesInput
2 1
0 4
1
-1
8
1 0
2 0
1 1
2 1
1 2
2 2
1 3
2 3
Output
0
4
1
3
1
2
1
2
Input
2 1
0 4
2
-1
8
1 0
2 0
1 1
2 1
1 2
2 2
1 3
2 3
Output
0
4
1
3
2
3
3
4
Input
2 2
0 1
1 -1
-1 1
4
1 0
1 1
1 2
1 3
Output
0
0
-1
0
Input
1 3
0
3 -2 1
3
1 5
1 10
1 15
Output
1
4
5
Input
4 3
-8 -4 2 5
-1 3 0
1 -3 -4
2 -5 2
-1 -4 2
5
3 12
4 18
4 11
1 6
1 10
Output
6
9
6
-8
-9
| 2 1
0 4
1
-1
8
1 0
2 0
1 1
2 1
1 2
2 2
1 3
2 3
| 0 4 1 3 1 2 1 2 | 1 second | 256 megabytes | ['*3500'] |
G. A Stroll Around the Matrixtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output William has two arrays of numbers a_1, a_2, \dots, a_n and b_1, b_2, \dots, b_m. The arrays satisfy the conditions of being convex. Formally an array c of length k is considered convex if c_i - c_{i - 1} < c_{i + 1} - c_i for all i from 2 to k - 1 and c_1 < c_2.Throughout William's life he observed q changes of two types happening to the arrays: Add the arithmetic progression d, d \cdot 2, d \cdot 3, \dots, d \cdot k to the suffix of the array a of length k. The array after the change looks like this: [a_1, a_2, \dots, a_{n - k}, a_{n - k + 1} + d, a_{n - k + 2} + d \cdot 2, \dots, a_n + d \cdot k]. The same operation, but for array b. After each change a matrix d is created from arrays a and b, of size n \times m, where d_{i, j}=a_i + b_j. William wants to get from cell (1, 1) to cell (n, m) of this matrix. From cell (x, y) he can only move to cells (x + 1, y) and (x, y + 1). The length of a path is calculated as the sum of numbers in cells visited by William, including the first and the last cells.After each change William wants you to help find out the minimal length of the path he could take.InputThe first line contains three integers n, m and q (2 \le n \le 100, 2 \le m \le 10^5, 1 \le q \le 10^5), the sizes of the arrays and the number of changes.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{12}), the contents of array a.The third line contains m integers b_1, b_2, \dots, b_m (1 \le b_i \le 10^{12}), the contents of array b.Each of the next q lines contains three integers type, k and d (1 \le type \le 2, if type = 1, then 1 \le k \le n otherwise 1 \le k \le m, 1 \le d \le 10^3).OutputAfter each change, output one integer, the minimum length of the path in the constructed matrix.ExamplesInput
5 3 4
1 2 4 7 11
5 7 10
1 3 2
2 2 5
1 5 4
2 1 7
Output
98
128
219
229
Input
5 6 7
4 9 22 118 226
7 94 238 395 565 738
2 1 95
1 4 54
1 2 5
1 2 87
2 6 62
2 1 143
1 1 77
Output
3639
5122
5162
5617
7663
7806
7960
| 5 3 4
1 2 4 7 11
5 7 10
1 3 2
2 2 5
1 5 4
2 1 7
| 98 128 219 229 | 6 seconds | 256 megabytes | ['data structures', 'greedy', 'math', '*3000'] |
F. Interesting Sectionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output William has an array of non-negative numbers a_1, a_2, \dots, a_n. He wants you to find out how many segments l \le r pass the check. The check is performed in the following manner: The minimum and maximum numbers are found on the segment of the array starting at l and ending at r. The check is considered to be passed if the binary representation of the minimum and maximum numbers have the same number of bits equal to 1. InputThe first line contains a single integer n (1 \le n \le 10^6), the size of array a.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^{18}), the contents of array a.OutputOutput a single number — the total number of segments that passed the check.ExamplesInput
5
1 2 3 4 5
Output
9
Input
10
0 5 7 3 9 10 1 6 13 7
Output
18
| 5
1 2 3 4 5
| 9 | 2 seconds | 256 megabytes | ['data structures', 'divide and conquer', 'meet-in-the-middle', 'two pointers', '*2800'] |
E. William The Oblivious time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string s of length n only consisting of characters "a", "b" and "c". There are q queries of format (pos, c), meaning replacing the element of string s at position pos with character c. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string x is said to be a subsequence of string y if x can be obtained from y by deleting some characters without changing the ordering of the remaining characters.InputThe first line contains two integers n and q (1 \le n, q \le 10^5), the length of the string and the number of queries, respectively.The second line contains the string s, consisting of characters "a", "b" and "c".Each of the next q lines contains an integer i and character c (1 \le i \le n), index and the value of the new item in the string, respectively. It is guaranteed that character's c value is "a", "b" or "c".OutputFor each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence.ExampleInput
9 12
aaabccccc
4 a
4 b
2 b
5 a
1 b
6 b
5 c
2 a
1 a
5 a
6 b
7 b
Output
0
1
2
2
1
2
1
2
2
2
2
2
NoteLet's consider the state of the string after each query: s = "aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. s = "aaabccccc". In this case 1 replacements can be performed to get, for instance, string s = "aaaaccccc". This string does not contain "abc" as a subsequence. s = "ababccccc". In this case 2 replacements can be performed to get, for instance, string s = aaaaccccc". This string does not contain "abc" as a subsequence. s = "ababacccc". In this case 2 replacements can be performed to get, for instance, string s = "aaaaacccc". This string does not contain "abc" as a subsequence. s = "bbabacccc". In this case 1 replacements can be performed to get, for instance, string s = "bbacacccc". This string does not contain "abc" as a subsequence. s = "bbababccc". In this case 2 replacements can be performed to get, for instance, string s = "bbacacccc". This string does not contain "abc" as a subsequence. s = "bbabcbccc". In this case 1 replacements can be performed to get, for instance, string s = "bbcbcbccc". This string does not contain "abc" as a subsequence. s = "baabcbccc". In this case 2 replacements can be performed to get, for instance, string s = "bbbbcbccc". This string does not contain "abc" as a subsequence. s = "aaabcbccc". In this case 2 replacements can be performed to get, for instance, string s = "aaacccccc". This string does not contain "abc" as a subsequence. s = "aaababccc". In this case 2 replacements can be performed to get, for instance, string s = "aaacacccc". This string does not contain "abc" as a subsequence. s = "aaababccc". In this case 2 replacements can be performed to get, for instance, string s = "aaacacccc". This string does not contain "abc" as a subsequence. s = "aaababbcc". In this case 2 replacements can be performed to get, for instance, string s = "aaababbbb". This string does not contain "abc" as a subsequence. | 9 12
aaabccccc
4 a
4 b
2 b
5 a
1 b
6 b
5 c
2 a
1 a
5 a
6 b
7 b
| 0 1 2 2 1 2 1 2 2 2 2 2 | 3 seconds | 256 megabytes | ['bitmasks', 'data structures', 'dp', 'matrices', '*2400'] |
D. Social Networktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has n participants, who are initially unfamiliar with each other. William can introduce any two people, a and b, who were not familiar before, to each other. William has d conditions, i'th of which requires person x_i to have a connection to person y_i. Formally, two people x and y have a connection if there is such a chain p_1=x, p_2, p_3, \dots, p_k=y for which for all i from 1 to k - 1 it's true that two people with numbers p_i and p_{i + 1} know each other.For every i (1 \le i \le d) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from 1 and up to and including i and performed exactly i introductions. The conditions are being checked after William performed i introductions. The answer for each i must be calculated independently. It means that when you compute an answer for i, you should assume that no two people have been introduced to each other yet.InputThe first line contains two integers n and d (2 \le n \le 10^3, 1 \le d \le n - 1), the number of people, and number of conditions, respectively.Each of the next d lines each contain two integers x_i and y_i (1 \le x_i, y_i \le n, x_i \neq y_i), the numbers of people which must have a connection according to condition i.OutputOutput d integers. ith number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed i introductions and satisfied the first i conditions.ExamplesInput
7 6
1 2
3 4
2 4
7 6
6 5
1 7
Output
1
1
3
3
3
6
Input
10 8
1 2
2 3
3 4
1 4
6 7
8 9
8 10
1 4
Output
1
2
3
4
5
5
6
8
NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | 7 6
1 2
3 4
2 4
7 6
6 5
1 7
| 1 1 3 3 3 6 | 2 seconds | 256 megabytes | ['dsu', 'graphs', 'greedy', 'implementation', 'trees', '*1600'] |
C. Complex Market Analysistime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output While performing complex market analysis William encountered the following problem:For a given array a of size n and a natural number e, calculate the number of pairs of natural numbers (i, k) which satisfy the following conditions: 1 \le i, k i + e \cdot k \le n. Product a_i \cdot a_{i + e} \cdot a_{i + 2 \cdot e} \cdot \ldots \cdot a_{i + k \cdot e} is a prime number. A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10\,000). Description of the test cases follows.The first line of each test case contains two integers n and e (1 \le e \le n \le 2 \cdot 10^5), the number of items in the array and number e, respectively.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6), the contents 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 output the answer in the following format:Output one line containing the number of pairs of numbers (i, k) which satisfy the conditions.ExampleInput
6
7 3
10 2 1 3 1 19 3
3 2
1 13 1
9 3
2 4 2 1 1 1 1 4 2
3 1
1 1 1
4 1
1 2 1 1
2 2
1 2
Output
2
0
4
0
5
0
NoteIn the first example test case two pairs satisfy the conditions: i = 2, k = 1, for which the product is: a_{2} \cdot a_{5} = 2 which is a prime number. i = 3, k = 1, for which the product is: a_{3} \cdot a_{6} = 19 which is a prime number. In the second example test case there are no pairs that satisfy the conditions.In the third example test case four pairs satisfy the conditions: i = 1, k = 1, for which the product is: a_{1} \cdot a_{4} = 2 which is a prime number. i = 1, k = 2, for which the product is: a_{1} \cdot a_{4} \cdot a_{7} = 2 which is a prime number. i = 3, k = 1, for which the product is: a_{3} \cdot a_{6} = 2 which is a prime number. i = 6, k = 1, for which the product is: a_{6} \cdot a_{9} = 2 which is a prime number. In the fourth example test case there are no pairs that satisfy the conditions.In the fifth example test case five pairs satisfy the conditions: i = 1, k = 1, for which the product is: a_{1} \cdot a_{2} = 2 which is a prime number. i = 1, k = 2, for which the product is: a_{1} \cdot a_{2} \cdot a_{3} = 2 which is a prime number. i = 1, k = 3, for which the product is: a_{1} \cdot a_{2} \cdot a_{3} \cdot a_{4} = 2 which is a prime number. i = 2, k = 1, for which the product is: a_{2} \cdot a_{3} = 2 which is a prime number. i = 2, k = 2, for which the product is: a_{2} \cdot a_{3} \cdot a_{4} = 2 which is a prime number. In the sixth example test case there are no pairs that satisfy the conditions. | 6
7 3
10 2 1 3 1 19 3
3 2
1 13 1
9 3
2 4 2 1 1 1 1 4 2
3 1
1 1 1
4 1
1 2 1 1
2 2
1 2
| 2 0 4 0 5 0 | 2 seconds | 256 megabytes | ['binary search', 'dp', 'implementation', 'number theory', 'schedules', 'two pointers', '*1400'] |
B. William the Vigilanttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is the correct formal description of the homework assignment:You are given a string s of length n only consisting of characters "a", "b" and "c". There are q queries of format (pos, c), meaning replacing the element of string s at position pos with character c. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string x is a substring of a string y if x can be obtained from y by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.InputThe first line contains two integers n and q (1 \le n, q \le 10^5), the length of the string and the number of queries, respectively.The second line contains the string s, consisting of characters "a", "b" and "c".Each of the next q lines contains an integer i and character c (1 \le i \le n), index and the value of the new item in the string, respectively. It is guaranteed that character's c value is "a", "b" or "c".OutputFor each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a substring.ExampleInput
9 10
abcabcabc
1 a
1 b
2 c
3 a
4 b
5 c
8 a
9 b
1 c
4 a
Output
3
2
2
2
1
2
1
1
1
0
NoteLet's consider the state of the string after each query: s = "abcabcabc". In this case 3 replacements can be performed to get, for instance, string s = "bbcaccabb". This string does not contain "abc" as a substring. s = "bbcabcabc". In this case 2 replacements can be performed to get, for instance, string s = "bbcbbcbbc". This string does not contain "abc" as a substring. s = "bccabcabc". In this case 2 replacements can be performed to get, for instance, string s = "bccbbcbbc". This string does not contain "abc" as a substring. s = "bcaabcabc". In this case 2 replacements can be performed to get, for instance, string s = "bcabbcbbc". This string does not contain "abc" as a substring. s = "bcabbcabc". In this case 1 replacements can be performed to get, for instance, string s = "bcabbcabb". This string does not contain "abc" as a substring. s = "bcabccabc". In this case 2 replacements can be performed to get, for instance, string s = "bcabbcabb". This string does not contain "abc" as a substring. s = "bcabccaac". In this case 1 replacements can be performed to get, for instance, string s = "bcabbcaac". This string does not contain "abc" as a substring. s = "bcabccaab". In this case 1 replacements can be performed to get, for instance, string s = "bcabbcaab". This string does not contain "abc" as a substring. s = "ccabccaab". In this case 1 replacements can be performed to get, for instance, string s = "ccabbcaab". This string does not contain "abc" as a substring. s = "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | 9 10
abcabcabc
1 a
1 b
2 c
3 a
4 b
5 c
8 a
9 b
1 c
4 a
| 3 2 2 2 1 2 1 1 1 0 | 2 seconds | 256 megabytes | ['implementation', 'strings', '*1100'] |
A. Divide and Multiplytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output William has array of n numbers a_1, a_2, \dots, a_n. He can perform the following sequence of operations any number of times: Pick any two items from array a_i and a_j, where a_i must be a multiple of 2 a_i = \frac{a_i}{2} a_j = a_j \cdot 2 Help William find the maximal sum of array elements, which he can get by performing the sequence of operations described above.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). Description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 15), the number of elements in William's array.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i < 16), the contents of William's array.OutputFor each test case output the maximal sum of array elements after performing an optimal sequence of operations.ExampleInput
5
3
6 4 2
5
1 2 3 4 5
1
10
3
2 3 4
15
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
Output
50
46
10
26
35184372088846
NoteIn the first example test case the optimal sequence would be: Pick i = 2 and j = 1. After performing a sequence of operations a_2 = \frac{4}{2} = 2 and a_1 = 6 \cdot 2 = 12, making the array look as: [12, 2, 2]. Pick i = 2 and j = 1. After performing a sequence of operations a_2 = \frac{2}{2} = 1 and a_1 = 12 \cdot 2 = 24, making the array look as: [24, 1, 2]. Pick i = 3 and j = 1. After performing a sequence of operations a_3 = \frac{2}{2} = 1 and a_1 = 24 \cdot 2 = 48, making the array look as: [48, 1, 1]. The final answer 48 + 1 + 1 = 50.In the third example test case there is no way to change the sum of elements, so the answer is 10. | 5
3
6 4 2
5
1 2 3 4 5
1
10
3
2 3 4
15
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
| 50 46 10 26 35184372088846 | 1 second | 256 megabytes | ['greedy', 'implementation', 'math', 'number theory', '*900'] |
G. Alphabetic Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given m strings and a tree on n nodes. Each edge has some letter written on it.You have to answer q queries. Each query is described by 4 integers u, v, l and r. The answer to the query is the total number of occurrences of str(u,v) in strings with indices from l to r. str(u,v) is defined as the string that is made by concatenating letters written on the edges on the shortest path from u to v (in order that they are traversed).InputThe first line of the input contains three integers n, m and q (2 \le n \le 10^5, 1 \le m,q \le 10^5).The i-th of the following n-1 lines contains two integers u_i, v_i and a lowercase Latin letter c_i (1 \le u_i, v_i \le n, u_i \neq v_i), denoting the edge between nodes u_i, v_i with a character c_i on it. It's guaranteed that these edges form a tree.The following m lines contain the strings consisting of lowercase Latin letters. The total length of those strings does not exceed 10^5.Then q lines follow, each containing four integers u, v, l and r (1 \le u,v \le n, u \neq v, 1 \le l \le r \le m), denoting the queries. OutputFor each query print a single integer — the answer to the query.ExamplesInput
2 5 3
1 2 a
aab
abab
aaa
b
a
2 1 1 5
1 2 1 3
2 1 3 5
Output
8
7
4
Input
9 5 6
1 2 a
2 7 c
1 3 b
3 4 b
4 6 b
3 5 a
5 8 b
5 9 c
ababa
cabbb
bac
bbbac
abacaba
2 7 1 4
2 5 1 5
6 3 4 4
6 9 4 5
5 7 3 5
5 3 1 5
Output
3
4
2
1
1
10
| 2 5 3
1 2 a
aab
abab
aaa
b
a
2 1 1 5
1 2 1 3
2 1 3 5
| 8 7 4 | 3 seconds | 256 megabytes | ['binary search', 'data structures', 'dfs and similar', 'hashing', 'string suffix structures', 'strings', 'trees', '*3500'] |
F. MEX countingtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor an array c of nonnegative integers, MEX(c) denotes the smallest nonnegative integer that doesn't appear in it. For example, MEX([0, 1, 3]) = 2, MEX([42]) = 0.You are given integers n, k, and an array [b_1, b_2, \ldots, b_n].Find the number of arrays [a_1, a_2, \ldots, a_n], for which the following conditions hold:0 \le a_i \le n for each i for each i from 1 to n.|MEX([a_1, a_2, \ldots, a_i]) - b_i| \le k for each i from 1 to n.As this number can be very big, output it modulo 998\,244\,353.InputThe first line of the input contains two integers n, k (1 \le n \le 2000, 0 \le k \le 50).The second line of the input contains n integers b_1, b_2, \ldots, b_n (-k \le b_i \le n+k) — elements of the array b.OutputOutput a single integer — the number of arrays which satisfy the conditions from the statement, modulo 998\,244\,353.ExamplesInput
4 0
0 0 0 0
Output
256
Input
4 1
0 0 0 0
Output
431
Input
4 1
0 0 1 1
Output
509
Input
5 2
0 0 2 2 0
Output
6546
Input
3 2
-2 0 4
Output
11
| 4 0
0 0 0 0
| 256 | 4 seconds | 256 megabytes | ['combinatorics', 'dp', 'implementation', '*3200'] |
E. The Cells on the Papertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn an endless checkered sheet of paper, n cells are chosen and colored in three colors, where n is divisible by 3. It turns out that there are exactly \frac{n}{3} marked cells of each of three colors! Find the largest such k that it's possible to choose \frac{k}{3} cells of each color, remove all other marked cells, and then select three rectangles with sides parallel to the grid lines so that the following conditions hold: No two rectangles can intersect (but they can share a part of the boundary). In other words, the area of intersection of any two of these rectangles must be 0. The i-th rectangle contains all the chosen cells of the i-th color and no chosen cells of other colors, for i = 1, 2, 3. InputThe first line of the input contains a single integer n — the number of the marked cells (3 \leq n \le 10^5, n is divisible by 3).The i-th of the following n lines contains three integers x_i, y_i, c_i (|x_i|,|y_i| \leq 10^9; 1 \leq c_i \leq 3), where (x_i, y_i) are the coordinates of the i-th marked cell and c_i is its color.It's guaranteed that all cells (x_i, y_i) in the input are distinct, and that there are exactly \frac{n}{3} cells of each color.OutputOutput a single integer k — the largest number of cells you can leave.ExamplesInput
9
2 3 1
4 1 2
2 1 3
3 4 1
5 3 2
4 4 3
2 4 1
5 2 2
3 5 3
Output
6
Input
3
1 1 1
2 2 2
3 3 3
Output
3
NoteIn the first sample, it's possible to leave 6 cells with indexes 1, 5, 6, 7, 8, 9.In the second sample, it's possible to leave 3 cells with indexes 1, 2, 3. | 9
2 3 1
4 1 2
2 1 3
3 4 1
5 3 2
4 4 3
2 4 1
5 2 2
3 5 3
| 6 | 2 seconds | 256 megabytes | ['binary search', 'implementation', 'sortings', '*2800'] |
D. Dominoestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each 1 \le i \le n the color of the right cell of the i-th domino is different from the color of the left cell of the ((i \bmod n)+1)-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo 998\,244\,353.InputThe first line of the input contains a single integer n (1 \le n \le 10^5) — the number of dominoes.The next n lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored. OutputPrint a single integer — the answer to the problem.ExamplesInput
1
?W
Output
1
Input
2
??
W?
Output
2
Input
4
BB
??
W?
??
Output
10
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only 2 such colorings:BB WW and WB WB. | 1
?W
| 1 | 1 second | 256 megabytes | ['combinatorics', 'fft', 'graphs', 'math', 'number theory', '*2400'] |
C. Game Mastertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputn players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of n-1 battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 10^5) — the number of players.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^9, a_i \neq a_j for i \neq j), where a_i is the strength of the i-th player on the first map. The third line of each test case contains n integers b_1, b_2, \dots, b_n (1 \leq b_i \leq 10^9, b_i \neq b_j for i \neq j), where b_i is the strength of the i-th player on the second map. It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case print a string of length n. i-th character should be "1" if the i-th player can win the tournament, or "0" otherwise.ExampleInput
3
4
1 2 3 4
1 2 3 4
4
11 12 20 21
44 22 11 30
1
1000000000
1000000000
Output
0001
1111
1
NoteIn the first test case, the 4-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament. | 3
4
1 2 3 4
1 2 3 4
4
11 12 20 21
44 22 11 30
1
1000000000
1000000000
| 0001 1111 1 | 1 second | 256 megabytes | ['data structures', 'dfs and similar', 'dp', 'graphs', 'greedy', 'two pointers', '*1700'] |
B. Build the Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers n, a, b. Determine if there exists a permutation p_1, p_2, \ldots, p_n of integers from 1 to n, such that:There are exactly a integers i with 2 \le i \le n-1 such that p_{i-1} < p_i > p_{i+1} (in other words, there are exactly a local maximums).There are exactly b integers i with 2 \le i \le n-1 such that p_{i-1} > p_i < p_{i+1} (in other words, there are exactly b local minimums).If such permutations exist, find any such permutation.InputThe first line of the input contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows.The only line of each test case contains three integers n, a and b (2 \leq n \leq 10^5, 0 \leq a,b \leq n).The sum of n over all test cases doesn't exceed 10^5.OutputFor each test case, if there is no permutation with the requested properties, output -1.Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.ExampleInput
3
4 1 1
6 1 2
6 4 0
Output
1 3 2 4
4 2 3 1 5 6
-1
NoteIn the first test case, one example of such permutations is [1, 3, 2, 4]. In it p_1 < p_2 > p_3, and 2 is the only such index, and p_2> p_3 < p_4, and 3 the only such index.One can show that there is no such permutation for the third test case. | 3
4 1 1
6 1 2
6 4 0
| 1 3 2 4 4 2 3 1 5 6 -1 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*1200'] |
A. Find Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven n, find any array a_1, a_2, \ldots, a_n of integers such that all of the following conditions hold: 1 \le a_i \le 10^9 for every i from 1 to n.a_1 < a_2 < \ldots <a_nFor every i from 2 to n, a_i isn't divisible by a_{i-1}It can be shown that such an array always exists under the constraints of the problem.InputThe first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The only line of each test case contains a single integer n (1 \le n \le 1000).It is guaranteed that the sum of n over all test cases does not exceed 10^4.OutputFor each test case print n integers a_1, a_2, \ldots, a_n — the array you found. If there are multiple arrays satisfying all the conditions, print any of them.ExampleInput
3
1
2
7
Output
1
2 3
111 1111 11111 111111 1111111 11111111 111111111NoteIn the first test case, array [1] satisfies all the conditions.In the second test case, array [2, 3] satisfies all the conditions, as 2<3 and 3 is not divisible by 2.In the third test case, array [111, 1111, 11111, 111111, 1111111, 11111111, 111111111] satisfies all the conditions, as it's increasing and a_i isn't divisible by a_{i-1} for any i from 2 to 7. | 3
1
2
7
| 1 2 3 111 1111 11111 111111 1111111 11111111 111111111 | 1 second | 256 megabytes | ['constructive algorithms', 'math', '*800'] |
H. Banquet Preparations 2time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe chef has cooked n dishes yet again: the i-th dish consists of a_i grams of fish and b_i grams of meat. Banquet organizers consider two dishes i and j equal if a_i=a_j and b_i=b_j at the same time.The banquet organizers estimate the variety of n dishes as follows. The variety of a set of dishes is equal to the number of different dishes in it. The less variety is, the better.In order to reduce the variety, a taster was invited. He will eat exactly m_i grams of food from each dish. For each dish, the taster determines separately how much fish and how much meat he will eat. The only condition is that he will eat exactly m_i grams of the i-th dish in total.Determine how much of what type of food the taster should eat from each dish so that the value of variety is the minimum possible. If there are several correct answers, you may output any of them.InputThe first line of input data contains an integer t (1 \leq t \leq 10^4) — the number of test cases.Each test case's description is preceded by a blank line. Next comes a line that contains an integer n (1 \leq n \leq 2 \cdot 10^5) — the number of dishes. Then follows n lines, i-th of which contains three integers a_i, b_i and m_i (0 \leq a_i, b_i \le 10^6; 0 \le m_i \le a_i+b_i) — the mass of fish in i-th dish, the mass of meat in i-th dish and how many grams in total the taster should eat in i-th dish.The sum of all n values for all input data sets in the test does not exceed 2 \cdot 10^5.OutputFor each test case, print on the first line the minimum value of variety that can be achieved by eating exactly m_i grams of food (for all i from 1 to n) from a dish i.Then print n lines that describe a way to do this: the i-th line should contain two integers x_i and y_i (0 \leq x_i \leq a_i; 0 \leq y_i \leq b_i; x_i+y_i=m_i), where x_i is how many grams of fish the taster should eat from i-th dish, and y_i is how many grams of meat.If there are several ways to achieve a minimum balance, print any of them.ExampleInput
5
3
10 10 2
9 9 0
10 9 1
2
3 4 1
5 1 2
3
7 2 5
6 5 4
5 5 6
1
13 42 50
5
5 7 12
3 1 4
7 3 7
0 0 0
4 1 5
Output
1
1 1
0 0
1 0
2
0 1
1 1
2
3 2
0 4
1 5
1
8 42
2
5 7
3 1
4 3
0 0
4 1
| 5
3
10 10 2
9 9 0
10 9 1
2
3 4 1
5 1 2
3
7 2 5
6 5 4
5 5 6
1
13 42 50
5
5 7 12
3 1 4
7 3 7
0 0 0
4 1 5
| 1 1 1 0 0 1 0 2 0 1 1 1 2 3 2 0 4 1 5 1 8 42 2 5 7 3 1 4 3 0 0 4 1 | 3 seconds | 256 megabytes | ['greedy', 'sortings', 'two pointers', '*2200'] |
G. Banquet Preparations 1time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA known chef has prepared n dishes: the i-th dish consists of a_i grams of fish and b_i grams of meat. The banquet organizers estimate the balance of n dishes as follows. The balance is equal to the absolute value of the difference between the total mass of fish and the total mass of meat.Technically, the balance equals to \left|\sum\limits_{i=1}^n a_i - \sum\limits_{i=1}^n b_i\right|. The smaller the balance, the better.In order to improve the balance, a taster was invited. He will eat exactly m grams of food from each dish. For each dish, the taster determines separately how much fish and how much meat he will eat. The only condition is that he should eat exactly m grams of each dish in total.Determine how much of what type of food the taster should eat from each dish so that the value of the balance is as minimal as possible. If there are several correct answers, you may choose any of them.InputThe first line of input data contains an integer t (1 \leq t \leq 10^4) — the number of the test cases.Each test case's description is preceded by a blank line. Next comes a line that contains integers n and m (1 \leq n \leq 2 \cdot 10^5; 0 \leq m \leq 10^6). The next n lines describe dishes, the i-th of them contains a pair of integers a_i and b_i (0 \leq a_i, b_i \le 10^6) — the masses of fish and meat in the i-th dish.It is guaranteed that it is possible to eat m grams of food from each dish. In other words, m \leq a_i+b_i for all i from 1 to n inclusive.The sum of all n values over all test cases in the test does not exceed 2 \cdot 10^5.OutputFor each test case, print on the first line the minimal balance value that can be achieved by eating exactly m grams of food from each dish.Then print n lines that describe a way to do this: the i-th line should contain two integers x_i and y_i (0 \leq x_i \leq a_i; 0 \leq y_i \leq b_i; x_i+y_i=m), where x_i is how many grams of fish taster should eat from the i-th meal and y_i is how many grams of meat.If there are several ways to achieve a minimal balance, find any of them.ExampleInput
8
1 5
3 4
1 6
3 4
2 2
1 3
4 2
2 4
1 3
1 7
3 6
1 7
1 8
1 9
3 6
1 8
1 9
30 10
3 4
3 1
3 2
4 1
5 4
0 7
6 4
0 8
4 1
5 3
Output
0
2 3
1
3 3
0
1 1
1 1
2
1 3
0 4
3
0 6
0 6
0 6
7
1 5
1 5
6 0
0
3 1
3 1
3 1
0
0 4
2 2
0 4
3 1
1 3
| 8
1 5
3 4
1 6
3 4
2 2
1 3
4 2
2 4
1 3
1 7
3 6
1 7
1 8
1 9
3 6
1 8
1 9
30 10
3 4
3 1
3 2
4 1
5 4
0 7
6 4
0 8
4 1
5 3
| 0 2 3 1 3 3 0 1 1 1 1 2 1 3 0 4 3 0 6 0 6 0 6 7 1 5 1 5 6 0 0 3 1 3 1 3 1 0 0 4 2 2 0 4 3 1 1 3 | 2 seconds | 256 megabytes | ['greedy', '*2200'] |
F. Robot on the Board 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe robot is located on a checkered rectangular board of size n \times m (n rows, m columns). The rows in the board are numbered from 1 to n from top to bottom, and the columns — from 1 to m from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.Each cell has one of the symbols 'L', 'R', 'D' or 'U' written on it, indicating the direction in which the robot will move when it gets in that cell — left, right, down or up, respectively.The robot can start its movement in any cell. He then moves to the adjacent square in the direction indicated on the current square in one move. If the robot moves beyond the edge of the board, it falls and breaks. If the robot appears in the cell it already visited before, it breaks (it stops and doesn't move anymore). Robot can choose any cell as the starting cell. Its goal is to make the maximum number of steps before it breaks or stops.Determine from which square the robot should start its movement in order to execute as many commands as possible. A command is considered successfully completed if the robot has moved from the square on which that command was written (it does not matter whether to another square or beyond the edge of the board).InputThe first line contains an integer t (1 \le t \le 10000) — the number of test cases in the test.Each test case's description is preceded by a blank line. Next is a line that contains integers n and m (1 \le n \le 2000; 1 \le m \le 2000) — the height and width of the board. This line followed by n lines, the i-th of which describes the i-th line of the board. Each of them is exactly m letters long and consists of symbols 'L', 'R', 'D' and 'U'.It is guaranteed that the sum of sizes of all boards in the input does not exceed 4\cdot10^6.OutputFor each test case, output three integers r, c and d (1 \le r \le n; 1 \le c \le m; d \ge 0), which denote that the robot should start moving from cell (r, c) to make the maximum number of moves d. If there are several answers, output any of them.ExampleInput
7
1 1
R
1 3
RRL
2 2
DL
RU
2 2
UD
RU
3 2
DL
UL
RU
4 4
RRRD
RUUD
URUD
ULLR
4 4
DDLU
RDDU
UUUU
RDLD
Output
1 1 1
1 1 3
1 1 4
2 1 3
3 1 5
4 3 12
1 1 4
| 7
1 1
R
1 3
RRL
2 2
DL
RU
2 2
UD
RU
3 2
DL
UL
RU
4 4
RRRD
RUUD
URUD
ULLR
4 4
DDLU
RDDU
UUUU
RDLD
| 1 1 1 1 1 3 1 1 4 2 1 3 3 1 5 4 3 12 1 1 4 | 2 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'graphs', 'implementation', '*2300'] |
E. Robot on the Board 1time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe robot is located on a checkered rectangular board of size n \times m (n rows, m columns). The rows in the board are numbered from 1 to n from top to bottom, and the columns — from 1 to m from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands s executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in s. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board 3 \times 3, if the robot starts a sequence of actions s="RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell (2, 1) (second row, first column) then all commands will be executed successfully and the robot will stop at the cell (1, 2) (first row, second column). The robot starts from cell (2, 1) (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell (1, 2) (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.InputThe first line contains an integer t (1 \leq t \leq 10^4) — the number of test cases.The next 2t lines contain descriptions of the test cases.In the description of each test case, the first line contains two integers n and m (1 \leq n, m \leq 10^6) — the height and width of the field that the robot is located on. The second line of the description is a string s consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from 1 to 10^6 commands.It is guaranteed that the total length of s over all test cases does not exceed 10^6.OutputPrint t lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers r (1 \leq r \leq n) and c (1 \leq c \leq m), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible.If there are several such cells, you may output any of them.ExampleInput
4
1 1
L
1 2
L
3 3
RRDLUU
4 3
LUURRDDLLLUU
Output
1 1
1 2
2 1
3 2
| 4
1 1
L
1 2
L
3 3
RRDLUU
4 3
LUURRDDLLLUU
| 1 1 1 2 2 1 3 2 | 2 seconds | 256 megabytes | ['implementation', '*1600'] |
D. Blue-Red Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of integers a of length n. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by 1; or you can select any red element and increase its value by 1. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make 0 or more steps such that the resulting array is a permutation of numbers from 1 to n?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array a contains in some order all numbers from 1 to n (inclusive), each exactly once.InputThe first line contains an integer t (1 \leq t \leq 10^4) — the number of input data sets in the test.The description of each set of input data consists of three lines. The first line contains an integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the original array a. The second line contains n integers a_1, a_2, ..., a_n (-10^9 \leq a_i \leq 10^9) — the array elements themselves.The third line has length n and consists exclusively of the letters 'B' and/or 'R': ith character is 'B' if a_i is colored blue, and is 'R' if colored red.It is guaranteed that the sum of n over all input sets does not exceed 2 \cdot 10^5.OutputPrint t lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise.You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).ExampleInput
8
4
1 2 5 2
BRBR
2
1 1
BB
5
3 1 4 2 5
RBRRB
5
3 1 3 1 3
RBRRB
5
5 1 5 1 5
RBRRB
4
2 2 2 2
BRBR
2
1 -2
BR
4
-2 -1 4 0
RRRR
Output
YES
NO
YES
YES
NO
YES
YES
YES
NoteIn the first test case of the example, the following sequence of moves can be performed: choose i=3, element a_3=5 is blue, so we decrease it, we get a=[1,2,4,2]; choose i=2, element a_2=2 is red, so we increase it, we get a=[1,3,4,2]; choose i=3, element a_3=4 is blue, so we decrease it, we get a=[1,3,3,2]; choose i=2, element a_2=2 is red, so we increase it, we get a=[1,4,3,2]. We got that a is a permutation. Hence the answer is YES. | 8
4
1 2 5 2
BRBR
2
1 1
BB
5
3 1 4 2 5
RBRRB
5
3 1 3 1 3
RBRRB
5
5 1 5 1 5
RBRRB
4
2 2 2 2
BRBR
2
1 -2
BR
4
-2 -1 4 0
RRRR
| YES NO YES YES NO YES YES YES | 1 second | 256 megabytes | ['greedy', 'math', 'sortings', '*1300'] |
C. Minimum Extractiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYelisey has an array a of n integers.If a has length strictly greater than 1, then Yelisei can apply an operation called minimum extraction to it: First, Yelisei finds the minimal number m in the array. If there are several identical minima, Yelisey can choose any of them. Then the selected minimal element is removed from the array. After that, m is subtracted from each remaining element. Thus, after each operation, the length of the array is reduced by 1.For example, if a = [1, 6, -4, -2, -4], then the minimum element in it is a_3 = -4, which means that after this operation the array will be equal to a=[1 {- (-4)}, 6 {- (-4)}, -2 {- (-4)}, -4 {- (-4)}] = [5, 10, 2, 0].Since Yelisey likes big numbers, he wants the numbers in the array a to be as big as possible.Formally speaking, he wants to make the minimum of the numbers in array a to be maximal possible (i.e. he want to maximize a minimum). To do this, Yelisey can apply the minimum extraction operation to the array as many times as he wants (possibly, zero). Note that the operation cannot be applied to an array of length 1.Help him find what maximal value can the minimal element of the array have after applying several (possibly, zero) minimum extraction operations to the array.InputThe first line contains an integer t (1 \leq t \leq 10^4) — the number of test cases.The next 2t lines contain descriptions of the test cases.In the description of each test case, the first line contains an integer n (1 \leq n \leq 2 \cdot 10^5) — the original length of the array a. The second line of the description lists n space-separated integers a_i (-10^9 \leq a_i \leq 10^9) — 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 of them containing the answer to the corresponding test case. The answer to the test case is a single integer — the maximal possible minimum in a, which can be obtained by several applications of the described operation to it.ExampleInput
8
1
10
2
0 0
3
-1 2 0
4
2 10 1 7
2
2 3
5
3 2 -4 -2 0
2
-1 1
1
-2
Output
10
0
2
5
2
2
2
-2
NoteIn the first example test case, the original length of the array n = 1. Therefore minimum extraction cannot be applied to it. Thus, the array remains unchanged and the answer is a_1 = 10.In the second set of input data, the array will always consist only of zeros.In the third set, the array will be changing as follows: [\color{blue}{-1}, 2, 0] \to [3, \color{blue}{1}] \to [\color{blue}{2}]. The minimum elements are highlighted with \color{blue}{\text{blue}}. The maximal one is 2.In the fourth set, the array will be modified as [2, 10, \color{blue}{1}, 7] \to [\color{blue}{1}, 9, 6] \to [8, \color{blue}{5}] \to [\color{blue}{3}]. Similarly, the maximum of the minimum elements is 5. | 8
1
10
2
0 0
3
-1 2 0
4
2 10 1 7
2
2 3
5
3 2 -4 -2 0
2
-1 1
1
-2
| 10 0 2 5 2 2 2 -2 | 1 second | 256 megabytes | ['brute force', 'sortings', '*1000'] |
B. Odd Grasshoppertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe grasshopper is located on the numeric axis at the point with coordinate x_0.Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate x with a distance d to the left moves the grasshopper to a point with a coordinate x - d, while jumping to the right moves him to a point with a coordinate x + d.The grasshopper is very fond of positive integers, so for each integer i starting with 1 the following holds: exactly i minutes after the start he makes a jump with a distance of exactly i. So, in the first minutes he jumps by 1, then by 2, and so on.The direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an even coordinate, the grasshopper jumps to the left, otherwise he jumps to the right.For example, if after 18 consecutive jumps he arrives at the point with a coordinate 7, he will jump by a distance of 19 to the right, since 7 is an odd number, and will end up at a point 7 + 19 = 26. Since 26 is an even number, the next jump the grasshopper will make to the left by a distance of 20, and it will move him to the point 26 - 20 = 6.Find exactly which point the grasshopper will be at after exactly n jumps.InputThe first line of input contains an integer t (1 \leq t \leq 10^4) — the number of test cases.Each of the following t lines contains two integers x_0 (-10^{14} \leq x_0 \leq 10^{14}) and n (0 \leq n \leq 10^{14}) — the coordinate of the grasshopper's initial position and the number of jumps.OutputPrint exactly t lines. On the i-th line print one integer — the answer to the i-th test case — the coordinate of the point the grasshopper will be at after making n jumps from the point x_0.ExampleInput
9
0 1
0 2
10 10
10 99
177 13
10000000000 987654321
-433494437 87178291199
1 0
-1 1
Output
-1
1
11
110
190
9012345679
-87611785637
1
0
NoteThe first two test cases in the example correspond to the first two jumps from the point x_0 = 0. Since 0 is an even number, the first jump of length 1 is made to the left, and the grasshopper ends up at the point 0 - 1 = -1.Then, since -1 is an odd number, a jump of length 2 is made to the right, bringing the grasshopper to the point with coordinate -1 + 2 = 1. | 9
0 1
0 2
10 10
10 99
177 13
10000000000 987654321
-433494437 87178291199
1 0
-1 1
| -1 1 11 110 190 9012345679 -87611785637 1 0 | 1 second | 256 megabytes | ['math', '*900'] |
A. Linear Keyboardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a keyboard that consists of 26 keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.You have to type the word s on this keyboard. It also consists only of lowercase Latin letters.To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions 8, 5, 12 and 15, respectively. Therefore, it will take |5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13 units of time to type the word "hello". Determine how long it will take to print the word s.InputThe first line contains an integer t (1 \leq t \leq 1000) — the number of test cases.The next 2t lines contain descriptions of the test cases.The first line of a description contains a keyboard — a string of length 26, which consists only of lowercase Latin letters. Each of the letters from 'a' to 'z' appears exactly once on the keyboard.The second line of the description contains the word s. The word has a length from 1 to 50 letters inclusive and consists of lowercase Latin letters.OutputPrint t lines, each line containing the answer to the corresponding test case. The answer to the test case is the minimal time it takes to type the word s on the given keyboard.ExampleInput
5
abcdefghijklmnopqrstuvwxyz
hello
abcdefghijklmnopqrstuvwxyz
i
abcdefghijklmnopqrstuvwxyz
codeforces
qwertyuiopasdfghjklzxcvbnm
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
qwertyuiopasdfghjklzxcvbnm
abacaba
Output
13
0
68
0
74
| 5
abcdefghijklmnopqrstuvwxyz
hello
abcdefghijklmnopqrstuvwxyz
i
abcdefghijklmnopqrstuvwxyz
codeforces
qwertyuiopasdfghjklzxcvbnm
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
qwertyuiopasdfghjklzxcvbnm
abacaba
| 13 0 68 0 74 | 1 second | 256 megabytes | ['implementation', 'strings', '*800'] |
F. Tree Queriestime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices. Recall that a tree is an undirected connected acyclic graph. The given tree is rooted at the vertex 1.You have to process q queries. In each query, you are given a vertex of the tree v and an integer k.To process a query, you may delete any vertices from the tree in any order, except for the root and the vertex v. When a vertex is deleted, its children become the children of its parent. You have to process a query in such a way that maximizes the value of c(v) - m \cdot k (where c(v) is the resulting number of children of the vertex v, and m is the number of vertices you have deleted). Print the maximum possible value you can obtain.The queries are independent: the changes you make to the tree while processing a query don't affect the tree in other queries.InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of vertices in the tree.Then n-1 lines follow, the i-th of them contains two integers x_i and y_i (1 \le x_i, y_i \le n; x_i \ne y_i) — the endpoints of the i-th edge. These edges form a tree.The next line contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries.Then q lines follow, the j-th of them contains two integers v_j and k_j (1 \le v_j \le n; 0 \le k_j \le 2 \cdot 10^5) — the parameters of the j-th query.OutputFor each query, print one integer — the maximum value of c(v) - m \cdot k you can achieve.ExampleInput
8
6 7
3 2
8 3
5 7
7 4
7 1
7 3
6
1 0
1 2
1 3
7 1
5 0
7 200000
Output
5
2
1
4
0
4
NoteThe tree in the first example is shown in the following picture: Answers to the queries are obtained as follows: v=1,k=0: you can delete vertices 7 and 3, so the vertex 1 has 5 children (vertices 2, 4, 5, 6, and 8), and the score is 5 - 2 \cdot 0 = 5; v=1,k=2: you can delete the vertex 7, so the vertex 1 has 4 children (vertices 3, 4, 5, and 6), and the score is 4 - 1 \cdot 2 = 2. v=1,k=3: you shouldn't delete any vertices, so the vertex 1 has only one child (vertex 7), and the score is 1 - 0 \cdot 3 = 1; v=7,k=1: you can delete the vertex 3, so the vertex 7 has 5 children (vertices 2, 4, 5, 6, and 8), and the score is 5 - 1 \cdot 1 = 4; v=5,k=0: no matter what you do, the vertex 5 will have no children, so the score is 0; v=7,k=200000: you shouldn't delete any vertices, so the vertex 7 has 4 children (vertices 3, 4, 5, and 6), and the score is 4 - 0 \cdot 200000 = 4. | 8
6 7
3 2
8 3
5 7
7 4
7 1
7 3
6
1 0
1 2
1 3
7 1
5 0
7 200000
| 5 2 1 4 0 4 | 6 seconds | 512 megabytes | ['brute force', 'dp', 'trees', '*2800'] |
E. Arenatime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n heroes fighting in the arena. Initially, the i-th hero has a_i health points.The fight in the arena takes place in several rounds. At the beginning of each round, each alive hero deals 1 damage to all other heroes. Hits of all heroes occur simultaneously. Heroes whose health is less than 1 at the end of the round are considered killed.If exactly 1 hero remains alive after a certain round, then he is declared the winner. Otherwise, there is no winner.Your task is to calculate the number of ways to choose the initial health points for each hero a_i, where 1 \le a_i \le x, so that there is no winner of the fight. The number of ways can be very large, so print it modulo 998244353. Two ways are considered different if at least one hero has a different amount of health. For example, [1, 2, 1] and [2, 1, 1] are different.InputThe only line contains two integers n and x (2 \le n \le 500; 1 \le x \le 500).OutputPrint one integer — the number of ways to choose the initial health points for each hero a_i, where 1 \le a_i \le x, so that there is no winner of the fight, taken modulo 998244353. ExamplesInput
2 5
Output
5
Input
3 3
Output
15
Input
5 4
Output
1024
Input
13 37
Output
976890680
| 2 5
| 5 | 3 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', '*2100'] |
D. Red-Blue Matrixtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix, consisting of n rows and m columns. The j-th cell of the i-th row contains an integer a_{ij}.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer k (1 \le k < m) and cut the colored matrix in such a way that the first k columns become a separate matrix (the left matrix) and the last m-k columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Then the descriptions of t testcases follow.The first line of each testcase contains two integers n and m (2 \le n, m \le 5 \cdot 10^5; n \cdot m \le 10^6) — the number of rows and the number of columns in the matrix, respectively.The i-th of the next n lines contains m integers a_{i1}, a_{i2}, \dots, a_{im} (1 \le a_{ij} \le 10^6).The sum of n \cdot m over all testcases doesn't exceed 10^6.OutputFor each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO".Otherwise, first, print "YES". Then a string, consisting of n characters: the i-th character should be 'R' if the i-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer k (1 \le k < m) — the number of columns from the left that are cut.ExampleInput
3
5 5
1 5 8 8 7
5 2 1 4 3
1 6 9 7 5
9 3 3 3 2
1 7 9 9 8
3 3
8 9 8
1 5 3
7 5 7
2 6
3 3 3 2 2 2
1 1 1 4 4 4
Output
YES
BRBRB 1
NO
YES
RB 3
NoteThe coloring and the cut for the first testcase: | 3
5 5
1 5 8 8 7
5 2 1 4 3
1 6 9 7 5
9 3 3 3 2
1 7 9 9 8
3 3
8 9 8
1 5 3
7 5 7
2 6
3 3 3 2 2 2
1 1 1 4 4 4
| YES BRBRB 1 NO YES RB 3 | 4 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', 'sortings', '*2400'] |
C. Banknotestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Berland, n different types of banknotes are used. Banknotes of the i-th type have denomination 10^{a_i} burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly 1.Let's denote f(s) as the minimum number of banknotes required to represent exactly s burles. For example, if the denominations of banknotes used in Berland are 1, 10 and 100, then f(59) = 14: 9 banknotes with denomination of 1 burle and 5 banknotes with denomination of 10 burles can be used to represent exactly 9 \cdot 1 + 5 \cdot 10 = 59 burles, and there's no way to do it with fewer banknotes.For a given integer k, find the minimum positive number of burles s that cannot be represented with k or fewer banknotes (that is, f(s) > k).InputThe first line contains a single integer t (1 \le t \le 10^4) — number of test cases.The first line of each test case contains two integers n and k (1 \le n \le 10; 1 \le k \le 10^9).The next line contains n integers a_1, a_2, \dots, a_n (0 = a_1 < a_2 < \dots < a_n \le 9).OutputFor each test case, print one integer — the minimum positive number of burles s that cannot be represented with k or fewer banknotes.ExampleInput
4
3 13
0 1 2
2 777
0 4
3 255
0 1 3
10 1000000000
0 1 2 3 4 5 6 7 8 9
Output
59
778
148999
999999920999999999
| 4
3 13
0 1 2
2 777
0 4
3 255
0 1 3
10 1000000000
0 1 2 3 4 5 6 7 8 9
| 59 778 148999 999999920999999999 | 2 seconds | 256 megabytes | ['greedy', 'number theory', '*1400'] |
B. Update Filestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland State University has received a new update for the operating system. Initially it is installed only on the 1-st computer.Update files should be copied to all n computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all n computers if there are only k patch cables in Berland State University.InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of test cases.Each test case consists of a single line that contains two integers n and k (1 \le k \le n \le 10^{18}) — the number of computers and the number of patch cables.OutputFor each test case print one integer — the minimum number of hours required to copy the update files to all n computers.ExampleInput
4
8 3
6 6
7 1
1 1
Output
4
3
6
0
NoteLet's consider the test cases of the example: n=8, k=3: during the first hour, we copy the update files from the computer 1 to the computer 2; during the second hour, we copy the update files from the computer 1 to the computer 3, and from the computer 2 to the computer 4; during the third hour, we copy the update files from the computer 1 to the computer 5, from the computer 2 to the computer 6, and from the computer 3 to the computer 7; during the fourth hour, we copy the update files from the computer 2 to the computer 8. n=6, k=6: during the first hour, we copy the update files from the computer 1 to the computer 2; during the second hour, we copy the update files from the computer 1 to the computer 3, and from the computer 2 to the computer 4; during the third hour, we copy the update files from the computer 1 to the computer 5, and from the computer 2 to the computer 6. n=7, k=1: during the first hour, we copy the update files from the computer 1 to the computer 2; during the second hour, we copy the update files from the computer 1 to the computer 3; during the third hour, we copy the update files from the computer 1 to the computer 4; during the fourth hour, we copy the update files from the computer 4 to the computer 5; during the fifth hour, we copy the update files from the computer 4 to the computer 6; during the sixth hour, we copy the update files from the computer 3 to the computer 7. | 4
8 3
6 6
7 1
1 1
| 4 3 6 0 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', '*1100'] |
A. AB Balancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n consisting of characters a and/or b.Let \operatorname{AB}(s) be the number of occurrences of string ab in s as a substring. Analogically, \operatorname{BA}(s) is the number of occurrences of ba in s as a substring.In one step, you can choose any index i and replace s_i with character a or b.What is the minimum number of steps you need to make to achieve \operatorname{AB}(s) = \operatorname{BA}(s)?Reminder:The number of occurrences of string d in s as substring is the number of indices i (1 \le i \le |s| - |d| + 1) such that substring s_i s_{i + 1} \dots s_{i + |d| - 1} is equal to d. For example, \operatorname{AB}(aabbbabaa) = 2 since there are two indices i: i = 2 where aabbbabaa and i = 6 where aabbbabaa.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 and only line of each test case contains a single string s (1 \le |s| \le 100, where |s| is the length of the string s), consisting only of characters a and/or b.OutputFor each test case, print the resulting string s with \operatorname{AB}(s) = \operatorname{BA}(s) you'll get making the minimum number of steps.If there are multiple answers, print any of them.ExampleInput
4
b
aabbbabaa
abbb
abbaab
Output
b
aabbbabaa
bbbb
abbaaaNoteIn the first test case, both \operatorname{AB}(s) = 0 and \operatorname{BA}(s) = 0 (there are no occurrences of ab (ba) in b), so can leave s untouched.In the second test case, \operatorname{AB}(s) = 2 and \operatorname{BA}(s) = 2, so you can leave s untouched. In the third test case, \operatorname{AB}(s) = 1 and \operatorname{BA}(s) = 0. For example, we can change s_1 to b and make both values zero.In the fourth test case, \operatorname{AB}(s) = 2 and \operatorname{BA}(s) = 1. For example, we can change s_6 to a and make both values equal to 1. | 4
b
aabbbabaa
abbb
abbaab
| b aabbbabaa bbbb abbaaa | 2 seconds | 256 megabytes | ['strings', '*900'] |
F. PalindORmetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn integer array a of length n is said to be a PalindORme if (a_{1} | a_{2} | \ldots | a_{i}) = (a_{{n - i + 1}} | \ldots | a_{{n - 1}} | a_{n}) for all 1 \leq i \leq n, where | denotes the bitwise OR operation.An integer array a of length n is considered to be good if its elements can be rearranged to form a PalindORme. Formally, array a is good if there exists a permutation p_1, p_2, \ldots p_n (an array where each integer from 1 to n appears exactly once) for which a_{p_1}, a_{p_2}, \ldots a_{p_n} is a PalindORme.Find the number of good arrays of length n, consisting only of integers in the range [0, 2^{k} - 1], and print it modulo some prime m.Two arrays a_1, a_2, \ldots, a_n and b_1, b_2, \ldots, b_n are considered to be different if there exists any i (1 \leq i \leq n) such that a_i \ne b_i.InputThe first and only line of the input contains three integers n, k and m (1 \leq n,k \leq 80, 10^8 \lt m \lt 10^9). It is guaranteed that m is prime.OutputPrint a single integer — the number of good arrays modulo m.ExamplesInput
1 1 998244353
Output
2
Input
3 2 999999733
Output
40
Input
7 3 796735397
Output
1871528
Input
2 46 606559127
Output
177013
NoteIn the first sample, both the possible arrays [0] and [1] are good.In the second sample, some examples of good arrays are: [2, 1, 2] because it is already PalindORme. [1, 1, 0] because it can rearranged to [1, 0, 1] which is PalindORmeNote that [1, 1, 0], [1, 0, 1] and [0, 1, 1] are all good arrays and are considered to be different according to the definition in the statement.In the third sample, an example of a good array is [1, 0, 1, 4, 2, 5, 4]. It can be rearranged to an array b = [1, 5, 0, 2, 4, 4, 1] which is a PalindORme because: \mathrm{OR}(1, 1) = \mathrm{OR}(7, 7) = 1 \mathrm{OR}(1, 2) = \mathrm{OR}(6, 7) = 5 \mathrm{OR}(1, 3) = \mathrm{OR}(5, 7) = 5 \mathrm{OR}(1, 4) = \mathrm{OR}(4, 7) = 7 \mathrm{OR}(1, 5) = \mathrm{OR}(3, 7) = 7 \mathrm{OR}(1, 6) = \mathrm{OR}(2, 7) = 7 \mathrm{OR}(1, 7) = \mathrm{OR}(1, 7) = 7Here \mathrm{OR}(l, r) denotes b_{l} | b_{l+1} | \ldots | b_{r} | 1 1 998244353
| 2 | 4 seconds | 256 megabytes | ['combinatorics', 'dp', '*2900'] |
E. Array Equalizertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJeevan has two arrays a and b of size n. He is fond of performing weird operations on arrays. This time, he comes up with two types of operations: Choose any i (1 \le i \le n) and increment a_j by 1 for every j which is a multiple of i and 1 \le j \le n. Choose any i (1 \le i \le n) and decrement a_j by 1 for every j which is a multiple of i and 1 \le j \le n. He wants to convert array a into an array b using the minimum total number of operations. However, Jeevan seems to have forgotten the value of b_1. So he makes some guesses. He will ask you q questions corresponding to his q guesses, the i-th of which is of the form: If b_1 = x_i, what is the minimum number of operations required to convert a to b? Help him by answering each question.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^{5}) — the size of arrays a and b.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^6).The third line contains n integers b_1, b_2, ..., b_n (1 \le b_i \le 10^6 for i \neq 1; b_1 = -1, representing that the value of b_1 is unknown).The fourth line contains a single integer q (1 \le q \le 2 \cdot 10^{5}) — the number of questions.Each of the following q lines contains a single integer x_i (1 \le x_i \le 10^6) — representing the i-th question.OutputOutput q integers — the answers to each of his q questions.ExamplesInput
2
3 7
-1 5
3
1
4
3
Output
2
4
2
Input
6
2 5 4 1 3 6
-1 4 6 2 3 5
3
1
8
4
Output
10
29
9
NoteConsider the first test case. b_1 = 1: We need to convert [3, 7] \rightarrow [1, 5]. We can perform the following operations:[3, 7] \xrightarrow[\text{decrease}]{\text{i = 1}} [2, 6] \xrightarrow[\text{decrease}]{\text{i = 1}} [1, 5]Hence the answer is 2. b_1 = 4: We need to convert [3, 7] \rightarrow [4, 5]. We can perform the following operations: [3, 7] \xrightarrow[\text{decrease}]{\text{i = 2}} [3, 6] \xrightarrow[\text{decrease}]{\text{i = 2}} [3, 5] \xrightarrow[\text{increase}]{\text{i = 1}} [4, 6] \xrightarrow[\text{decrease}]{\text{i = 2}} [4, 5]Hence the answer is 4. b_1 = 3: We need to convert [3, 7] \rightarrow [3, 5]. We can perform the following operations:[3, 7] \xrightarrow[\text{decrease}]{\text{i = 2}} [3, 6] \xrightarrow[\text{decrease}]{\text{i = 2}} [3, 5]Hence the answer is 2. | 2
3 7
-1 5
3
1
4
3
| 2 4 2 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'implementation', 'math', 'number theory', 'sortings', 'two pointers', '*2400'] |
D. Treelabelingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEikooc and Sushi play a game.The game is played on a tree having n nodes numbered 1 to n. Recall that a tree having n nodes is an undirected, connected graph with n-1 edges.They take turns alternately moving a token on the tree. Eikooc makes the first move, placing the token on any node of her choice. Sushi makes the next move, followed by Eikooc, followed by Sushi, and so on. In each turn after the first, a player must move the token to a node u such that u is adjacent to the node v the token is currently on u has not been visited before u \oplus v \leq min(u, v) Here x \oplus y denotes the bitwise XOR operation on integers x and y.Both the players play optimally. The player who is unable to make a move loses.The following are examples which demonstrate the rules of the game. Suppose Eikooc starts the game by placing the token at node 4. Sushi then moves the token to node 6, which is unvisited and adjacent to 4. It also holds that 6 \oplus 4 = 2 \leq min(6, 4). In the next turn, Eikooc moves the token to node 5, which is unvisited and adjacent to 6. It holds that 5 \oplus 6 = 3 \leq min(5, 6). Sushi has no more moves to play, so she loses. Suppose Eikooc starts the game by placing the token at node 3. Sushi moves the token to node 2, which is unvisited and adjacent to 3. It also holds that 3 \oplus 2 = 1 \leq min(3, 2). Eikooc cannot move the token to node 6 since 6 \oplus 2 = 4 \nleq min(6, 2). Since Eikooc has no moves to play, she loses. Before the game begins, Eikooc decides to sneakily relabel the nodes of the tree in her favour. Formally, a relabeling is a permutation p of length n (sequence of n integers wherein each integer from 1 to n occurs exactly once) where p_i denotes the new numbering of node i.She wants to maximize the number of nodes she can choose in the first turn which will guarantee her a win. Help Eikooc find any relabeling which will help her do so. InputThe first line contains a single integer t~(1 \le t \le 10^5) — the number of test cases. The description of each test case is as follows.The first line of each test case contains an integer n~(1 \le n \le 2 \cdot 10^5) — the number of nodes in the tree.The next n-1 lines contain two integers u and v (1 \le u, v \le n; u \neq v) — denoting an edge between nodes u and v.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print any suitable relabeling — a permutation of length n which maximizes the number of nodes that can be chosen in the first turn that guarantee a win for Eikooc. If there are multiple such relabelings, you may print any of them.ExampleInput
3
1
2
1 2
3
1 2
1 3
Output
1
2 1
1 2 3
NoteIn the first test case, Eikooc has only one choice. Sushi will have no moves to play after Eikooc chooses this node and Eikooc will win.In the second test case, 1 \oplus 2 = 3 \nleq min(1, 2). Hence, after Eikooc picks either of the nodes, Sushi will have no moves to play and Eikooc will win. Both \{1, 2\} and \{2, 1\} are optimal relabelings. | 3
1
2
1 2
3
1 2
1 3
| 1 2 1 1 2 3 | 2 seconds | 256 megabytes | ['bitmasks', 'constructive algorithms', 'dfs and similar', 'games', 'greedy', 'implementation', 'trees', '*2100'] |
C. Dominant Charactertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAshish has a string s of length n containing only characters 'a', 'b' and 'c'.He wants to find the length of the smallest substring, which satisfies the following conditions: Length of the substring is at least 2 'a' occurs strictly more times in this substring than 'b' 'a' occurs strictly more times in this substring than 'c' Ashish is busy planning his next Codeforces round. Help him solve the problem.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.InputThe first line contains a single integer t (1 \le t \le 10^{5}) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2 \le n \le 10^{6}) — the length of the string s.The second line of each test case contains a string s consisting only of characters 'a', 'b' and 'c'.It is guaranteed that the sum of n over all test cases does not exceed 10^{6}.OutputFor each test case, output the length of the smallest substring which satisfies the given conditions or print -1 if there is no such substring.ExampleInput
3
2
aa
5
cbabb
8
cacabccc
Output
2
-1
3
NoteConsider the first test case. In the substring "aa", 'a' occurs twice, while 'b' and 'c' occur zero times. Since 'a' occurs strictly more times than 'b' and 'c', the substring "aa" satisfies the condition and the answer is 2. The substring "a" also satisfies this condition, however its length is not at least 2.In the second test case, it can be shown that in none of the substrings of "cbabb" does 'a' occur strictly more times than 'b' and 'c' each.In the third test case, "cacabccc", the length of the smallest substring that satisfies the conditions is 3. | 3
2
aa
5
cbabb
8
cacabccc
| 2 -1 3 | 2 seconds | 256 megabytes | ['brute force', 'greedy', 'implementation', 'strings', '*1400'] |
B. Reverse Sorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAshish has a binary string s of length n that he wants to sort in non-decreasing order.He can perform the following operation: Choose a subsequence of any length such that its elements are in non-increasing order. Formally, choose any k such that 1 \leq k \leq n and any sequence of k indices 1 \le i_1 \lt i_2 \lt \ldots \lt i_k \le n such that s_{i_1} \ge s_{i_2} \ge \ldots \ge s_{i_k}. Reverse this subsequence in-place. Formally, swap s_{i_1} with s_{i_k}, swap s_{i_2} with s_{i_{k-1}}, \ldots and swap s_{i_{\lfloor k/2 \rfloor}} with s_{i_{\lceil k/2 \rceil + 1}} (Here \lfloor x \rfloor denotes the largest integer not exceeding x, and \lceil x \rceil denotes the smallest integer not less than x) Find the minimum number of operations required to sort the string in non-decreasing order. It can be proven that it is always possible to sort the given binary string in at most n operations.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 1000) — the length of the binary string s.The second line of each test case contains a binary string s of length n containing only 0s and 1s.It is guaranteed that the sum of n over all test cases does not exceed 1000.OutputFor each test case output the following: The minimum number of operations m in the first line (0 \le m \le n). Each of the following m lines should be of the form: k i_1 i_2 ... i_{k}, where k is the length and i_1 \lt i_2 \lt ... \lt i_{k} are the indices of the chosen subsequence. For them the conditions from the statement must hold. ExampleInput
3
7
0011111
5
10100
6
001000
Output
0
1
4 1 3 4 5
1
3 3 5 6
NoteIn the first test case, the binary string is already sorted in non-decreasing order.In the second test case, we can perform the following operation: k = 4: choose the indices \{1, 3, 4, 5\}\underline{1} 0 \underline{1} \underline{0} \underline{0} \rightarrow \underline{0} 0 \underline{0} \underline{1} \underline{1} In the third test case, we can perform the following operation: k = 3: choose the indices \{3, 5, 6\}0 0 \underline{1} 0 \underline{0} \underline{0} \rightarrow 0 0 \underline{0} 0 \underline{0} \underline{1} | 3
7
0011111
5
10100
6
001000
| 0 1 4 1 3 4 5 1 3 3 5 6 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*1000'] |
A. A.M. Deviationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA number a_2 is said to be the arithmetic mean of two numbers a_1 and a_3, if the following condition holds: a_1 + a_3 = 2\cdot a_2. We define an arithmetic mean deviation of three numbers a_1, a_2 and a_3 as follows: d(a_1, a_2, a_3) = |a_1 + a_3 - 2 \cdot a_2|.Arithmetic means a lot to Jeevan. He has three numbers a_1, a_2 and a_3 and he wants to minimize the arithmetic mean deviation d(a_1, a_2, a_3). To do so, he can perform the following operation any number of times (possibly zero): Choose i, j from \{1, 2, 3\} such that i \ne j and increment a_i by 1 and decrement a_j by 1 Help Jeevan find out the minimum value of d(a_1, a_2, a_3) that can be obtained after applying the operation any number of times.InputThe first line contains a single integer t (1 \le t \le 5000) — the number of test cases.The first and only line of each test case contains three integers a_1, a_2 and a_3 (1 \le a_1, a_2, a_3 \le 10^{8}).OutputFor each test case, output the minimum value of d(a_1, a_2, a_3) that can be obtained after applying the operation any number of times.ExampleInput
3
3 4 5
2 2 6
1 6 5
Output
0
1
0
NoteNote that after applying a few operations, the values of a_1, a_2 and a_3 may become negative.In the first test case, 4 is already the Arithmetic Mean of 3 and 5.d(3, 4, 5) = |3 + 5 - 2 \cdot 4| = 0In the second test case, we can apply the following operation:(2, 2, 6) \xrightarrow[\text{increment a_2}]{\text{decrement a_1}} (1, 3, 6)d(1, 3, 6) = |1 + 6 - 2 \cdot 3| = 1It can be proven that answer can not be improved any further.In the third test case, we can apply the following operations:(1, 6, 5) \xrightarrow[\text{increment a_3}]{\text{decrement a_2}} (1, 5, 6) \xrightarrow[\text{increment a_1}]{\text{decrement a_2}} (2, 4, 6)d(2, 4, 6) = |2 + 6 - 2 \cdot 4| = 0 | 3
3 4 5
2 2 6
1 6 5
| 0 1 0 | 1 second | 256 megabytes | ['math', 'number theory', '*800'] |
B. XOR Specia-LIS-ttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYouKn0wWho has an integer sequence a_1, a_2, \ldots a_n. Now he will split the sequence a into one or more consecutive subarrays so that each element of a belongs to exactly one subarray. Let k be the number of resulting subarrays, and h_1, h_2, \ldots, h_k be the lengths of the longest increasing subsequences of corresponding subarrays.For example, if we split [2, 5, 3, 1, 4, 3, 2, 2, 5, 1] into [2, 5, 3, 1, 4], [3, 2, 2, 5], [1], then h = [3, 2, 1].YouKn0wWho wonders if it is possible to split the sequence a in such a way that the bitwise XOR of h_1, h_2, \ldots, h_k is equal to 0. You have to tell whether it is possible.The longest increasing subsequence (LIS) of a sequence b_1, b_2, \ldots, b_m is the longest sequence of valid indices i_1, i_2, \ldots, i_k such that i_1 \lt i_2 \lt \ldots \lt i_k and b_{i_1} \lt b_{i_2} \lt \ldots \lt b_{i_k}. For example, the LIS of [2, 5, 3, 3, 5] is [2, 3, 5], which has length 3.An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputThe first line contains a single integer t (1 \le t \le 10\,000) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case, print "YES" (without quotes) if it is possible to split into subarrays in the desired way, print "NO" (without quotes) otherwise. You can print each letter in any register (upper or lower).ExampleInput
4
7
1 3 4 2 2 1 5
3
1 3 4
5
1 3 2 4 2
4
4 3 2 1
Output
YES
NO
YES
YES
NoteIn the first test case, YouKn0wWho can split the sequence in the following way: [1, 3, 4], [2, 2], [1, 5]. This way, the LIS lengths are h = [3, 1, 2], and the bitwise XOR of the LIS lengths is 3 \oplus 1 \oplus 2 = 0.In the second test case, it can be shown that it is impossible to split the sequence into subarrays that will satisfy the condition. | 4
7
1 3 4 2 2 1 5
3
1 3 4
5
1 3 2 4 2
4
4 3 2 1
| YES NO YES YES | 1 second | 256 megabytes | ['*1100'] |
A. Eratime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputShohag has an integer sequence a_1, a_2, \ldots, a_n. He can perform the following operation any number of times (possibly, zero): Select any positive integer k (it can be different in different operations). Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any two elements) and insert k into the sequence at this position. This way, the sequence a changes, and the next operation is performed on this changed sequence. For example, if a=[3,3,4] and he selects k = 2, then after the operation he can obtain one of the sequences [\underline{2},3,3,4], [3,\underline{2},3,4], [3,3,\underline{2},4], or [3,3,4,\underline{2}].Shohag wants this sequence to satisfy the following condition: for each 1 \le i \le |a|, a_i \le i. Here, |a| denotes the size of a.Help him to find the minimum number of operations that he has to perform to achieve this goal. We can show that under the constraints of the problem it's always possible to achieve this goal in a finite number of operations.InputThe first line contains a single integer t (1 \le t \le 200) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 100) — the initial length of the sequence.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the elements of the sequence.OutputFor each test case, print a single integer — the minimum number of operations needed to perform to achieve the goal mentioned in the statement.ExampleInput
4
3
1 3 4
5
1 2 5 7 4
1
1
3
69 6969 696969
Output
1
3
0
696966
NoteIn the first test case, we have to perform at least one operation, as a_2=3>2. We can perform the operation [1, 3, 4] \rightarrow [1, \underline{2}, 3, 4] (the newly inserted element is underlined), now the condition is satisfied.In the second test case, Shohag can perform the following operations:[1, 2, 5, 7, 4] \rightarrow [1, 2, \underline{3}, 5, 7, 4] \rightarrow [1, 2, 3, \underline{4}, 5, 7, 4] \rightarrow [1, 2, 3, 4, 5, \underline{3}, 7, 4].In the third test case, the sequence already satisfies the condition. | 4
3
1 3 4
5
1 2 5 7 4
1
1
3
69 6969 696969
| 1 3 0 696966 | 1 second | 256 megabytes | ['greedy', '*800'] |
F. October 18, 2017time limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIt was October 18, 2017. Shohag, a melancholic soul, made a strong determination that he will pursue Competitive Programming seriously, by heart, because he found it fascinating. Fast forward to 4 years, he is happy that he took this road. He is now creating a contest on Codeforces. He found an astounding problem but has no idea how to solve this. Help him to solve the final problem of the round.You are given three integers n, k and x. Find the number, modulo 998\,244\,353, of integer sequences a_1, a_2, \ldots, a_n such that the following conditions are satisfied: 0 \le a_i \lt 2^k for each integer i from 1 to n. There is no non-empty subsequence in a such that the bitwise XOR of the elements of the subsequence is x. A sequence b is a subsequence of a sequence c if b can be obtained from c by deletion of several (possibly, zero or all) elements.InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of test cases.The first and only line of each test case contains three space-separated integers n, k, and x (1 \le n \le 10^9, 0 \le k \le 10^7, 0 \le x \lt 2^{\operatorname{min}(20, k)}).It is guaranteed that the sum of k over all test cases does not exceed 5 \cdot 10^7.OutputFor each test case, print a single integer — the answer to the problem.ExampleInput
6
2 2 0
2 1 1
3 2 3
69 69 69
2017 10 18
5 7 0
Output
6
1
15
699496932
892852568
713939942
NoteIn the first test case, the valid sequences are [1, 2], [1, 3], [2, 1], [2, 3], [3, 1] and [3, 2].In the second test case, the only valid sequence is [0, 0]. | 6
2 2 0
2 1 1
3 2 3
69 69 69
2017 10 18
5 7 0
| 6 1 15 699496932 892852568 713939942 | 4 seconds | 512 megabytes | ['combinatorics', 'dp', 'implementation', 'math', '*2700'] |
E. A Perfect Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of integers b_1, b_2, \ldots, b_m is called good if max(b_1, b_2, \ldots, b_m) \cdot min(b_1, b_2, \ldots, b_m) \ge b_1 + b_2 + \ldots + b_m.A sequence of integers a_1, a_2, \ldots, a_n is called perfect if every non-empty subsequence of a is good.YouKn0wWho has two integers n and M, M is prime. Help him find the number, modulo M, of perfect sequences a_1, a_2, \ldots, a_n such that 1 \le a_i \le n + 1 for each integer i from 1 to n.A sequence d is a subsequence of a sequence c if d can be obtained from c by deletion of several (possibly, zero or all) elements.InputThe first and only line of the input contains two space-separated integers n and M (1 \le n \le 200; 10^8 \le M \le 10^9). It is guaranteed that M is prime.OutputPrint a single integer — the number of perfect sequences modulo M.ExamplesInput
2 998244353
Output
4
Input
4 100000007
Output
32
Input
69 999999937
Output
456886663
NoteIn the first test case, the perfect sequences are [2, 2], [2, 3], [3, 2] and [3, 3].In the second test case, some of the perfect sequences are [3, 4, 3, 5], [4, 5, 4, 4], [4, 5, 5, 5] etc. One example of a sequence which is not perfect is [2, 3, 3, 4], because, for example, the subsequence [2, 3, 4] is not an good as 2 \cdot 4 < 2 + 3 + 4. | 2 998244353
| 4 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', '*3200'] |
D. Artistic Partitiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFor two positive integers l and r (l \le r) let c(l, r) denote the number of integer pairs (i, j) such that l \le i \le j \le r and \operatorname{gcd}(i, j) \ge l. Here, \operatorname{gcd}(i, j) is the greatest common divisor (GCD) of integers i and j.YouKn0wWho has two integers n and k where 1 \le k \le n. Let f(n, k) denote the minimum of \sum\limits_{i=1}^{k}{c(x_i+1,x_{i+1})} over all integer sequences 0=x_1 \lt x_2 \lt \ldots \lt x_{k} \lt x_{k+1}=n.Help YouKn0wWho find f(n, k). InputThe first line contains a single integer t (1 \le t \le 3 \cdot 10^5) — the number of test cases.The first and only line of each test case contains two integers n and k (1 \le k \le n \le 10^5). OutputFor each test case, print a single integer — f(n, k).ExampleInput
4
6 2
4 4
3 1
10 3
Output
8
4
6
11
NoteIn the first test case, YouKn0wWho can select the sequence [0, 2, 6]. So f(6, 2) = c(1, 2) + c(3, 6) = 3 + 5 = 8 which is the minimum possible. | 4
6 2
4 4
3 1
10 3
| 8 4 6 11 | 3 seconds | 1024 megabytes | ['divide and conquer', 'dp', 'number theory', '*3000'] |
C. Extreme Extensiontime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor an array b of n integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make b non-decreasing: Select an index i such that 1 \le i \le |b|, where |b| is the current length of b. Replace b_i with two elements x and y such that x and y both are positive integers and x + y = b_i. This way, the array b changes and the next operation is performed on this modified array. For example, if b = [2, 4, 3] and index 2 gets selected, then the possible arrays after this operation are [2, \underline{1}, \underline{3}, 3], [2, \underline{2}, \underline{2}, 3], or [2, \underline{3}, \underline{1}, 3]. And consequently, for this array, this single operation is enough to make it non-decreasing: [2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3].It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array a of n integers. Help him find the sum of extreme values of all nonempty subarrays of a modulo 998\,244\,353. If a subarray appears in a multiple times, its extreme value should be counted the number of times it appears.An array d is a subarray of an array c if d can be obtained from c by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputThe first line contains a single integer t (1 \le t \le 10\,000) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^5).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 sum of extreme values of all subarrays of a modulo 998\,244\,353.ExampleInput
4
3
5 4 3
4
3 2 1 4
1
69
8
7264 40515 28226 92776 35285 21709 75124 48163
Output
5
9
0
117
NoteLet f(l, r) denote the extreme value of [a_l, a_{l+1}, \ldots, a_r].In the first test case, f(1, 3) = 3, because YouKn0wWho can perform the following operations on the subarray [5, 4, 3] (the newly inserted elements are underlined):[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]; f(1, 2) = 1, because [5, 4] \rightarrow [\underline{2}, \underline{3}, 4]; f(2, 3) = 1, because [4, 3] \rightarrow [\underline{1}, \underline{3}, 3]; f(1, 1) = f(2, 2) = f(3, 3) = 0, because they are already non-decreasing. So the total sum of extreme values of all subarrays of a = 3 + 1 + 1 + 0 + 0 + 0 = 5. | 4
3
5 4 3
4
3 2 1 4
1
69
8
7264 40515 28226 92776 35285 21709 75124 48163
| 5 9 0 117 | 4 seconds | 256 megabytes | ['dp', 'greedy', 'math', 'number theory', '*2300'] |
B. Moderate Modular Modetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYouKn0wWho has two even integers x and y. Help him to find an integer n such that 1 \le n \le 2 \cdot 10^{18} and n \bmod x = y \bmod n. Here, a \bmod b denotes the remainder of a after division by b. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints.InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of test cases.The first and only line of each test case contains two integers x and y (2 \le x, y \le 10^9, both are even).OutputFor each test case, print a single integer n (1 \le n \le 2 \cdot 10^{18}) that satisfies the condition mentioned in the statement. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints.ExampleInput
4
4 8
4 2
420 420
69420 42068
Output
4
10
420
9969128
NoteIn the first test case, 4 \bmod 4 = 8 \bmod 4 = 0.In the second test case, 10 \bmod 4 = 2 \bmod 10 = 2.In the third test case, 420 \bmod 420 = 420 \bmod 420 = 0. | 4
4 8
4 2
420 420
69420 42068
| 4 10 420 9969128 | 1 second | 256 megabytes | ['constructive algorithms', 'math', 'number theory', '*1600'] |
A. Di-visible Confusiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYouKn0wWho has an integer sequence a_1, a_2, \ldots, a_n. He will perform the following operation until the sequence becomes empty: select an index i such that 1 \le i \le |a| and a_i is not divisible by (i + 1), and erase this element from the sequence. Here |a| is the length of sequence a at the moment of operation. Note that the sequence a changes and the next operation is performed on this changed sequence.For example, if a=[3,5,4,5], then he can select i = 2, because a_2 = 5 is not divisible by i+1 = 3. After this operation the sequence is [3,4,5].Help YouKn0wWho determine if it is possible to erase the whole sequence using the aforementioned operation.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 a single integer n (1 \le n \le 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case, print "YES" (without quotes) if it is possible to erase the whole sequence using the aforementioned operation, print "NO" (without quotes) otherwise. You can print each letter in any register (upper or lower).ExampleInput
5
3
1 2 3
1
2
2
7 7
10
384836991 191890310 576823355 782177068 404011431 818008580 954291757 160449218 155374934 840594328
8
6 69 696 69696 696969 6969696 69696969 696969696
Output
YES
NO
YES
YES
NO
NoteIn the first test case, YouKn0wWho can perform the following operations (the erased elements are underlined): [1, \underline{2}, 3] \rightarrow [\underline{1}, 3] \rightarrow [\underline{3}] \rightarrow [\,].In the second test case, it is impossible to erase the sequence as i can only be 1, and when i=1, a_1 = 2 is divisible by i + 1 = 2. | 5
3
1 2 3
1
2
2
7 7
10
384836991 191890310 576823355 782177068 404011431 818008580 954291757 160449218 155374934 840594328
8
6 69 696 69696 696969 6969696 69696969 696969696
| YES NO YES YES NO | 1 second | 256 megabytes | ['constructive algorithms', 'math', 'number theory', '*1300'] |
B. Divine Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBlack is gifted with a Divine array a consisting of n (1 \le n \le 2000) integers. Each position in a has an initial value. After shouting a curse over the array, it becomes angry and starts an unstoppable transformation.The transformation consists of infinite steps. Array a changes at the i-th step in the following way: for every position j, a_j becomes equal to the number of occurrences of a_j in a before starting this step.Here is an example to help you understand the process better: Initial array:2 1 1 4 3 1 2After the 1-st step:2 3 3 1 1 3 2After the 2-nd step:2 3 3 2 2 3 2After the 3-rd step:4 3 3 4 4 3 4...... In the initial array, we had two 2-s, three 1-s, only one 4 and only one 3, so after the first step, each element became equal to the number of its occurrences in the initial array: all twos changed to 2, all ones changed to 3, four changed to 1 and three changed to 1.The transformation steps continue forever.You have to process q queries: in each query, Black is curious to know the value of a_x after the k-th step of transformation.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 (1 \le n \le 2000) — the size of the array a.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — the initial values of array a.The third line of each test case contains a single integer q (1 \le q \le 100\,000) — the number of queries.Next q lines contain the information about queries — one query per line. The i-th line contains two integers x_i and k_i (1 \le x_i \le n; 0 \le k_i \le 10^9), meaning that Black is asking for the value of a_{x_i} after the k_i-th step of transformation. k_i = 0 means that Black is interested in values of the initial array.It is guaranteed that the sum of n over all test cases doesn't exceed 2000 and the sum of q over all test cases doesn't exceed 100\,000.OutputFor each test case, print q answers. The i-th of them should be the value of a_{x_i} after the k_i-th step of transformation. It can be shown that the answer to each query is unique.ExampleInput
2
7
2 1 1 4 3 1 2
4
3 0
1 1
2 2
6 1
2
1 1
2
1 0
2 1000000000
Output
1
2
3
3
1
2
NoteThe first test case was described ih the statement. It can be seen that: k_1 = 0 (initial array): a_3 = 1; k_2 = 1 (after the 1-st step): a_1 = 2; k_3 = 2 (after the 2-nd step): a_2 = 3; k_4 = 1 (after the 1-st step): a_6 = 3. For the second test case, Initial array:1 1After the 1-st step:2 2After the 2-nd step:2 2......It can be seen that: k_1 = 0 (initial array): a_1 = 1; k_2 = 1000000000: a_2 = 2; | 2
7
2 1 1 4 3 1 2
4
3 0
1 1
2 2
6 1
2
1 1
2
1 0
2 1000000000
| 1 2 3 3 1 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'implementation', '*1100'] |
A. Two Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s. You need to find two non-empty strings a and b such that the following conditions are satisfied: Strings a and b are both subsequences of s. For each index i, character s_i of string s must belong to exactly one of strings a or b. String a is lexicographically minimum possible; string b may be any possible string. Given string s, print any valid a and b.Reminder:A string a (b) is a subsequence of a string s if a (b) can be obtained from s by deletion of several (possibly, zero) elements. For example, "dores", "cf", and "for" are subsequences of "codeforces", while "decor" and "fork" are not.A string x is lexicographically smaller than a string y if and only if one of the following holds: x is a prefix of y, but x \ne y; in the first position where x and y differ, the string x has a letter that appears earlier in the alphabet than the corresponding letter in y. 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 and only line of each test case contains one string s (2 \le |s| \le 100 where |s| means the length of s). String s consists of lowercase Latin letters.OutputFor each test case, print the strings a and b that satisfy the given conditions. If there are multiple answers, print any.ExampleInput
3
fc
aaaa
thebrightboiler
Output
c f
a aaa
b therightboiler
NoteIn the first test case, there are only two choices: either a = f and b = c or a = c and b = f. And a = c is lexicographically smaller than a = f.In the second test case, a is the only character in the string.In the third test case, it can be proven that b is the lexicographically smallest subsequence of s. The second string can be of two variants; one of them is given here. | 3
fc
aaaa
thebrightboiler
| c f a aaa b therightboiler | 2 seconds | 256 megabytes | ['implementation', '*800'] |
F. Two Sortstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIntegers from 1 to n (inclusive) were sorted lexicographically (considering integers as strings). As a result, array a_1, a_2, \dots, a_n was obtained.Calculate value of (\sum_{i = 1}^n ((i - a_i) \mod 998244353)) \mod 10^9 + 7.x \mod y here means the remainder after division x by y. This remainder is always non-negative and doesn't exceed y - 1. For example, 5 \mod 3 = 2, (-1) \mod 6 = 5. InputThe first line contains the single integer n (1 \leq n \leq 10^{12}).OutputPrint one integer — the required sum.ExamplesInput
3
Output
0
Input
12
Output
994733045
Input
21
Output
978932159
Input
1000000000000
Output
289817887
NoteA string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, 42 is lexicographically smaller than 6, because they differ in the first digit, and 4 < 6; 42 < 420, because 42 is a prefix of 420.Let's denote 998244353 as M.In the first example, array a is equal to [1, 2, 3]. (1 - 1) \mod M = 0 \mod M = 0 (2 - 2) \mod M = 0 \mod M = 0 (3 - 3) \mod M = 0 \mod M = 0 As a result, (0 + 0 + 0) \mod 10^9 + 7 = 0In the second example, array a is equal to [1, 10, 11, 12, 2, 3, 4, 5, 6, 7, 8, 9]. (1 - 1) \mod M = 0 \mod M = 0 (2 - 10) \mod M = (-8) \mod M = 998244345 (3 - 11) \mod M = (-8) \mod M = 998244345 (4 - 12) \mod M = (-8) \mod M = 998244345 (5 - 2) \mod M = 3 \mod M = 3 (6 - 3) \mod M = 3 \mod M = 3 (7 - 4) \mod M = 3 \mod M = 3 (8 - 5) \mod M = 3 \mod M = 3 (9 - 6) \mod M = 3 \mod M = 3 (10 - 7) \mod M = 3 \mod M = 3 (11 - 8) \mod M = 3 \mod M = 3 (12 - 9) \mod M = 3 \mod M = 3 As a result, (0 + 998244345 + 998244345 + 998244345 + 3 + 3 + 3 + 3 + 3 + 3 + 3 + 3) \mod 10^9 + 7 = 2994733059 \mod 10^9 + 7 = 994733045 | 3
| 0 | 4 seconds | 512 megabytes | ['binary search', 'dfs and similar', 'math', 'meet-in-the-middle', '*3400'] |
E. Phys Ed Onlinetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputStudents of one unknown college don't have PE courses. That's why q of them decided to visit a gym nearby by themselves. The gym is open for n days and has a ticket system. At the i-th day, the cost of one ticket is equal to a_i. You are free to buy more than one ticket per day.You can activate a ticket purchased at day i either at day i or any day later. Each activated ticket is valid only for k days. In other words, if you activate ticket at day t, it will be valid only at days t, t + 1, \dots, t + k - 1. You know that the j-th student wants to visit the gym at each day from l_j to r_j inclusive. Each student will use the following strategy of visiting the gym at any day i (l_j \le i \le r_j): person comes to a desk selling tickets placed near the entrance and buy several tickets with cost a_i apiece (possibly, zero tickets); if the person has at least one activated and still valid ticket, they just go in. Otherwise, they activate one of tickets purchased today or earlier and go in. Note that each student will visit gym only starting l_j, so each student has to buy at least one ticket at day l_j.Help students to calculate the minimum amount of money they have to spend in order to go to the gym.InputThe first line contains three integers n, q and k (1 \le n, q \le 300\,000; 1 \le k \le n) — the number of days, the number of students and the number of days each ticket is still valid. The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the cost of one ticket at the corresponding day.Each of the next q lines contains two integers l_i and r_i (1 \le l_i \le r_i \le n) — the segment of days the corresponding student want to visit the gym.OutputFor each student, print the minimum possible amount of money they have to spend in order to go to the gym at desired days.ExampleInput
7 5 2
2 15 6 3 7 5 6
1 2
3 7
5 5
7 7
3 5
Output
2
12
7
6
9
NoteLet's see how each student have to spend their money: The first student should buy one ticket at day 1. The second student should buy one ticket at day 3 and two tickets at day 4. Note that student can keep purchased tickets for the next days. The third student should buy one ticket at day 5. The fourth student should buy one ticket at day 7. The fifth student should buy one ticket at day 3 and one at day 4. | 7 5 2
2 15 6 3 7 5 6
1 2
3 7
5 5
7 7
3 5
| 2 12 7 6 9 | 2 seconds | 512 megabytes | ['data structures', 'dp', 'greedy', '*2900'] |
D. Difficult Mountaintime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA group of n alpinists has just reached the foot of the mountain. The initial difficulty of climbing this mountain can be described as an integer d.Each alpinist can be described by two integers s and a, where s is his skill of climbing mountains and a is his neatness.An alpinist of skill level s is able to climb a mountain of difficulty p only if p \leq s. As an alpinist climbs a mountain, they affect the path and thus may change mountain difficulty. Specifically, if an alpinist of neatness a climbs a mountain of difficulty p the difficulty of this mountain becomes \max(p, a). Alpinists will climb the mountain one by one. And before the start, they wonder, what is the maximum number of alpinists who will be able to climb the mountain if they choose the right order. As you are the only person in the group who does programming, you are to answer the question.Note that after the order is chosen, each alpinist who can climb the mountain, must climb the mountain at that time. InputThe first line contains two integers n and d (1 \leq n \leq 500\,000; 0 \leq d \leq 10^9) — the number of alpinists and the initial difficulty of the mountain.Each of the next n lines contains two integers s_i and a_i (0 \leq s_i, a_i \leq 10^9) that define the skill of climbing and the neatness of the i-th alpinist.OutputPrint one integer equal to the maximum number of alpinists who can climb the mountain if they choose the right order to do so.ExamplesInput
3 2
2 6
3 5
5 7
Output
2
Input
3 3
2 4
6 4
4 6
Output
2
Input
5 0
1 5
4 8
2 7
7 6
3 2
Output
3
NoteIn the first example, alpinists 2 and 3 can climb the mountain if they go in this order. There is no other way to achieve the answer of 2.In the second example, alpinist 1 is not able to climb because of the initial difficulty of the mountain, while alpinists 2 and 3 can go up in any order.In the third example, the mountain can be climbed by alpinists 5, 3 and 4 in this particular order. There is no other way to achieve optimal answer. | 3 2
2 6
3 5
5 7
| 2 | 2 seconds | 512 megabytes | ['data structures', 'dp', 'greedy', 'sortings', '*2700'] |
C. Optimal Insertiontime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given two arrays of integers a_1, a_2, \ldots, a_n and b_1, b_2, \ldots, b_m.You need to insert all elements of b into a in an arbitrary way. As a result you will get an array c_1, c_2, \ldots, c_{n+m} of size n + m.Note that you are not allowed to change the order of elements in a, while you can insert elements of b at arbitrary positions. They can be inserted at the beginning, between any elements of a, or at the end. Moreover, elements of b can appear in the resulting array in any order.What is the minimum possible number of inversions in the resulting array c? Recall that an inversion is a pair of indices (i, j) such that i < j and c_i > c_j.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^4). Description of the test cases follows.The first line of each test case contains two integers n and m (1 \leq n, m \leq 10^6).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 third line of each test case contains m integers b_1, b_2, \ldots, b_m (1 \leq b_i \leq 10^9).It is guaranteed that the sum of n for all tests cases in one input doesn't exceed 10^6. The sum of m for all tests cases doesn't exceed 10^6 as well.OutputFor each test case, print one integer — the minimum possible number of inversions in the resulting array c.ExampleInput
3
3 4
1 2 3
4 3 2 1
3 3
3 2 1
1 2 3
5 4
1 3 5 3 1
4 3 6 1
Output
0
4
6
NoteBelow is given the solution to get the optimal answer for each of the example test cases (elements of a are underscored). In the first test case, c = [\underline{1}, 1, \underline{2}, 2, \underline{3}, 3, 4]. In the second test case, c = [1, 2, \underline{3}, \underline{2}, \underline{1}, 3]. In the third test case, c = [\underline{1}, 1, 3, \underline{3}, \underline{5}, \underline{3}, \underline{1}, 4, 6]. | 3
3 4
1 2 3
4 3 2 1
3 3
3 2 1
1 2 3
5 4
1 3 5 3 1
4 3 6 1
| 0 4 6 | 3 seconds | 512 megabytes | ['data structures', 'divide and conquer', 'dp', 'greedy', 'sortings', '*2300'] |
B. Frog Travelertime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputFrog Gorf is traveling through Swamp kingdom. Unfortunately, after a poor jump, he fell into a well of n meters depth. Now Gorf is on the bottom of the well and has a long way up.The surface of the well's walls vary in quality: somewhere they are slippery, but somewhere have convenient ledges. In other words, if Gorf is on x meters below ground level, then in one jump he can go up on any integer distance from 0 to a_x meters inclusive. (Note that Gorf can't jump down, only up).Unfortunately, Gorf has to take a break after each jump (including jump on 0 meters). And after jumping up to position x meters below ground level, he'll slip exactly b_x meters down while resting.Calculate the minimum number of jumps Gorf needs to reach ground level.InputThe first line contains a single integer n (1 \le n \le 300\,000) — the depth of the well.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le i), where a_i is the maximum height Gorf can jump from i meters below ground level.The third line contains n integers b_1, b_2, \ldots, b_n (0 \le b_i \le n - i), where b_i is the distance Gorf will slip down if he takes a break on i meters below ground level.OutputIf Gorf can't reach ground level, print -1. Otherwise, firstly print integer k — the minimum possible number of jumps.Then print the sequence d_1,\,d_2,\,\ldots,\,d_k where d_j is the depth Gorf'll reach after the j-th jump, but before he'll slip down during the break. Ground level is equal to 0.If there are multiple answers, print any of them.ExamplesInput
3
0 2 2
1 1 0
Output
2
1 0
Input
2
1 1
1 0
Output
-1
Input
10
0 1 2 3 5 5 6 7 8 5
9 8 7 1 5 4 3 2 0 0
Output
3
9 4 0
NoteIn the first example, Gorf is on the bottom of the well and jump to the height 1 meter below ground level. After that he slip down by meter and stays on height 2 meters below ground level. Now, from here, he can reach ground level in one jump.In the second example, Gorf can jump to one meter below ground level, but will slip down back to the bottom of the well. That's why he can't reach ground level.In the third example, Gorf can reach ground level only from the height 5 meters below the ground level. And Gorf can reach this height using a series of jumps 10 \Rightarrow 9 \dashrightarrow 9 \Rightarrow 4 \dashrightarrow 5 where \Rightarrow is the jump and \dashrightarrow is slipping during breaks. | 3
0 2 2
1 1 0
| 2 1 0 | 2 seconds | 512 megabytes | ['data structures', 'dfs and similar', 'dp', 'graphs', 'shortest paths', 'two pointers', '*1900'] |
A. Array Eliminationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given array a_1, a_2, \ldots, a_n, consisting of non-negative integers.Let's define operation of "elimination" with integer parameter k (1 \leq k \leq n) as follows: Choose k distinct array indices 1 \leq i_1 < i_2 < \ldots < i_k \le n. Calculate x = a_{i_1} ~ \& ~ a_{i_2} ~ \& ~ \ldots ~ \& ~ a_{i_k}, where \& denotes the bitwise AND operation (notes section contains formal definition). Subtract x from each of a_{i_1}, a_{i_2}, \ldots, a_{i_k}; all other elements remain untouched. Find all possible values of k, such that it's possible to make all elements of array a equal to 0 using a finite number of elimination operations with parameter k. It can be proven that exists at least one possible k for any array a.Note that you firstly choose k and only after that perform elimination operations with value k you've chosen initially.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^4). Description of the test cases follows.The first line of each test case contains one integer n (1 \leq n \leq 200\,000) — the length 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}) — array a itself.It's guaranteed that the sum of n over all test cases doesn't exceed 200\,000.OutputFor each test case, print all values k, such that it's possible to make all elements of a equal to 0 in a finite number of elimination operations with the given parameter k.Print them in increasing order.ExampleInput
5
4
4 4 4 4
4
13 7 25 19
6
3 5 3 1 7 1
1
1
5
0 0 0 0 0
Output
1 2 4
1 2
1
1
1 2 3 4 5
NoteIn the first test case: If k = 1, we can make four elimination operations with sets of indices \{1\}, \{2\}, \{3\}, \{4\}. Since \& of one element is equal to the element itself, then for each operation x = a_i, so a_i - x = a_i - a_i = 0. If k = 2, we can make two elimination operations with, for example, sets of indices \{1, 3\} and \{2, 4\}: x = a_1 ~ \& ~ a_3 = a_2 ~ \& ~ a_4 = 4 ~ \& ~ 4 = 4. For both operations x = 4, so after the first operation a_1 - x = 0 and a_3 - x = 0, and after the second operation — a_2 - x = 0 and a_4 - x = 0. If k = 3, it's impossible to make all a_i equal to 0. After performing the first operation, we'll get three elements equal to 0 and one equal to 4. After that, all elimination operations won't change anything, since at least one chosen element will always be equal to 0. If k = 4, we can make one operation with set \{1, 2, 3, 4\}, because x = a_1 ~ \& ~ a_2 ~ \& ~ a_3 ~ \& ~ a_4 = 4. In the second test case, if k = 2 then we can make the following elimination operations: Operation with indices \{1, 3\}: x = a_1 ~ \& ~ a_3 = 13 ~ \& ~ 25 = 9. a_1 - x = 13 - 9 = 4 and a_3 - x = 25 - 9 = 16. Array a will become equal to [4, 7, 16, 19]. Operation with indices \{3, 4\}: x = a_3 ~ \& ~ a_4 = 16 ~ \& ~ 19 = 16. a_3 - x = 16 - 16 = 0 and a_4 - x = 19 - 16 = 3. Array a will become equal to [4, 7, 0, 3]. Operation with indices \{2, 4\}: x = a_2 ~ \& ~ a_4 = 7 ~ \& ~ 3 = 3. a_2 - x = 7 - 3 = 4 and a_4 - x = 3 - 3 = 0. Array a will become equal to [4, 4, 0, 0]. Operation with indices \{1, 2\}: x = a_1 ~ \& ~ a_2 = 4 ~ \& ~ 4 = 4. a_1 - x = 4 - 4 = 0 and a_2 - x = 4 - 4 = 0. Array a will become equal to [0, 0, 0, 0]. Formal definition of bitwise AND:Let's define bitwise AND (\&) as follows. Suppose we have two non-negative integers x and y, let's look at their binary representations (possibly, with leading zeroes): x_k \dots x_2 x_1 x_0 and y_k \dots y_2 y_1 y_0. Here, x_i is the i-th bit of number x, and y_i is the i-th bit of number y. Let r = x ~ \& ~ y is a result of operation \& on number x and y. Then binary representation of r will be r_k \dots r_2 r_1 r_0, where: r_i = \begin{cases} 1, ~ \text{if} ~ x_i = 1 ~ \text{and} ~ y_i = 1 \\ 0, ~ \text{if} ~ x_i = 0 ~ \text{or} ~ y_i = 0 \end{cases} | 5
4
4 4 4 4
4
13 7 25 19
6
3 5 3 1 7 1
1
1
5
0 0 0 0 0
| 1 2 4 1 2 1 1 1 2 3 4 5 | 2 seconds | 512 megabytes | ['bitmasks', 'greedy', 'math', 'number theory', '*1300'] |
J. Robot Factorytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have received data from a Bubble bot. You know your task is to make factory facilities, but before you even start, you need to know how big the factory is and how many rooms it has. When you look at the data you see that you have the dimensions of the construction, which is in rectangle shape: N x M. Then in the next N lines you have M numbers. These numbers represent factory tiles and they can go from 0 to 15. Each of these numbers should be looked in its binary form. Because from each number you know on which side the tile has walls. For example number 10 in it's binary form is 1010, which means that it has a wall from the North side, it doesn't have a wall from the East, it has a wall on the South side and it doesn't have a wall on the West side. So it goes North, East, South, West. It is guaranteed that the construction always has walls on it's edges. The input will be correct. Your task is to print the size of the rooms from biggest to smallest. InputThe first line has two numbers which are N and M, the size of the construction. Both are integers: n (1 \leq n \leq 10^3)m (1 \leq m \leq 10^3)Next N x M numbers represent each tile of construction.OutputOnce you finish processing the data your output consists of one line sorted from biggest to smallest room sizes. ExampleInput
4 5
9 14 11 12 13
5 15 11 6 7
5 9 14 9 14
3 2 14 3 14
Output
9 4 4 2 1
| 4 5
9 14 11 12 13
5 15 11 6 7
5 9 14 9 14
3 2 14 3 14
| 9 4 4 2 1 | 1 second | 256 megabytes | ['bitmasks', 'dfs and similar', '*1400'] |
F. Party Organizationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the great island of Baltia, there live N people, numbered from 1 to N. There are exactly M pairs of people that are friends with each other. The people of Baltia want to organize a successful party, but they have very strict rules on what a party is and when the party is successful. On the island of Baltia, a party is a gathering of exactly 5 people. The party is considered to be successful if either all the people at the party are friends with each other (so that they can all talk to each other without having to worry about talking to someone they are not friends with) or no two people at the party are friends with each other (so that everyone can just be on their phones without anyone else bothering them). Please help the people of Baltia organize a successful party or tell them that it's impossible to do so.InputThe first line contains two integer numbers, N (5 \leq N \leq 2*10^5) and M (0 \leq M \leq 2*10^5) – the number of people that live in Baltia, and the number of friendships. The next M lines each contains two integers U_i and V_i (1 \leq U_i,V_i \leq N) – meaning that person U_i is friends with person V_i. Two friends can not be in the list of friends twice (no pairs are repeated) and a person can be friends with themselves (U_i \ne V_i).OutputIf it's possible to organize a successful party, print 5 numbers indicating which 5 people should be invited to the party. If it's not possible to organize a successful party, print -1 instead. If there are multiple successful parties possible, print any.ExamplesInput
6 3
1 4
4 2
5 4
Output
1 2 3 5 6
Input
5 4
1 2
2 3
3 4
4 5
Output
-1
| 6 3
1 4
4 2
5 4
| 1 2 3 5 6 | 1 second | 256 megabytes | ['brute force', 'math', 'probabilities', '*2300'] |
E. Array Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game. They are given an array A of length N. The array consists of integers. They are building a sequence together. In the beginning, the sequence is empty. In one turn a player can remove a number from the left or right side of the array and append it to the sequence. The rule is that the sequence they are building must be strictly increasing. The winner is the player that makes the last move. Alice is playing first. Given the starting array, under the assumption that they both play optimally, who wins the game?InputThe first line contains one integer N (1 \leq N \leq 2*10^5) - the length of the array A.The second line contains N integers A_1, A_2,...,A_N (0 \leq A_i \leq 10^9)OutputThe first and only line of output consists of one string, the name of the winner. If Alice won, print "Alice", otherwise, print "Bob".ExamplesInput
1
5
Output
Alice
Input
3
5 4 5
Output
Alice
Input
6
5 8 2 1 10 9
Output
Bob
| 1
5
| Alice | 1 second | 256 megabytes | ['games', 'greedy', 'two pointers', '*1900'] |
J. Bob's Beautiful Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob really likes playing with arrays of numbers. That's why for his birthday, his friends bought him a really interesting machine – an array beautifier. The array beautifier takes an array A consisting of N integers, and it outputs a new array B of length N that it constructed based on the array given to it. The array beautifier constructs the new array in the following way: it takes two numbers at different indices from the original array and writes their sum to the end of the new array. It does this step N times - resulting in an output array of length N. During this process, the machine can take the same index multiple times in different steps. Bob was very excited about the gift that his friends gave him, so he put his favorite array in the machine. However, when the machine finished, Bob was not happy with the resulting array. He misses his favorite array very much, and hopes to get it back. Given the array that the machine outputted, help Bob find an array that could be the original array that he put in the machine. Sometimes the machine makes mistakes, so it is possible that no appropriate input array exists for the array it has outputted. In such case, let Bob know that his array is forever lost.InputThe first line contains one positive integer N (2 \leq N \leq 10^3) – the length of Bob's array.The second line contains N integers B_1, B_2, ..., B_N (1 \leq B_i \leq 10^6) – the elements of the array the machine outputted.OutputIf an appropriate input array exists, print "YES", followed by the input array A_1, A_2, ..., A_N (-10^9 \leq A_i \leq 10^9) in the next line. Otherwise, print "NO".ExamplesInput
2
5 5
Output
YES
2 3
Input
3
1 2 3
Output
YES
0 1 2
Input
3
2 4 5
Output
NO
Input
4
1 3 5 7
Output
YES
6 -3 4 1
| 2
5 5
| YES 2 3 | 1 second | 256 megabytes | ['bitmasks', 'brute force', 'greedy', '*2600'] |
I. Deserttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph of N nodes and M edges, E_1, E_2, \dots E_M.A connected graph is a cactus if each of it's edges belogs to at most one simple cycle. A graph is a desert if each of it's connected components is a cactus. Find the number of pairs (L, R), (1 \leq L \leq R \leq M) such that, if we delete all the edges except for E_L, E_{L+1}, \dots E_R, the graph is a desert. InputThe first line contains two integers N and M (2 \leq N \leq 2.5 \times 10^5, 1 \leq M \leq 5 \times 10^5). Each of the next M lines contains two integers. The i-th line describes the i-th edge. It contains integers U_i and V_i, the nodes connected by the i-th edge (E_i=(U_i, V_i)). It is guaranteed that 1 \leq U_i, V_i \leq N and U_i \neq V_i. OutputThe output contains one integer number – the answer.ExamplesInput
5 6
1 2
2 3
3 4
4 5
5 1
2 4
Output
20Input
2 3
1 2
1 2
1 2
Output
5NoteIn the second example: Graphs for pairs (1, 1), (2, 2) and (3, 3) are deserts because they don't have any cycles. Graphs for pairs (1, 2) and (2, 3) have one cycle of length 2 so they are deserts. | 5 6
1 2
2 3
3 4
4 5
5 1
2 4
| 20 | 2 seconds | 256 megabytes | ['data structures', 'graphs', '*2700'] |
H. Hidden Fortresstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem!As part of your contribution in the Great Bubble War, you have been tasked with finding the newly built enemy fortress. The world you live in is a giant 10^9 \times 10^9 grid, with squares having both coordinates between 1 and 10^9. You know that the enemy base has the shape of a rectangle, with the sides parallel to the sides of the grid. The people of your world are extremely scared of being at the edge of the world, so you know that the base doesn't contain any of the squares on the edges of the grid (the x or y coordinate being 1 or 10^9). To help you locate the base, you have been given a device that you can place in any square of the grid, and it will tell you the manhattan distance to the closest square of the base. The manhattan distance from square (a, b) to square (p, q) is calculated as |a−p|+|b−q|. If you try to place the device inside the enemy base, you will be captured by the enemy. Because of this, you need to make sure to never place the device inside the enemy base. Unfortunately, the device is powered by a battery and you can't recharge it. This means that you can use the device at most 40 times. InputThe input contains the answers to your queries. InteractionYour code is allowed to place the device on any square in the grid by writing "? i j" (1 \leq i,j \leq 10^9). In return, it will recieve the manhattan distance to the closest square of the enemy base from square (i,j) or -1 if the square you placed the device on is inside the enemy base or outside the grid. If you recieve -1 instead of a positive number, exit immidiately and you will see the wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.Your solution should use no more than 40 queries. Once you are sure where the enemy base is located, you should print "! x y p q" (1 \leq x \leq p\leq 10^9, 1 \leq y \leq q\leq 10^9), where (x, y) is the square inside the enemy base with the smallest x and y coordinates, and (p, q) is the square inside the enemy base with the largest x and y coordinates. Note that answering doesn't count as one of the 40 queries.After printing a query or printing the answer, do not forget to output end of line and flush the output. Otherwise, you will get idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; See the documentation for other languages.ExampleInput
1
1
2
1
Output
? 2 2
? 5 5
? 4 7
? 1 5
! 2 3 4 5
| 1
1
2
1
| ? 2 2 ? 5 5 ? 4 7 ? 1 5 ! 2 3 4 5 | 1 second | 256 megabytes | ['interactive', 'math', '*2100'] |
G. Shortest pathtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given N points on an infinite plane with the Cartesian coordinate system on it. N-1 points lay on one line, and one point isn't on that line. You are on point K at the start, and the goal is to visit every point. You can move between any two points in a straight line, and you can revisit points. What is the minimum length of the path? InputThe first line contains two integers: N (3 \leq N \leq 2*10^5) - the number of points, and K (1 \leq K \leq N) - the index of the starting point.Each of the next N lines contain two integers, A_i, B_i (-10^6 \leq A_i, B_i \leq 10^6) - coordinates of the i-th point.OutputThe output contains one number - the shortest path to visit all given points starting from point K. The absolute difference between your solution and the main solution shouldn't exceed 10^-6;ExampleInput
5 2
0 0
-1 1
2 -2
0 1
-2 2
Output
7.478709NoteThe shortest path consists of these moves: 2 -> 5 5 -> 4 4 -> 1 1 -> 3 There isn't any shorter path possible. | 5 2
0 0
-1 1
2 -2
0 1
-2 2
| 7.478709 | 1 second | 256 megabytes | ['brute force', 'geometry', 'math', 'shortest paths', '*2700'] |
F. Marstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the year 2420 humans have finally built a colony on Mars thanks to the work of Elon Tusk. There are 10^9+7 cities arranged in a circle in this colony and none of them are connected yet. Elon Tusk wants to connect some of those cities using only roads of the same size in order to lower the production cost of those roads. Because of that he gave a list on N cites where some cites can appear more than once and Q queries that you need to answer. For the query you need to determine if it is possible to connect all the cities from L_{i} to R_{i} on that list using only roads of length D_{i}. InputThe first line contains two integers N and Q (1 \leq N, Q \leq 2\cdot10^5 ) — the length of the array of cities and the number of queries you need to answer. The second lines contains N integers representing the array of cites. Next Q lines contain three integers L, R and D (1 \leq L_{i}, R_{i} \leq N, 0 \leq D_{i} \leq 10^9+6) — the range of cities that needs to be connected and the length of the road that you can use. OutputThe output contains Q lines. If it is possible to connect all the cities from the i-th query can be connected with roads of length D_{i} the i-th line should contain the word "Yes", otherwise it should contain the word "No". ExamplesInput
9 8
17 0 12 6 10 8 2 4 5
2 3 12
2 3 6
2 4 6
4 6 2
2 8 2
1 2 17
1 8 2
9 9 14
Output
Yes
No
Yes
Yes
Yes
Yes
No
Yes
Input
4 1
7 21 14 0
1 4 1000000000
Output
Yes
NoteIn the 5^{th} query of the first test case we can connect cities in this order 0-2-4-6-8-10-12 this way distance between any two connected cities is 2. In the second test case we can connect cities in this order 21-14-7-0 this way distance between any two connected cities is 10^9 module 10^9+7. | 9 8
17 0 12 6 10 8 2 4 5
2 3 12
2 3 6
2 4 6
4 6 2
2 8 2
1 2 17
1 8 2
9 9 14
| Yes No Yes Yes Yes Yes No Yes | 2 seconds | 256 megabytes | ['hashing', '*2700'] |
E. Two Arraystime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integer arrays of length N, A1 and A2. You are also given Q queries of 4 types: 1 k l r x: set Ak_i:=min(Ak_i, x) for each l \leq i \leq r.2 k l r x: set Ak_i:=max(Ak_i, x) for each l \leq i \leq r.3 k l r x: set Ak_i:=Ak_i+x for each l \leq i \leq r.4 l r: find the (\sum_{i=l}^r F(A1_i+A2_i)) \% (10^9+7) where F(k) is the k-th Fibonacci number (F(0)=0, F(1)=1, F(k)=F(k-1)+F(k-2)), and x \% y denotes the remainder of the division of x by y.You should process these queries and answer each query of the fourth type.InputThe first line contains two integers N and Q. (1 \leq N, Q \leq 5 \times 10^4) The second line contains N integers, array A1_1, A1_2, \dots A1_N. (0 \leq A1_i \leq 10^6)The third line contains N integers, array A2_1, A2_2, \dots A2_N. (0 \leq A2_i \leq 10^6)The next Q lines describe the queries. Each line contains 5 or 3 integers, where the first integer denotes the type of the query. (k \in \{1, 2\}, 1 \leq l \leq r \leq N)For queries of type 1 and 2, 0 \leq x \leq 10^9 holds.For queries of type 3, −10^6 \leq x \leq 10^6 holds.It is guaranteed that after every query each number in arrays A1 and A2 will be nonnegative. OutputPrint the answer to each query of the fourth type, in separate lines. ExamplesInput
3 4
1 0 2
2 1 0
4 1 3
3 2 2 2 3
1 1 1 3 0
4 1 3
Output
4
4
Input
5 4
1 3 5 3 2
4 2 1 3 3
4 1 3
4 2 5
2 1 2 4 6
4 2 4
Output
18
26
68
NoteIn the first example: The answer for the first query is F(1 + 2) + F(0 + 1) + F(2 + 0) = F(3) + F(1) + F(2) = 2 + 1 + 1 = 4. After the second query, the array A2 changes to [2, 4, 0]. After the third query, the array A1 changes to [0, 0, 0]. The answer for the fourth query is F(0 + 2) + F(0 + 4) + F(0 + 0) = F(2) + F(4) + F(0) = 1 + 3 + 0 = 4. In the second example: The answer for the first query is F(1 + 4) + F(3 + 2) + F(5 + 1) = F(5) + F(5) + F(6) = 5 + 5 + 8 = 18. The answer for the second query is F(3 + 2) + F(5 + 1) + F(3 + 3) + F(2 + 3) = F(5) + F(6) + F(6) + F(5) = 5 + 8 + 8 + 5 = 26. After the third query, the array A1 changes to [1, 6, 6, 6, 2]. The answer for the fourth query is F(6 + 2) + F(6 + 1) + F(6 + 3) = F(8) + F(7) + F(9) = 21 + 13 + 34 = 68. | 3 4
1 0 2
2 1 0
4 1 3
3 2 2 2 3
1 1 1 3 0
4 1 3
| 4 4 | 5 seconds | 256 megabytes | ['data structures', 'matrices', '*3200'] |
D. Bubble Poppingtime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are N bubbles in a coordinate plane. Bubbles are so tiny that it can be assumed that each bubble is a point (X_i, Y_i). Q Bubble Cup finalists plan to play with the bubbles. Each finalist would link to use infinitely long Bubble Cup stick to pop some bubbles. The i-th finalist would like to place the stick in the direction of vector (dxi, dyi), and plays the following game until K_i bubbles are popped. The game starts with finalist placing the stick in the direction of vector (dx_i, dy_i), and sweeping it from the infinity to the left until it hits some bubble, which is immediately popped. It is guaranteed that only one bubble will be hit in this step. After that the finalist starts rotating the stick in the counter clockwise direction with the center of rotation in point where the previous bubble was popped. When the next bubble is hit, it is immediately popped and becomes the new center of rotation. The process continues until K_i bubbles have been popped. It is guaranteed that the stick won't hit two bubbles simultaneously in this process. For each finalist find which bubble would be popped the last. Note that each game starts with the configuration of all N bubbles, so the games don't depend on the previous games. InputThe first line contains one integer N — the number of bubbles. (1 \leq N \leq 10^5)Each of the next N lines contains two integers. The i-th line contains integers X_i and Y_i — the coordinates of the i-th bubble. (-10^9 \leq X_i, Y_i \leq 10^9, (X_i, Y_i) \neq (X_j, Y_j) for i \neq j)The next line contains one integer Q — the number of finalists willing to play with the bubbles. (1 \leq Q \leq 10^5)Each of the next Q lines contains 3 integers. The i-th line contains integers dx_i, dy_i and K_i. (-10^9 \leq dx_i, dy_i \leq 10^9, 1 \leq K_i \leq N)OutputFor each of the Q finalists, print the index of the bubble which would be popped last, in the separate line. ExamplesInput
4
0 0
1 0
0 1
1 1
2
1 -1 3
-1 1 4
Output
4
2
Input
4
1 1
2 2
7 1
1 7
3
2 2 1
1 -5 4
-6 5 3
Output
3
2
3
NoteThere are two finalists willing to play with the bubbles. If the first finalist plays with the bubbles, then the bubbles at coordinates (0, 0), (1, 0) and (1, 1) would be popped in that order. Their indexes are 1, 2 and 4, so the answer is 4. If the second finalist plays with the bubbles, then the bubbles at coordinates (1, 1), (0, 1), (0, 0) and (1, 0) would be popped in that order, so the answer is 2.Visualization: link. | 4
0 0
1 0
0 1
1 1
2
1 -1 3
-1 1 4
| 4 2 | 2.5 seconds | 256 megabytes | ['*3200'] |
C. Bubble Striketime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Johnny Bubbles enjoys spending hours in front of his computer playing video games. His favorite game is Bubble Strike, fast-paced bubble shooting online game for two players.Each game is set in one of the N maps, each having different terrain configuration. First phase of each game decides on which map the game will be played. The game system randomly selects three maps and shows them to the players. Each player must pick one of those three maps to be discarded. The game system then randomly selects one of the maps that were not picked by any of the players and starts the game.Johnny is deeply enthusiastic about the game and wants to spend some time studying maps, thus increasing chances to win games played on those maps. However, he also needs to do his homework, so he does not have time to study all the maps. That is why he asked himself the following question: "What is the minimum number of maps I have to study, so that the probability to play one of those maps is at least P"?Can you help Johnny find the answer for this question? You can assume Johnny's opponents do not know him, and they will randomly pick maps.InputThe first line contains two integers N (3 \leq N \leq 10^{3}) and P (0 \leq P \leq 1) – total number of maps in the game and probability to play map Johnny has studied. P will have at most four digits after the decimal point.OutputOutput contains one integer number – minimum number of maps Johnny has to study.ExampleInput
7 1.0000
Output
6
| 7 1.0000
| 6 | 0.5 seconds | 256 megabytes | ['combinatorics', 'math', 'probabilities', 'ternary search', '*2000'] |
B. Restaurant Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob always had hard time choosing restaurant for the dinner. Previously they performed Eenie Meenie Miney Mo game, but eventually as their restaurant list grew, they had to create a new game. This new game starts as they write restaurant names on N cards and align the cards in one line. Before the game begins, they both choose starting card and starting direction they are going to. They take turns in order one after another. After each turn, they move one card in their current direction. If they reach the end or beginning of the line of cards they change direction. Once they meet in a card, the card is marked for removal and is removed the first moment they both leave the card. Example of how card is removed They repeat this process until there is only one restaurant card left. Since there are a lot of restaurant cards, they are bored to simulate this process over and over and need your help to determine the last card that remains. Can you help them? InputThe first line of the input is one integer T (1 \leq T \leq 10^{4}) representing number of test cases. Each test case contains 3 lines: The first line contains an integer N representing initial number of cards. Next line contains two integer values A,B (0 \leq A, B < N, 2 \leq N \leq 10^{18}) representing starting 0-based index of the card in the array. Last line contains two strings D_A, D_B \in {"left", "right"} representing starting direction of their movement.OutputThe output contains T integer number – the 0-based index of the last card that remains for every test case in order.ExampleInput
1
4
0 1
left right
Output
0
NoteNote that since Alice is starting at the beginning of the line even though her initial direction is left, on her next move she will go right. | 1
4
0 1
left right
| 0 | 1 second | 256 megabytes | ['*3100'] |
A. Weightstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array A of length N weights of masses A_1, A_2...A_N. No two weights have the same mass. You can put every weight on one side of the balance (left or right). You don't have to put weights in order A_1,...,A_N. There is also a string S consisting of characters "L" and "R", meaning that after putting the i-th weight (not A_i, but i-th weight of your choice) left or right side of the balance should be heavier. Find the order of putting the weights on the balance such that rules of string S are satisfied. InputThe first line contains one integer N (1 \leq N \leq 2*10^5) - the length of the array A The second line contains N distinct integers: A_1, A_2,...,A_N (1 \leq A_i \leq 10^9) - the weights given The third line contains string S of length N consisting only of letters "L" and "R" - string determining which side of the balance should be heavier after putting the i-th weight of your choiceOutputThe output contains N lines. In every line, you should print one integer and one letter - integer representing the weight you are putting on the balance in that move and the letter representing the side of the balance where you are putting the weight. If there is no solution, print -1.ExampleInput
5
3 8 2 13 7
LLRLL
Output
3 L
2 R
8 R
13 L
7 L
NoteExplanation for the test case: after the 1st weight: 3 L (left side is heavier)after the 2nd weight: 2 R (left side is heavier)after the 3rd weight: 8 R (right side is heavier)after the 4th weight: 13 L (left side is heavier)after the 5th weight: 7 L (left side is heavier)So, the rules given by string S are fulfilled and our order of putting the weights is correct. | 5
3 8 2 13 7
LLRLL
| 3 L 2 R 8 R 13 L 7 L | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'two pointers', '*2600'] |
G. The Sum of Good Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a positive integer good if there is no digit 0 in its decimal representation.For an array of a good numbers a, one found out that the sum of some two neighboring elements is equal to x (i.e. x = a_i + a_{i + 1} for some i). x had turned out to be a good number as well.Then the elements of the array a were written out one after another without separators into one string s. For example, if a = [12, 5, 6, 133], then s = 1256133.You are given a string s and a number x. Your task is to determine the positions in the string that correspond to the adjacent elements of the array that have sum x. If there are several possible answers, you can print any of them.InputThe first line contains the string s (2 \le |s| \le 5 \cdot 10^5).The second line contains an integer x (2 \le x < 10^{200000}).An additional constraint on the input: the answer always exists, i.e you can always select two adjacent substrings of the string s so that if you convert these substrings to integers, their sum is equal to x.OutputIn the first line, print two integers l_1, r_1, meaning that the first term of the sum (a_i) is in the string s from position l_1 to position r_1.In the second line, print two integers l_2, r_2, meaning that the second term of the sum (a_{i + 1}) is in the string s from position l_2 to position r_2.ExamplesInput
1256133
17
Output
1 2
3 3
Input
9544715561
525
Output
2 3
4 6
Input
239923
5
Output
1 1
2 2
Input
1218633757639
976272
Output
2 7
8 13
NoteIn the first example s[1;2] = 12 and s[3;3] = 5, 12+5=17.In the second example s[2;3] = 54 and s[4;6] = 471, 54+471=525.In the third example s[1;1] = 2 and s[2;2] = 3, 2+3=5.In the fourth example s[2;7] = 218633 and s[8;13] = 757639, 218633+757639=976272. | 1256133
17
| 1 2 3 3 | 2 seconds | 256 megabytes | ['hashing', 'math', 'string suffix structures', 'strings', '*3200'] |
F. RBStime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence (or, shortly, an RBS) is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example: bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"); bracket sequences ")(", "(" and ")" are not. Let's denote the concatenation of two strings x and y as x+y. For example, "()()" + ")(" = "()())(".You are given n bracket sequences s_1, s_2, \dots, s_n. You can rearrange them in any order (you can rearrange only the strings themselves, but not the characters in them).Your task is to rearrange the strings in such a way that the string s_1 + s_2 + \dots + s_n has as many non-empty prefixes that are RBS as possible.InputThe first line contains a single integer n (1 \le n \le 20).Then n lines follow, the i-th of them contains s_i — a bracket sequence (a string consisting of characters "(" and/or ")". All sequences s_i are non-empty, their total length does not exceed 4 \cdot 10^5.OutputPrint one integer — the maximum number of non-empty prefixes that are RBS for the string s_1 + s_2 + \dots + s_n, if the strings s_1, s_2, \dots, s_n can be rearranged arbitrarily.ExamplesInput
2
(
)
Output
1
Input
4
()()())
(
(
)
Output
4
Input
1
(())
Output
1
Input
1
)(()
Output
0
NoteIn the first example, you can concatenate the strings as follows: "(" + ")" = "()", the resulting string will have one prefix, that is an RBS: "()".In the second example, you can concatenate the strings as follows: "(" + ")" + "()()())" + "(" = "()()()())(", the resulting string will have four prefixes that are RBS: "()", "()()", "()()()", "()()()()".The third and the fourth examples contain only one string each, so the order is fixed. | 2
(
)
| 1 | 3 seconds | 512 megabytes | ['binary search', 'bitmasks', 'brute force', 'data structures', 'dp', '*2400'] |
E. Staircasestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix, consisting of n rows and m columns. The rows are numbered top to bottom, the columns are numbered left to right.Each cell of the matrix can be either free or locked.Let's call a path in the matrix a staircase if it: starts and ends in the free cell; visits only free cells; has one of the two following structures: the second cell is 1 to the right from the first one, the third cell is 1 to the bottom from the second one, the fourth cell is 1 to the right from the third one, and so on; the second cell is 1 to the bottom from the first one, the third cell is 1 to the right from the second one, the fourth cell is 1 to the bottom from the third one, and so on. In particular, a path, consisting of a single cell, is considered to be a staircase.Here are some examples of staircases: Initially all the cells of the matrix are free.You have to process q queries, each of them flips the state of a single cell. So, if a cell is currently free, it makes it locked, and if a cell is currently locked, it makes it free.Print the number of different staircases after each query. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.InputThe first line contains three integers n, m and q (1 \le n, m \le 1000; 1 \le q \le 10^4) — the sizes of the matrix and the number of queries.Each of the next q lines contains two integers x and y (1 \le x \le n; 1 \le y \le m) — the description of each query.OutputPrint q integers — the i-th value should be equal to the number of different staircases after i queries. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.ExamplesInput
2 2 8
1 1
1 1
1 1
2 2
1 1
1 2
2 1
1 1
Output
5
10
5
2
5
3
1
0
Input
3 4 10
1 4
1 2
2 3
1 2
2 3
3 2
1 3
3 4
1 3
3 1
Output
49
35
24
29
49
39
31
23
29
27
Input
1000 1000 2
239 634
239 634
Output
1332632508
1333333000
| 2 2 8
1 1
1 1
1 1
2 2
1 1
1 2
2 1
1 1
| 5 10 5 2 5 3 1 0 | 2 seconds | 256 megabytes | ['brute force', 'combinatorics', 'data structures', 'dfs and similar', 'dp', 'implementation', 'math', '*2100'] |
D. Training Sessiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is the coach of the Berland State University programming teams. He decided to compose a problemset for a training session for his teams.Monocarp has n problems that none of his students have seen yet. The i-th problem has a topic a_i (an integer from 1 to n) and a difficulty b_i (an integer from 1 to n). All problems are different, that is, there are no two tasks that have the same topic and difficulty at the same time.Monocarp decided to select exactly 3 problems from n problems for the problemset. The problems should satisfy at least one of two conditions (possibly, both): the topics of all three selected problems are different; the difficulties of all three selected problems are different. Your task is to determine the number of ways to select three problems for the problemset.InputThe first line contains a single integer t (1 \le t \le 50000) — the number of testcases.The first line of each testcase contains an integer n (3 \le n \le 2 \cdot 10^5) — the number of problems that Monocarp have.In the i-th of the following n lines, there are two integers a_i and b_i (1 \le a_i, b_i \le n) — the topic and the difficulty of the i-th problem.It is guaranteed that there are no two problems that have the same topic and difficulty at the same time.The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputPrint the number of ways to select three training problems that meet either of the requirements described in the statement.ExampleInput
2
4
2 4
3 4
2 1
1 3
5
1 5
2 4
3 3
4 2
5 1
Output
3
10
NoteIn the first example, you can take the following sets of three problems: problems 1, 2, 4; problems 1, 3, 4; problems 2, 3, 4. Thus, the number of ways is equal to three. | 2
4
2 4
3 4
2 1
1 3
5
1 5
2 4
3 3
4 2
5 1
| 3 10 | 2 seconds | 256 megabytes | ['combinatorics', 'data structures', 'geometry', 'implementation', 'math', '*1700'] |
C. Delete Two Elementstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp has got an array a consisting of n integers. Let's denote k as the mathematic mean of these elements (note that it's possible that k is not an integer). The mathematic mean of an array of n elements is the sum of elements divided by the number of these elements (i. e. sum divided by n).Monocarp wants to delete exactly two elements from a so that the mathematic mean of the remaining (n - 2) elements is still equal to k.Your task is to calculate the number of pairs of positions [i, j] (i < j) such that if the elements on these positions are deleted, the mathematic mean of (n - 2) remaining elements is equal to k (that is, it is equal to the mathematic mean of n elements of the original array a).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 one integer n (3 \le n \le 2 \cdot 10^5) — the number of elements in the array.The second line contains a sequence of integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^{9}), where a_i is the i-th element of the array.The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputPrint one integer — the number of pairs of positions [i, j] (i < j) such that if the elements on these positions are deleted, the mathematic mean of (n - 2) remaining elements is equal to k (that is, it is equal to the mathematic mean of n elements of the original array a).ExampleInput
4
4
8 8 8 8
3
50 20 10
5
1 4 7 3 5
7
1 2 3 4 5 6 7
Output
6
0
2
3
NoteIn the first example, any pair of elements can be removed since all of them are equal.In the second example, there is no way to delete two elements so the mathematic mean doesn't change.In the third example, it is possible to delete the elements on positions 1 and 3, or the elements on positions 4 and 5. | 4
4
8 8 8 8
3
50 20 10
5
1 4 7 3 5
7
1 2 3 4 5 6 7
| 6 0 2 3 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'implementation', 'math', 'two pointers', '*1200'] |
B. Groupstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputn students attended the first meeting of the Berland SU programming course (n is even). All students will be divided into two groups. Each group will be attending exactly one lesson each week during one of the five working days (Monday, Tuesday, Wednesday, Thursday and Friday), and the days chosen for the groups must be different. Furthermore, both groups should contain the same number of students.Each student has filled a survey in which they told which days of the week are convenient for them to attend a lesson, and which are not. Your task is to determine if it is possible to choose two different week days to schedule the lessons for the group (the first group will attend the lesson on the first chosen day, the second group will attend the lesson on the second chosen day), and divide the students into two groups, so the groups have equal sizes, and for each student, the chosen lesson day for their group is convenient.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.Then the descriptions of t testcases follow.The first line of each testcase contains one integer n (2 \le n \le 1\,000) — the number of students.The i-th of the next n lines contains 5 integers, each of them is 0 or 1. If the j-th integer is 1, then the i-th student can attend the lessons on the j-th day of the week. If the j-th integer is 0, then the i-th student cannot attend the lessons on the j-th day of the week. Additional constraints on the input: for each student, at least one of the days of the week is convenient, the total number of students over all testcases doesn't exceed 10^5.OutputFor each testcase print an answer. If it's possible to divide the students into two groups of equal sizes and choose different days for the groups so each student can attend the lesson in the chosen day of their group, print "YES" (without quotes). Otherwise, print "NO" (without quotes). ExampleInput
2
4
1 0 0 1 0
0 1 0 0 1
0 0 0 1 0
0 1 0 1 0
2
0 0 0 1 0
0 0 0 1 0
Output
YES
NO
NoteIn the first testcase, there is a way to meet all the constraints. For example, the first group can consist of the first and the third students, they will attend the lessons on Thursday (the fourth day); the second group can consist of the second and the fourth students, and they will attend the lessons on Tuesday (the second day).In the second testcase, it is impossible to divide the students into groups so they attend the lessons on different days. | 2
4
1 0 0 1 0
0 1 0 0 1
0 0 0 1 0
0 1 0 1 0
2
0 0 0 1 0
0 0 0 1 0
| YES NO | 4 seconds | 256 megabytes | ['brute force', 'implementation', '*1000'] |
A. Computer Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of 2 rows and n columns. Monocarp controls a character, which starts in cell (1, 1) — at the intersection of the 1-st row and the 1-st column.Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell (x_1, y_1) to cell (x_2, y_2) in one step if |x_1 - x_2| \le 1 and |y_1 - y_2| \le 1. Obviously, it is prohibited to go outside the grid.There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.To complete a level, Monocarp's character should reach cell (2, n) — at the intersection of row 2 and column n.Help Monocarp determine if it is possible to complete the level.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases. Then the test cases follow. Each test case consists of three lines.The first line contains a single integer n (3 \le n \le 100) — the number of columns.The next two lines describe the level. The i-th of these lines describes the i-th line of the level — the line consists of the characters '0' and '1'. The character '0' corresponds to a safe cell, the character '1' corresponds to a trap cell.Additional constraint on the input: cells (1, 1) and (2, n) are safe.OutputFor each test case, output YES if it is possible to complete the level, and NO otherwise.ExampleInput
4
3
000
000
4
0011
1100
4
0111
1110
6
010101
101010
Output
YES
YES
NO
YES
NoteConsider the example from the statement.In the first test case, one of the possible paths is (1, 1) \rightarrow (2, 2) \rightarrow (2, 3).In the second test case, one of the possible paths is (1, 1) \rightarrow (1, 2) \rightarrow (2, 3) \rightarrow (2, 4).In the fourth test case, one of the possible paths is (1, 1) \rightarrow (2, 2) \rightarrow (1, 3) \rightarrow (2, 4) \rightarrow (1, 5) \rightarrow (2, 6). | 4
3
000
000
4
0011
1100
4
0111
1110
6
010101
101010
| YES YES NO YES | 2 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'dp', 'implementation', '*800'] |
F. Ideal Farmtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTheofanis decided to visit his uncle's farm. There are s animals and n animal pens on the farm. For utility purpose, animal pens are constructed in one row.Uncle told Theofanis that a farm is lucky if you can distribute all animals in all pens in such a way that there are no empty pens and there is at least one continuous segment of pens that has exactly k animals in total.Moreover, a farm is ideal if it's lucky for any distribution without empty pens.Neither Theofanis nor his uncle knows if their farm is ideal or not. Can you help them to figure it out?InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of test cases.The first and only line of each test case contains three integers s, n, and k (1 \le s, n, k \le 10^{18}; n \le s).OutputFor each test case, print YES (case-insensitive), if the farm is ideal, or NO (case-insensitive) otherwise.ExampleInput
4
1 1 1
1 1 2
100 50 200
56220 47258 14497
Output
YES
NO
NO
YES
NoteFor the first and the second test case, the only possible combination is [1] so there always will be a subsegment with 1 animal but not with 2 animals. | 4
1 1 1
1 1 2
100 50 200
56220 47258 14497
| YES NO NO YES | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', '*2400'] |
E2. Rubik's Cube Coloring (hard version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is the hard version of the problem. The difference is that in this version, there are nodes with already chosen colors.Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?You have a perfect binary tree of 2^k - 1 nodes — a binary tree where all vertices i from 1 to 2^{k - 1} - 1 have exactly two children: vertices 2i and 2i + 1. Vertices from 2^{k - 1} to 2^k - 1 don't have any children. You want to color its vertices with the 6 Rubik's cube colors (White, Green, Red, Blue, Orange and Yellow).Let's call a coloring good when all edges connect nodes with colors that are neighboring sides in the Rubik's cube. A picture of Rubik's cube and its 2D map. More formally: a white node can not be neighboring with white and yellow nodes; a yellow node can not be neighboring with white and yellow nodes; a green node can not be neighboring with green and blue nodes; a blue node can not be neighboring with green and blue nodes; a red node can not be neighboring with red and orange nodes; an orange node can not be neighboring with red and orange nodes; However, there are n special nodes in the tree, colors of which are already chosen.You want to calculate the number of the good colorings of the binary tree. Two colorings are considered different if at least one node is colored with a different color.The answer may be too large, so output the answer modulo 10^9+7.InputThe first line contains the integers k (1 \le k \le 60) — the number of levels in the perfect binary tree you need to color.The second line contains the integer n (1 \le n \le \min(2^k - 1, 2000)) — the number of nodes, colors of which are already chosen.The next n lines contains integer v (1 \le v \le 2^k - 1) and string s — the index of the node and the color of the node (s is one of the white, yellow, green, blue, red and orange).It is guaranteed that each node v appears in the input at most once.OutputPrint one integer — the number of the different colorings modulo 10^9+7.ExamplesInput
3
2
5 orange
2 white
Output
1024
Input
2
2
1 white
2 white
Output
0
Input
10
3
1 blue
4 red
5 orange
Output
328925088
NoteIn the picture below, you can see one of the correct colorings of the first test example. | 3
2
5 orange
2 white
| 1024 | 3 seconds | 256 megabytes | ['brute force', 'dp', 'implementation', 'math', 'trees', '*2300'] |
E1. Rubik's Cube Coloring (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is the easy version of the problem. The difference is that in this version, there are no nodes with already chosen colors.Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?You have a perfect binary tree of 2^k - 1 nodes — a binary tree where all vertices i from 1 to 2^{k - 1} - 1 have exactly two children: vertices 2i and 2i + 1. Vertices from 2^{k - 1} to 2^k - 1 don't have any children. You want to color its vertices with the 6 Rubik's cube colors (White, Green, Red, Blue, Orange and Yellow).Let's call a coloring good when all edges connect nodes with colors that are neighboring sides in the Rubik's cube. A picture of Rubik's cube and its 2D map. More formally: a white node can not be neighboring with white and yellow nodes; a yellow node can not be neighboring with white and yellow nodes; a green node can not be neighboring with green and blue nodes; a blue node can not be neighboring with green and blue nodes; a red node can not be neighboring with red and orange nodes; an orange node can not be neighboring with red and orange nodes; You want to calculate the number of the good colorings of the binary tree. Two colorings are considered different if at least one node is colored with a different color.The answer may be too large, so output the answer modulo 10^9+7.InputThe first and only line contains the integers k (1 \le k \le 60) — the number of levels in the perfect binary tree you need to color.OutputPrint one integer — the number of the different colorings modulo 10^9+7.ExamplesInput
3
Output
24576
Input
14
Output
934234
NoteIn the picture below, you can see one of the correct colorings of the first example. | 3
| 24576 | 2 seconds | 256 megabytes | ['combinatorics', 'math', '*1300'] |
D. The Number of Imposterstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTheofanis started playing the new online game called "Among them". However, he always plays with Cypriot players, and they all have the same name: "Andreas" (the most common name in Cyprus).In each game, Theofanis plays with n other players. Since they all have the same name, they are numbered from 1 to n.The players write m comments in the chat. A comment has the structure of "i j c" where i and j are two distinct integers and c is a string (1 \le i, j \le n; i \neq j; c is either imposter or crewmate). The comment means that player i said that player j has the role c.An imposter always lies, and a crewmate always tells the truth. Help Theofanis find the maximum possible number of imposters among all the other Cypriot players, or determine that the comments contradict each other (see the notes for further explanation).Note that each player has exactly one role: either imposter or crewmate.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Description of each test case follows.The first line of each test case contains two integers n and m (1 \le n \le 2 \cdot 10^5; 0 \le m \le 5 \cdot 10^5) — the number of players except Theofanis and the number of comments.Each of the next m lines contains a comment made by the players of the structure "i j c" where i and j are two distinct integers and c is a string (1 \le i, j \le n; i \neq j; c is either imposter or crewmate).There can be multiple comments for the same pair of (i, j).It is guaranteed that the sum of all n does not exceed 2 \cdot 10^5 and the sum of all m does not exceed 5 \cdot 10^5.OutputFor each test case, print one integer — the maximum possible number of imposters. If the comments contradict each other, print -1.ExampleInput
5
3 2
1 2 imposter
2 3 crewmate
5 4
1 3 crewmate
2 5 crewmate
2 4 imposter
3 4 imposter
2 2
1 2 imposter
2 1 crewmate
3 5
1 2 imposter
1 2 imposter
3 2 crewmate
3 2 crewmate
1 3 imposter
5 0
Output
2
4
-1
2
5
NoteIn the first test case, imposters can be Andreas 2 and 3.In the second test case, imposters can be Andreas 1, 2, 3 and 5.In the third test case, comments contradict each other. This is because player 1 says that player 2 is an imposter, and player 2 says that player 1 is a crewmate. If player 1 is a crewmate, then he must be telling the truth, so player 2 must be an imposter. But if player 2 is an imposter then he must be lying, so player 1 can't be a crewmate. Contradiction. | 5
3 2
1 2 imposter
2 3 crewmate
5 4
1 3 crewmate
2 5 crewmate
2 4 imposter
3 4 imposter
2 2
1 2 imposter
2 1 crewmate
3 5
1 2 imposter
1 2 imposter
3 2 crewmate
3 2 crewmate
1 3 imposter
5 0
| 2 4 -1 2 5 | 3 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'dp', 'dsu', 'graphs', '*1700'] |
C. Make Them Equaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTheofanis has a string s_1 s_2 \dots s_n and a character c. He wants to make all characters of the string equal to c using the minimum number of operations.In one operation he can choose a number x (1 \le x \le n) and for every position i, where i is not divisible by x, replace s_i with c. Find the minimum number of operations required to make all the characters equal to c and the x-s that he should use in his operations.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 the integer n (3 \le n \le 3 \cdot 10^5) and a lowercase Latin letter c — the length of the string s and the character the resulting string should consist of.The second line of each test case contains a string s of lowercase Latin letters — the initial string.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, firstly print one integer m — the minimum number of operations required to make all the characters equal to c.Next, print m integers x_1, x_2, \dots, x_m (1 \le x_j \le n) — the x-s that should be used in the order they are given.It can be proved that under given constraints, an answer always exists. If there are multiple answers, print any.ExampleInput
3
4 a
aaaa
4 a
baaa
4 b
bzyx
Output
0
1
2
2
2 3
NoteLet's describe what happens in the third test case: x_1 = 2: we choose all positions that are not divisible by 2 and replace them, i. e. bzyx \rightarrow bzbx; x_2 = 3: we choose all positions that are not divisible by 3 and replace them, i. e. bzbx \rightarrow bbbb. | 3
4 a
aaaa
4 a
baaa
4 b
bzyx
| 0 1 2 2 2 3 | 2 seconds | 256 megabytes | ['brute force', 'greedy', 'math', 'strings', '*1200'] |
B. Special Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTheofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers.Let's call a positive number special if it can be written as a sum of different non-negative powers of n. For example, for n = 4 number 17 is special, because it can be written as 4^0 + 4^2 = 1 + 16 = 17, but 9 is not.Theofanis asks you to help him find the k-th special number if they are sorted in increasing order. Since this number may be too large, output it modulo 10^9+7.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first and only line of each test case contains two integers n and k (2 \le n \le 10^9; 1 \le k \le 10^9).OutputFor each test case, print one integer — the k-th special number in increasing order modulo 10^9+7.ExampleInput
3
3 4
2 12
105 564
Output
9
12
3595374
NoteFor n = 3 the sequence is [1,3,4,9...] | 3
3 4
2 12
105 564
| 9 12 3595374 | 2 seconds | 256 megabytes | ['bitmasks', 'math', '*1100'] |
A. Consecutive Sum Riddletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTheofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi for free (Cypriot cheese).You are given an integer n. You need to find two integers l and r such that -10^{18} \le l < r \le 10^{18} and l + (l + 1) + \ldots + (r - 1) + r = n.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first and only line of each test case contains a single integer n (1 \le n \le 10^{18}).OutputFor each test case, print the two integers l and r such that -10^{18} \le l < r \le 10^{18} and l + (l + 1) + \ldots + (r - 1) + r = n. It can be proven that an answer always exists. If there are multiple answers, print any.ExampleInput
7
1
2
3
6
100
25
3000000000000
Output
0 1
-1 2
1 2
1 3
18 22
-2 7
999999999999 1000000000001NoteIn the first test case, 0 + 1 = 1.In the second test case, (-1) + 0 + 1 + 2 = 2.In the fourth test case, 1 + 2 + 3 = 6.In the fifth test case, 18 + 19 + 20 + 21 + 22 = 100.In the sixth test case, (-2) + (-1) + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 = 25. | 7
1
2
3
6
100
25
3000000000000
| 0 1 -1 2 1 2 1 3 18 22 -2 7 999999999999 1000000000001 | 2 seconds | 256 megabytes | ['math', '*800'] |
G. Changing Bracketstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of round and square brackets is given. You can change the sequence by performing the following operations: change the direction of a bracket from opening to closing and vice versa without changing the form of the bracket: i.e. you can change '(' to ')' and ')' to '('; you can change '[' to ']' and ']' to '['. The operation costs 0 burles. change any square bracket to round bracket having the same direction: i.e. you can change '[' to '(' but not from '(' to '['; similarly, you can change ']' to ')' but not from ')' to ']'. The operation costs 1 burle. The operations can be performed in any order any number of times.You are given a string s of the length n and q queries of the type "l r" where 1 \le l < r \le n. For every substring s[l \dots r], find the minimum cost to pay to make it a correct bracket sequence. It is guaranteed that the substring s[l \dots r] has an even length.The queries must be processed independently, i.e. the changes made in the string for the answer to a question i don't affect the queries j (j > i). In other words, for every query, the substring s[l \dots r] is given from the initially given string s.A correct bracket sequence is a sequence that can be built according the following rules: an empty sequence is a correct bracket sequence; if "s" is a correct bracket sequence, the sequences "(s)" and "[s]" are correct bracket sequences. if "s" and "t" are correct bracket sequences, the sequence "st" (the concatenation of the sequences) is a correct bracket sequence. E.g. the sequences "", "(()[])", "[()()]()" and "(())()" are correct bracket sequences whereas "(", "[(])" and ")))" are not.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.For each test case, the first line contains a non-empty string s containing only round ('(', ')') and square ('[', ']') brackets. The length of the string doesn't exceed 10^6. The string contains at least 2 characters.The second line contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries.Then q lines follow, each of them contains two integers l and r (1 \le l < r \le n where n is the length of s). It is guaranteed that the substring s[l \dots r] has even length.It is guaranteed that the sum of the lengths of all strings given in all test cases doesn't exceed 10^6. The sum of all q given in all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case output in a separate line for each query one integer x (x \ge 0) — the minimum cost to pay to make the given substring a correct bracket sequence.ExampleInput
3
([))[)()][]]
3
1 12
4 9
3 6
))))))
2
2 3
1 4
[]
1
1 2
Output
0
2
1
0
0
0
NoteConsider the first test case. The first query describes the whole given string, the string can be turned into the following correct bracket sequence: "([()])()[[]]". The forms of the brackets aren't changed so the cost of changing is 0.The second query describes the substring ")[)()]". It may be turned into "(()())", the cost is equal to 2.The third query describes the substring "))[)". It may be turned into "()()", the cost is equal to 1.The substrings of the second test case contain only round brackets. It's possible to prove that any sequence of round brackets having an even length may be turned into a correct bracket sequence for the cost of 0 burles.In the third test case, the single query describes the string "[]" that is already a correct bracket sequence. | 3
([))[)()][]]
3
1 12
4 9
3 6
))))))
2
2 3
1 4
[]
1
1 2
| 0 2 1 0 0 0 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'dp', 'greedy', '*2200'] |
F. Red-Black Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is given a non-negative integer x, the decimal representation of which contains n digits. You need to color each its digit in red or black, so that the number formed by the red digits is divisible by A, and the number formed by the black digits is divisible by B.At least one digit must be colored in each of two colors. Consider, the count of digits colored in red is r and the count of digits colored in black is b. Among all possible colorings of the given number x, you need to output any such that the value of |r - b| is the minimum possible.Note that the number x and the numbers formed by digits of each color, may contain leading zeros. Example of painting a number for A = 3 and B = 13 The figure above shows an example of painting the number x = 02165 of n = 5 digits for A = 3 and B = 13. The red digits form the number 015, which is divisible by 3, and the black ones — 26, which is divisible by 13. Note that the absolute value of the difference between the counts of red and black digits is 1, it is impossible to achieve a smaller value.InputThe first line contains one integer t (1 \le t \le 10) — the number of test cases. Then t test cases follow.Each test case consists of two lines. The first line contains three integers n, A, B (2 \le n \le 40, 1 \le A, B \le 40). The second line contains a non-negative integer x containing exactly n digits and probably containing leading zeroes.OutputFor each test case, output in a separate line: -1 if the desired coloring does not exist; a string s of n characters, each of them is a letter 'R' or 'B'. If the i-th digit of the number x is colored in red, then the i-th character of the string s must be the letter 'R', otherwise the letter 'B'. The number formed by digits colored red should divisible by A. The number formed by digits colored black should divisible by B. The value |r-b| should be minimal, where r is the count of red digits, b is the count of black digits. If there are many possible answers, print any of them.ExampleInput
4
5 3 13
02165
4 2 1
1357
8 1 1
12345678
2 7 9
90
Output
RBRBR
-1
BBRRRRBB
BR
NoteThe first test case is considered in the statement.In the second test case, there are no even digits, so it is impossible to form a number from its digits that is divisible by 2.In the third test case, each coloring containing at least one red and one black digit is possible, so you can color 4 digits in red and 4 in black (|4 - 4| = 0, it is impossible to improve the result).In the fourth test case, there is a single desired coloring. | 4
5 3 13
02165
4 2 1
1357
8 1 1
12345678
2 7 9
90
| RBRBR -1 BBRRRRBB BR | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'implementation', 'math', 'meet-in-the-middle', '*2100'] |
E. Gardener and Treetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tree is an undirected connected graph in which there are no cycles. This problem is about non-rooted trees. A leaf of a tree is a vertex that is connected to at most one vertex.The gardener Vitaly grew a tree from n vertices. He decided to trim the tree. To do this, he performs a number of operations. In one operation, he removes all leaves of the tree. Example of a tree. For example, consider the tree shown in the figure above. The figure below shows the result of applying exactly one operation to the tree. The result of applying the operation "remove all leaves" to the tree. Note the special cases of the operation: applying an operation to an empty tree (of 0 vertices) does not change it; applying an operation to a tree of one vertex removes this vertex (this vertex is treated as a leaf); applying an operation to a tree of two vertices removes both vertices (both vertices are treated as leaves). Vitaly applied k operations sequentially to the tree. How many vertices remain?InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.Each test case is preceded by an empty line.Each test case consists of several lines. The first line of the test case contains two integers n and k (1 \le n \le 4 \cdot 10^5, 1 \le k \le 2 \cdot 10^5) — the number of vertices in the tree and the number of operations, respectively. Then n - 1 lines follow, each of them contains two integers u and v (1 \le u, v \le n, u \neq v) which describe a pair of vertices connected by an edge. It is guaranteed that the given graph is a tree and has no loops or multiple edges.It is guaranteed that the sum of n from all test cases does not exceed 4 \cdot 10^5.OutputFor each test case output on a separate line a single integer — the number of vertices that remain in the tree after applying k operations.ExampleInput
6
14 1
1 2
2 3
2 4
4 5
4 6
2 7
7 8
8 9
8 10
3 11
3 12
1 13
13 14
2 200000
1 2
3 2
1 2
2 3
5 1
5 1
3 2
2 1
5 4
6 2
5 1
2 5
5 6
4 2
3 4
7 1
4 3
5 1
1 3
6 1
1 7
2 1
Output
7
0
0
3
1
2
NoteThe first test case is considered in the statement.The second test case contains a tree of two vertices. 200000 operations are applied to it. The first one removes all two vertices, the other operations do not change the tree.In the third test case, a tree of three vertices is given. As a result of the first operation, only 1 vertex remains in it (with the index 2), the second operation makes the tree empty. | 6
14 1
1 2
2 3
2 4
4 5
4 6
2 7
7 8
8 9
8 10
3 11
3 12
1 13
13 14
2 200000
1 2
3 2
1 2
2 3
5 1
5 1
3 2
2 1
5 4
6 2
5 1
2 5
5 6
4 2
3 4
7 1
4 3
5 1
1 3
6 1
1 7
2 1
| 7 0 0 3 1 2 | 4 seconds | 256 megabytes | ['brute force', 'data structures', 'dfs and similar', 'greedy', 'implementation', 'trees', '*1600'] |
D2. Half of Sametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is a complicated version of D1, but it has significant differences, so read the whole statement.Polycarp has an array of n (n is even) integers a_1, a_2, \dots, a_n. Polycarp conceived of a positive integer k. After that, Polycarp began performing the following operations on the array: take an index i (1 \le i \le n) and reduce the number a_i by k.After Polycarp performed some (possibly zero) number of such operations, it turned out that at least half of the numbers in the array became the same. Find the maximum k at which such a situation is possible, or print -1 if such a number can be arbitrarily large.InputThe first line contains one integer t (1 \le t \le 10) — the number of test cases. Then t test cases follow.Each test case consists of two lines. The first line contains an even integer n (4 \le n \le 40) (n is even). The second line contains n integers a_1, a_2, \dots a_n (-10^6 \le a_i \le 10^6).It is guaranteed that the sum of all n specified in the given test cases does not exceed 100.OutputFor each test case output on a separate line an integer k (k \ge 1) — the maximum possible number that Polycarp used in operations on the array, or -1, if such a number can be arbitrarily large.ExampleInput
4
6
48 13 22 -15 16 35
8
-1 0 1 -1 0 1 -1 0
4
100 -1000 -1000 -1000
4
1 1 1 1
Output
13
2
-1
-1
| 4
6
48 13 22 -15 16 35
8
-1 0 1 -1 0 1 -1 0
4
100 -1000 -1000 -1000
4
1 1 1 1
| 13 2 -1 -1 | 1 second | 256 megabytes | ['brute force', 'math', 'number theory', '*1900'] |
D1. All are Sametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is a simplified version of D2, but it has significant differences, so read the whole statement.Polycarp has an array of n (n is even) integers a_1, a_2, \dots, a_n. Polycarp conceived of a positive integer k. After that, Polycarp began performing the following operations on the array: take an index i (1 \le i \le n) and reduce the number a_i by k.After Polycarp performed some (possibly zero) number of such operations, it turned out that all numbers in the array became the same. Find the maximum k at which such a situation is possible, or print -1 if such a number can be arbitrarily large.InputThe first line contains one integer t (1 \le t \le 10) — the number of test cases. Then t test cases follow.Each test case consists of two lines. The first line contains an even integer n (4 \le n \le 40) (n is even). The second line contains n integers a_1, a_2, \dots a_n (-10^6 \le a_i \le 10^6).It is guaranteed that the sum of all n specified in the given test cases does not exceed 100.OutputFor each test case output on a separate line an integer k (k \ge 1) — the maximum possible number that Polycarp used in operations on the array, or -1, if such a number can be arbitrarily large.ExampleInput
3
6
1 5 3 1 1 5
8
-1 0 1 -1 0 1 -1 0
4
100 -1000 -1000 -1000
Output
2
1
1100
| 3
6
1 5 3 1 1 5
8
-1 0 1 -1 0 1 -1 0
4
100 -1000 -1000 -1000
| 2 1 1100 | 1 second | 256 megabytes | ['math', 'number theory', '*1100'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.