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
A. Reordertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that \sum_{i=1}^{n}{\sum_{j=i}^{n}{\frac{a_j}{j}}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, \frac{5}{2}=2.5.InputThe first line contains a single integer t — the number of test cases (1 \le t \le 100). The test cases follow, each in two lines.The first line of a test case contains two integers n and m (1 \le n \le 100, 0 \le m \le 10^6). The second line contains integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^6) — the elements of the array.OutputFor each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise.ExampleInput 2 3 8 2 5 1 4 4 0 1 2 3 Output YES NO NoteIn the first test case one of the reorders could be [1, 2, 5]. The sum is equal to (\frac{1}{1} + \frac{2}{2} + \frac{5}{3}) + (\frac{2}{2} + \frac{5}{3}) + (\frac{5}{3}) = 8. The brackets denote the inner sum \sum_{j=i}^{n}{\frac{a_j}{j}}, while the summation of brackets corresponds to the sum over i.
2 3 8 2 5 1 4 4 0 1 2 3
YES NO
1 second
256 megabytes
['math', '*800']
E. A Convex Gametime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputShikamaru and Asuma like to play different games, and sometimes they play the following: given an increasing list of numbers, they take turns to move. Each move consists of picking a number from the list.Assume the picked numbers are v_{i_1}, v_{i_2}, \ldots, v_{i_k}. The following conditions must hold: i_{j} < i_{j+1} for all 1 \leq j \leq k-1; v_{i_{j+1}} - v_{i_j} < v_{i_{j+2}} - v_{i_{j+1}} for all 1 \leq j \leq k-2. However, it's easy to play only one instance of game, so today Shikamaru and Asuma decided to play n simultaneous games. They agreed on taking turns as for just one game, Shikamaru goes first. At each turn, the player performs a valid move in any single game. The player who cannot move loses. Find out who wins, provided that both play optimally.InputThe first line contains the only integer n (1 \leq n \leq 1000) standing for the number of games Shikamaru and Asuma play at once. Next lines describe the games.Each description starts from a line with the only number m (m\geq 1) denoting the length of the number list. The second line contains the increasing space-separated sequence v_1, v_2, ..., v_m from the game (1 \leq v_{1} < v_{2} < ... < v_{m} \leq 10^{5}).The total length of all sequences doesn't exceed 10^5.OutputPrint "YES" if Shikamaru can secure the victory, and "NO" otherwise.ExamplesInput 1 10 1 2 3 4 5 6 7 8 9 10 Output YES Input 2 10 1 2 3 4 5 6 7 8 9 10 10 1 2 3 4 5 6 7 8 9 10 Output NO Input 4 7 14404 32906 41661 47694 51605 75933 80826 5 25374 42550 60164 62649 86273 2 7002 36731 8 23305 45601 46404 47346 47675 58125 74092 87225 Output NO NoteIn the first example Shikamaru can pick the last number, and Asuma cannot do anything because of the first constraint.In the second sample test Asuma can follow the symmetric strategy, repeating Shikamaru's moves in the other instance each time, and therefore win.
1 10 1 2 3 4 5 6 7 8 9 10
YES
3 seconds
512 megabytes
['dsu', 'games', '*3500']
G. Reducing Delivery Costtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are a mayor of Berlyatov. There are n districts and m two-way roads between them. The i-th road connects districts x_i and y_i. The cost of travelling along this road is w_i. There is some path between each pair of districts, so the city is connected.There are k delivery routes in Berlyatov. The i-th route is going from the district a_i to the district b_i. There is one courier on each route and the courier will always choose the cheapest (minimum by total cost) path from the district a_i to the district b_i to deliver products.The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).You can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with 0).Let d(x, y) be the cheapest cost of travel between districts x and y.Your task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with 0. In other words, you have to find the minimum possible value of \sum\limits_{i = 1}^{k} d(a_i, b_i) after applying the operation described above optimally.InputThe first line of the input contains three integers n, m and k (2 \le n \le 1000; n - 1 \le m \le min(1000, \frac{n(n-1)}{2}); 1 \le k \le 1000) — the number of districts, the number of roads and the number of courier routes.The next m lines describe roads. The i-th road is given as three integers x_i, y_i and w_i (1 \le x_i, y_i \le n; x_i \ne y_i; 1 \le w_i \le 1000), where x_i and y_i are districts the i-th road connects and w_i is its cost. It is guaranteed that there is some path between each pair of districts, so the city is connected. It is also guaranteed that there is at most one road between each pair of districts.The next k lines describe courier routes. The i-th route is given as two integers a_i and b_i (1 \le a_i, b_i \le n) — the districts of the i-th route. The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).OutputPrint one integer — the minimum total courier routes cost you can achieve (i.e. the minimum value \sum\limits_{i=1}^{k} d(a_i, b_i), where d(x, y) is the cheapest cost of travel between districts x and y) if you can make some (at most one) road cost zero.ExamplesInput 6 5 2 1 2 5 2 3 7 2 4 4 4 5 2 4 6 8 1 6 5 3 Output 22 Input 5 5 4 1 2 5 2 3 4 1 4 3 4 3 7 3 5 2 1 5 1 3 3 3 1 5 Output 13 NoteThe picture corresponding to the first example:There, you can choose either the road (2, 4) or the road (4, 6). Both options lead to the total cost 22.The picture corresponding to the second example:There, you can choose the road (3, 4). This leads to the total cost 13.
6 5 2 1 2 5 2 3 7 2 4 4 4 5 2 4 6 8 1 6 5 3
22
1 second
256 megabytes
['brute force', 'graphs', 'shortest paths', '*2100']
F. Zero Remainder Sum time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix a of size n \times m consisting of integers.You can choose no more than \left\lfloor\frac{m}{2}\right\rfloor elements in each row. Your task is to choose these elements in such a way that their sum is divisible by k and this sum is the maximum.In other words, you can choose no more than a half (rounded down) of elements in each row, you have to find the maximum sum of these elements divisible by k.Note that you can choose zero elements (and the sum of such set is 0).InputThe first line of the input contains three integers n, m and k (1 \le n, m, k \le 70) — the number of rows in the matrix, the number of columns in the matrix and the value of k. The next n lines contain m elements each, where the j-th element of the i-th row is a_{i, j} (1 \le a_{i, j} \le 70).OutputPrint one integer — the maximum sum divisible by k you can obtain.ExamplesInput 3 4 3 1 2 3 4 5 2 2 2 7 1 1 4 Output 24 Input 5 5 4 1 2 4 2 1 3 5 1 2 4 1 5 7 1 2 3 8 7 1 2 8 4 7 1 6 Output 56 NoteIn the first example, the optimal answer is 2 and 4 in the first row, 5 and 2 in the second row and 7 and 4 in the third row. The total sum is 2 + 4 + 5 + 2 + 7 + 4 = 24.
3 4 3 1 2 3 4 5 2 2 2 7 1 1 4
24
1 second
256 megabytes
['dp', '*2100']
E. Two Round Dancestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, n people (n is an even number) met on a plaza and made two round dances, each round dance consists of exactly \frac{n}{2} people. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly \frac{n}{2} people. Each person should belong to exactly one of these two round dances.Round dance is a dance circle consisting of 1 or more people. Two round dances are indistinguishable (equal) if one can be transformed to another by choosing the first participant. For example, round dances [1, 3, 4, 2], [4, 2, 1, 3] and [2, 1, 3, 4] are indistinguishable.For example, if n=2 then the number of ways is 1: one round dance consists of the first person and the second one of the second person.For example, if n=4 then the number of ways is 3. Possible options: one round dance — [1,2], another — [3,4]; one round dance — [2,4], another — [3,1]; one round dance — [4,1], another — [3,2]. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly \frac{n}{2} people.InputThe input contains one integer n (2 \le n \le 20), n is an even number.OutputPrint one integer — the number of ways to make two round dances. It is guaranteed that the answer fits in the 64-bit integer data type.ExamplesInput2Output1Input4Output3Input8Output1260Input20Output12164510040883200
Input2
Output1
1 second
256 megabytes
['combinatorics', 'math', '*1300']
D. Districts Connectiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).If two districts belonging to the same gang are connected directly with a road, this gang will revolt.You don't want this so your task is to build n-1 two-way roads in such a way that all districts are reachable from each other (possibly, using intermediate districts) and each pair of directly connected districts belong to different gangs, or determine that it is impossible to build n-1 roads to satisfy all the conditions.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 500) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (2 \le n \le 5000) — the number of districts. The second line of the test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9), where a_i is the gang the i-th district belongs to.It is guaranteed that the sum of n does not exceed 5000 (\sum n \le 5000).OutputFor each test case, print: NO on the only line if it is impossible to connect all districts satisfying the conditions from the problem statement. YES on the first line and n-1 roads on the next n-1 lines. Each road should be presented as a pair of integers x_i and y_i (1 \le x_i, y_i \le n; x_i \ne y_i), where x_i and y_i are two districts the i-th road connects. For each road i, the condition a[x_i] \ne a[y_i] should be satisfied. Also, all districts should be reachable from each other (possibly, using intermediate districts).ExampleInput 4 5 1 2 2 1 3 3 1 1 1 4 1 1000 101 1000 4 1 2 3 4 Output YES 1 3 3 5 5 4 1 2 NO YES 1 2 2 3 3 4 YES 1 2 1 3 1 4
4 5 1 2 2 1 3 3 1 1 1 4 1 1000 101 1000 4 1 2 3 4
YES 1 3 3 5 5 4 1 2 NO YES 1 2 2 3 3 4 YES 1 2 1 3 1 4
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', '*1200']
C. Dominant Piranhatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n piranhas with sizes a_1, a_2, \ldots, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the aquarium (except itself, of course). Other piranhas will do nothing while the dominant piranha will eat them.Because the aquarium is pretty narrow and long, the piranha can eat only one of the adjacent piranhas during one move. Piranha can do as many moves as it needs (or as it can). More precisely: The piranha i can eat the piranha i-1 if the piranha i-1 exists and a_{i - 1} < a_i. The piranha i can eat the piranha i+1 if the piranha i+1 exists and a_{i + 1} < a_i. When the piranha i eats some piranha, its size increases by one (a_i becomes a_i + 1).Your task is to find any dominant piranha in the aquarium or determine if there are no such piranhas.Note that you have to find any (exactly one) dominant piranha, you don't have to find all of them.For example, if a = [5, 3, 4, 4, 5], then the third piranha can be dominant. Consider the sequence of its moves: The piranha eats the second piranha and a becomes [5, \underline{5}, 4, 5] (the underlined piranha is our candidate). The piranha eats the third piranha and a becomes [5, \underline{6}, 5]. The piranha eats the first piranha and a becomes [\underline{7}, 5]. The piranha eats the second piranha and a becomes [\underline{8}]. You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (2 \le n \le 3 \cdot 10^5) — the number of piranhas in the aquarium. The second line of the test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9), where a_i is the size of the i-th piranha.It is guaranteed that the sum of n does not exceed 3 \cdot 10^5 (\sum n \le 3 \cdot 10^5).OutputFor each test case, print the answer: -1 if there are no dominant piranhas in the aquarium or index of any dominant piranha otherwise. If there are several answers, you can print any.ExampleInput 6 5 5 3 4 4 5 3 1 1 1 5 4 4 3 4 4 5 5 5 4 3 2 3 1 1 2 5 5 4 3 5 5 Output 3 -1 4 3 3 1 NoteThe first test case of the example is described in the problem statement.In the second test case of the example, there are no dominant piranhas in the aquarium.In the third test case of the example, the fourth piranha can firstly eat the piranha to the left and the aquarium becomes [4, 4, 5, 4], then it can eat any other piranha in the aquarium.
6 5 5 3 4 4 5 3 1 1 1 5 4 4 3 4 4 5 5 5 4 3 2 3 1 1 2 5 5 4 3 5 5
3 -1 4 3 3 1
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*900']
B. Yet Another Bookshelftime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r the condition a_i = 1 holds) and: Shift it to the right by 1: move the book at index i to i + 1 for all l \le i \le r. This move can be done only if r+1 \le n and there is no book at the position r+1. Shift it to the left by 1: move the book at index i to i-1 for all l \le i \le r. This move can be done only if l-1 \ge 1 and there is no book at the position l-1. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for a = [0, 0, 1, 0, 1] there is a gap between books (a_4 = 0 when a_3 = 1 and a_5 = 1), for a = [1, 1, 0] there are no gaps between books and for a = [0, 0,0] there are also no gaps between books.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 200) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 50) — the number of places on a bookshelf. The second line of the test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 1), where a_i is 1 if there is a book at this position and 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.OutputFor each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).ExampleInput 5 7 0 0 1 0 1 0 1 3 1 0 0 5 1 1 0 0 1 6 1 0 0 0 0 1 5 1 1 0 1 1 Output 2 0 2 4 1 NoteIn the first test case of the example, you can shift the segment [3; 3] to the right and the segment [4; 5] to the right. After all moves, the books form the contiguous segment [5; 7]. So the answer is 2.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment [5; 5] to the left and then the segment [4; 4] to the left again. After all moves, the books form the contiguous segment [1; 3]. So the answer is 2.In the fourth test case of the example, you can shift the segment [1; 1] to the right, the segment [2; 2] to the right, the segment [6; 6] to the left and then the segment [5; 5] to the left. After all moves, the books form the contiguous segment [3; 4]. So the answer is 4.In the fifth test case of the example, you can shift the segment [1; 2] to the right. After all moves, the books form the contiguous segment [2; 5]. So the answer is 1.
5 7 0 0 1 0 1 0 1 3 1 0 0 5 1 1 0 0 1 6 1 0 0 0 0 1 5 1 1 0 1 1
2 0 2 4 1
1 second
256 megabytes
['greedy', 'implementation', '*800']
A. Boring Apartmentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone answers the call, in the following order: First he calls all apartments consisting of digit 1, in increasing order (1, 11, 111, 1111). Next he calls all apartments consisting of digit 2, in increasing order (2, 22, 222, 2222) And so on. The resident of the boring apartment x answers the call, and our character stops calling anyone further.Our character wants to know how many digits he pressed in total and your task is to help him to count the total number of keypresses.For example, if the resident of boring apartment 22 answered, then our character called apartments with numbers 1, 11, 111, 1111, 2, 22 and the total number of digits he pressed is 1 + 2 + 3 + 4 + 1 + 2 = 13.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 36) — the number of test cases.The only line of the test case contains one integer x (1 \le x \le 9999) — the apartment number of the resident who answered the call. It is guaranteed that x consists of the same digit.OutputFor each test case, print the answer: how many digits our character pressed in total.ExampleInput 4 22 9999 1 777 Output 13 90 1 66
4 22 9999 1 777
13 90 1 66
1 second
256 megabytes
['implementation', 'math', '*800']
J. Zero-XOR Arraytime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of integers a of size n. This array is non-decreasing, i. e. a_1 \le a_2 \le \dots \le a_n.You have to find arrays of integers b of size 2n - 1, such that: b_{2i-1} = a_i (1 \le i \le n); array b is non-decreasing; b_1 \oplus b_2 \oplus \dots \oplus b_{2n-1} = 0 (\oplus denotes bitwise XOR operation: https://en.wikipedia.org/wiki/Exclusive_or. In Kotlin, it is xor function). Calculate the number of arrays that meet all the above conditions, modulo 998244353.InputThe first line contains a single integer n (2 \le n \le 17) — the size of the array a.The second line contains n integers (0 \le a_i \le 2^{60} - 1; a_i \le a_{i+1}) — elements of the array a.OutputPrint a single integer — the number of arrays that meet all the above conditions, modulo 998244353.ExamplesInput 3 0 1 3 Output 2 Input 4 0 3 6 7 Output 6 Input 5 1 5 9 10 23 Output 20 Input 10 39 62 64 79 81 83 96 109 120 122 Output 678132
3 0 1 3
2
6 seconds
256 megabytes
['*special problem', 'dp', '*3400']
I. Cyclic Shiftstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a matrix consisting of n rows and m columns. The matrix contains lowercase letters of the Latin alphabet.You can perform the following operation any number of times you want to: choose two integers i (1 \le i \le m) and k (0 < k < n), and shift every column j such that i \le j \le m cyclically by k. The shift is performed upwards.For example, if you have a matrix \left( \begin{array} \\ a & b & c \\ d & e & f \\ g & h & i \end{array}\right) and perform an operation with i = 2, k = 1, then it becomes: \left( \begin{array} \\ a & e & f \\ d & h & i \\ g & b & c \end{array}\right) You have to process q queries. Each of the queries is a string of length m consisting of lowercase letters of the Latin alphabet. For each query, you have to calculate the minimum number of operations described above you have to perform so that at least one row of the matrix is equal to the string from the query. Note that all queries are independent, that is, the operations you perform in a query don't affect the initial matrix in other queries.InputThe first line contains three integers n, m, q (2 \le n, m, q \le 2.5 \cdot 10^5; n \cdot m \le 5 \cdot 10^5; q \cdot m \le 5 \cdot 10^5) — the number of rows and columns in the matrix and the number of queries, respectively.The next n lines contains m lowercase Latin letters each — elements of the matrix.The following q lines contains a description of queries — strings of length m consisting of lowercase letters of the Latin alphabet.OutputPrint q integers. The i-th integer should be equal to the minimum number of operations you have to perform so that the matrix contains a string from the i-th query or -1 if the specified string cannot be obtained.ExamplesInput 3 5 4 abacc ccbba ccabc abacc acbbc ababa acbbc Output 0 2 1 2 Input 6 4 4 daac bcba acad cbdc aaaa bcbb dcdd acba bbbb dbcd Output 3 1 2 -1 Input 5 10 5 ltjksdyfgg cbhpsereqn ijndtzbzcf ghgcgeadep bfzdgxqmqe ibgcgzyfep bbhdgxqmqg ltgcgxrzep ljnpseldgn ghhpseyzcf Output 5 3 5 -1 3
3 5 4 abacc ccbba ccabc abacc acbbc ababa acbbc
0 2 1 2
3 seconds
512 megabytes
['*special problem', 'strings', '*2900']
H. Rogue-like Gametime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMarina plays a new rogue-like game. In this game, there are n different character species and m different classes. The game is played in runs; for each run, Marina has to select a species and a class for her character. If she selects the i-th species and the j-th class, she will get c_{i, j} points for this run.Initially, some species and classes are unlocked, all others are locked. To unlock the i-th species, Marina has to get at least a_i points in total for previous runs — that is, as soon as her total score for played runs is at least a_i, this species is unlocked. Similarly, to unlock the j-th class, she has to get at least b_j points in total for previous runs. If a_i = 0 for some i, then this species is unlocked initially (the same applies to classes with b_j = 0).Marina wants to unlock all species and classes in the minimum number of runs. Before playing the game, she can read exactly one guide on some combination of species and class, and reading a guide will increase the score she gets for all runs with that combination by k (formally, before playing the game, she can increase exactly one value of c_{i, j} by k).What is the minimum number of runs she has to play to unlock all species and classes if she chooses the combination to read a guide on optimally?InputThe first line contains three integers n, m and k (1 \le n, m \le 1500; 0 \le k \le 10^9).The second line contains n integers a_1, a_2, ..., a_n (0 = a_1 \le a_2 \le \dots \le a_n \le 10^{12}), where a_i is the number of points required to unlock the i-th species (or 0, if it is unlocked initially). Note that a_1 = 0, and these values are non-descending.The third line contains m integers b_1, b_2, ..., b_m (0 = b_1 \le b_2 \le \dots \le b_m \le 10^{12}), where b_i is the number of points required to unlock the i-th class (or 0, if it is unlocked initially). Note that b_1 = 0, and these values are non-descending.Then n lines follow, each of them contains m integers. The j-th integer in the i-th line is c_{i, j} (1 \le c_{i, j} \le 10^9) — the score Marina gets for a run with the i-th species and the j-th class.OutputPrint one integer — the minimum number of runs Marina has to play to unlock all species and all classes if she can read exactly one guide before playing the game.ExamplesInput 3 4 2 0 5 7 0 2 6 10 2 5 5 2 5 3 4 4 3 4 2 4 Output 3 Input 4 2 1 0 3 9 9 0 2 3 3 5 1 1 3 2 3 Output 2 Input 3 3 5 0 8 11 0 0 3 3 1 3 1 2 1 1 1 3 Output 2 NoteThe explanation for the first test: Marina reads a guide on the combination of the 1-st species and the 2-nd class. Thus, c_{1, 2} becomes 7. Initially, only the 1-st species and the 1-st class are unlocked. Marina plays a run with the 1-st species and the 1-st class. Her score becomes 2, and she unlocks the 2-nd class. Marina plays a run with the 1-st species and the 2-nd class. Her score becomes 9, and she unlocks everything except the 4-th class. Marina plays a run with the 3-rd species and the 3-rd class. Her score becomes 11, and she unlocks the 4-th class. She has unlocked everything in 3 runs. Note that this way to unlock everything is not the only one.The explanation for the second test: Marina reads a guide on the combination of the 2-nd species and the 1-st class. Thus, c_{2, 1} becomes 6. Initially, only the 1-st species and the 1-st class are unlocked. Marina plays a run with the 1-st species and the 1-st class. Her score becomes 3, and she unlocks the 2-nd species and the 2-nd class. Marina plays a run with the 2-nd species and the 1-st class. Her score becomes 9, and she unlocks the 3-rd species and the 4-th species. She has unlocked everything in 2 runs. As in the 1-st example, this is not the only way to unlock everything in 2 runs.
3 4 2 0 5 7 0 2 6 10 2 5 5 2 5 3 4 4 3 4 2 4
3
4 seconds
256 megabytes
['*special problem', 'brute force', 'greedy', 'two pointers', '*2600']
G. Number Deletion Gametime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice and Bob play a game. They have a set that initially consists of n integers. The game is played in k turns. During each turn, the following events happen: firstly, Alice chooses an integer from the set. She can choose any integer except for the maximum one. Let the integer chosen by Alice be a; secondly, Bob chooses an integer from the set. He can choose any integer that is greater than a. Let the integer chosen by Bob be b; finally, both a and b are erased from the set, and the value of b - a is added to the score of the game. Initially, the score is 0. Alice wants to maximize the resulting score, Bob wants to minimize it. Assuming that both Alice and Bob play optimally, calculate the resulting score of the game.InputThe first line contains two integers n and k (2 \le n \le 400, 1 \le k \le \lfloor\frac{n}{2}\rfloor) — the initial size of the set and the number of turns in the game.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6) — the initial contents of the set. These integers are pairwise distinct.OutputPrint one integer — the resulting score of the game (assuming that both Alice and Bob play optimally).ExamplesInput 5 2 3 4 1 5 2 Output 4 Input 7 3 101 108 200 1 201 109 100 Output 283
5 2 3 4 1 5 2
4
2 seconds
512 megabytes
['*special problem', 'dp', 'games', 'greedy', '*2100']
F. Neural Network Problemtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to train a neural network model for your graduation work. There are n images in the dataset, the i-th image's size is a_i bytes.You don't have any powerful remote servers to train this model so you have to do it on your local machine. But there is a problem: the total size of the dataset is too big for your machine, so you decided to remove some images — though you don't want to make the dataset too weak so you can remove no more than k images from it. Note that you can only remove images, you can't change their order.You want to remove these images optimally so you came up with a metric (you're a data scientist after all) that allows to measure the result of removals. Consider the array b_1, b_2, \ldots, b_m after removing at most k images (n - k \le m \le n). The data from this array will be uploaded to the machine in blocks of x consecutive elements each. More precisely: elements with indices from 1 to x (b_1, b_2, \ldots, b_x) belong to the first block; elements with indices from x + 1 to 2x (b_{x + 1}, b_{x + 2}, \ldots, b_{2x}) belong to the second block; elements with indices from 2x + 1 to 3x (b_{2x + 1}, b_{2x + 2}, \ldots, b_{3x}) belong to the third block; and so on. There will be cnt = \left\lceil\frac{m}{x}\right\rceil blocks in total. Note that if m is not divisible by x then the last block contains less than x elements, and it's okay.Let w(i) be the total size of the i-th block — that is, the sum of sizes of images inside this block. For example, the size of the first block w(1) is b_1 + b_2 + \ldots + b_x, the size of the second block w(2) is b_{x + 1} + b_{x + 2} + \ldots + b_{2x}.The value of the metric you came up with is the maximum block size over the blocks of the resulting dataset. In other words, the value of the metric is \max\limits_{i=1}^{cnt} w(i).You don't want to overload your machine too much, so you have to remove at most k images in a way that minimizes the value of the metric described above.InputThe first line of the input contains three integers n, k and x (1 \le n \le 10^5; 1 \le k, x \le n) — the number of images in the dataset, the maximum number of images you can remove and the length of each block (except maybe for the last one), respectively.The second line of the input contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^5), where a_i is the size of the i-th image.OutputPrint one integer: the minimum possible value of the metric described in the problem statement after removing no more than k images from the dataset.ExamplesInput 5 5 4 1 1 5 4 5 Output 0 Input 5 2 4 6 1 5 5 6 Output 11 Input 6 1 4 3 3 1 3 1 2 Output 8 Input 6 1 3 2 2 1 2 2 1 Output 5 NoteIn the first example, you can remove the whole array so the answer is 0.In the second example, you can remove the first and the last elements of a and obtain b = [1, 5, 5]. The size of the first (and the only) block is 11. So the answer is 11.In the third example, you can remove the second element of a and obtain b = [3, 1, 3, 1, 2]. The size of the first block is 8 and the size of the second block is 2. So the answer is 8.In the fourth example, you can keep the array a unchanged and obtain b = [2, 2, 1, 2, 2, 1]. The size of the first block is 5 as well as the size of the second block. So the answer is 5.
5 5 4 1 1 5 4 5
0
5 seconds
256 megabytes
['*special problem', 'binary search', 'greedy', '*2100']
E. Chess Matchtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe final of Berland Chess Team Championship is going to be held soon. Two teams consisting of n chess players each will compete for first place in the tournament. The skill of the i-th player in the first team is a_i, and the skill of the i-th player in the second team is b_i. The match will be held as follows: each player of the first team will play a game against one player from the second team in such a way that every player has exactly one opponent. Formally, if the player i from the first team opposes the player p_i from the second team, then [p_1, p_2, \dots, p_n] is a permutation (a sequence where each integer from 1 to n appears exactly once).Whenever two players of almost equal skill play a game, it will likely result in a tie. Chess fans don't like ties, so the organizers of the match should distribute the players in such a way that ties are unlikely.Let the unfairness of the match be the following value: \min\limits_{i = 1}^{n} |a_i - b_{p_i}|. Your task is to assign each player from the first team an opponent from the second team so that the unfairness is maximum possible (the greater it is, the smaller the probability of ties is, that's why you should maximize it).InputThe first line contains one integer t (1 \le t \le 3000) — the number of test cases.Each test case consists of three lines. The first line contains one integer n (1 \le n \le 3000) — the number of players in each team.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_1 \le a_2 \le \dots \le a_n \le 10^6) — the skills of players of the first team.The third line contains n integers b_1, b_2, \dots, b_n (1 \le b_1 \le b_2 \le \dots \le b_n \le 10^6) — the skills of players of the second team.It is guaranteed that the sum of n over all test cases does not exceed 3000.OutputFor each test case, output the answer as follows:Print n integers p_1, p_2, \dots, p_n on a separate line. All integers from 1 to n should occur among them exactly once. The value of \min\limits_{i = 1}^{n} |a_i - b_{p_i}| should be maximum possible. If there are multiple answers, print any of them.ExampleInput 4 4 1 2 3 4 1 2 3 4 2 1 100 100 101 2 1 100 50 51 5 1 1 1 1 1 3 3 3 3 3 Output 3 4 1 2 1 2 2 1 5 4 2 3 1
4 4 1 2 3 4 1 2 3 4 2 1 100 100 101 2 1 100 50 51 5 1 1 1 1 1 3 3 3 3 3
3 4 1 2 1 2 2 1 5 4 2 3 1
2 seconds
512 megabytes
['*special problem', '*2000']
D. Used Markerstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour University has a large auditorium and today you are on duty there. There will be n lectures today — all from different lecturers, and your current task is to choose in which order ord they will happen.Each lecturer will use one marker to write something on a board during their lecture. Unfortunately, markers become worse the more you use them and lecturers may decline using markers which became too bad in their opinion.Formally, the i-th lecturer has their acceptance value a_i which means they will not use the marker that was used at least in a_i lectures already and will ask for a replacement. More specifically: before the first lecture you place a new marker in the auditorium; before the ord_j-th lecturer (in the order you've chosen) starts, they check the quality of the marker and if it was used in at least a_{ord_j} lectures before, they will ask you for a new marker; if you were asked for a new marker, then you throw away the old one, place a new one in the auditorium, and the lecturer gives a lecture. You know: the better the marker — the easier for an audience to understand what a lecturer has written, so you want to maximize the number of used markers. Unfortunately, the higher-ups watch closely how many markers were spent, so you can't just replace markers before each lecture. So, you have to replace markers only when you are asked by a lecturer. The marker is considered used if at least one lecturer used it for their lecture.You can choose the order ord in which lecturers will give lectures. Find such order that leads to the maximum possible number of the used markers.InputThe first line contains one integer t (1 \le t \le 100) — the number of independent tests.The first line of each test case contains one integer n (1 \le n \le 500) — the number of lectures and lecturers.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — acceptance values of each lecturer.OutputFor each test case, print n integers — the order ord of lecturers which maximizes the number of used markers. The lecturers are numbered from 1 to n in the order of the input. If there are multiple answers, print any of them.ExampleInput 4 4 1 2 1 2 2 2 1 3 1 1 1 4 2 3 1 3 Output 4 1 3 2 1 2 3 1 2 4 3 2 1 NoteIn the first test case, one of the optimal orders is the following: the 4-th lecturer comes first. The marker is new, so they don't ask for a replacement; the 1-st lecturer comes next. The marker is used once and since a_1 = 1 the lecturer asks for a replacement; the 3-rd lecturer comes next. The second marker is used once and since a_3 = 1 the lecturer asks for a replacement; the 2-nd lecturer comes last. The third marker is used once but a_2 = 2 so the lecturer uses this marker. In total, 3 markers are used.In the second test case, 2 markers are used.In the third test case, 3 markers are used.In the fourth test case, 3 markers are used.
4 4 1 2 1 2 2 2 1 3 1 1 1 4 2 3 1 3
4 1 3 2 1 2 3 1 2 4 3 2 1
3 seconds
256 megabytes
['*special problem', 'greedy', '*1500']
C. Black Fridaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a local shop in your area getting prepared for the great holiday of Black Friday. There are n items with prices p_1, p_2, \dots, p_n on the display. They are ordered by price, so p_1 \le p_2 \le \dots \le p_n.The shop has a prechosen discount value k. The Black Friday discount is applied in the following way: for a single purchase of x items, you get the cheapest \lfloor \frac x k \rfloor items of them for free (\lfloor \frac x k \rfloor is x divided by k rounded down to the nearest integer). You can include each item in your purchase no more than once.For example, if there are items with prices [1, 1, 2, 2, 2, 3, 4, 5, 6] in the shop, and you buy items with prices [1, 2, 2, 4, 5], and k = 2, then you get the cheapest \lfloor \frac 5 2 \rfloor = 2 for free. They are items with prices 1 and 2.So you, being the naive customer, don't care about how much money you spend. However, you want the total price of the items you get for free to be as large as possible.What is the maximum total price of the items you can get for free on a single purchase?InputThe first line contains a single integer t (1 \le t \le 500) — the number of testcases.Then the description of t testcases follows.The first line of each testcase contains two integers n and k (1 \le n \le 200; 1 \le k \le n) — the number of items in the shop and the discount value, respectively.The second line of each testcase contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le 10^6) — the prices of the items on the display of the shop. The items are ordered by their price, so p_1 \le p_2 \le \dots \le p_n.OutputPrint a single integer for each testcase: the maximum total price of the items you can get for free on a single purchase.ExampleInput 5 5 2 1 3 4 6 7 6 3 1 2 3 4 5 6 6 3 3 3 4 4 5 5 1 1 7 4 4 1 3 3 7 Output 7 4 6 7 1
5 5 2 1 3 4 6 7 6 3 1 2 3 4 5 6 6 3 3 3 4 4 5 5 1 1 7 4 4 1 3 3 7
7 4 6 7 1
2 seconds
256 megabytes
['*special problem', 'implementation', '*1600']
B. Polycarp and the Language of Godstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has just finished writing down the lecture on elvish languages. The language this week was "VwV" (pronounced as "uwu"). The writing system of this language consists of only two lowercase Latin letters: 'v' and 'w'.Unfortunately, Polycarp has written all the lecture in cursive and without any spaces, so the notes look like a neverending sequence of squiggles. To be exact, Polycarp can't tell 'w' apart from 'vv' in his notes as both of them consist of the same two squiggles.Luckily, his brother Monocarp has better writing habits, so Polycarp managed to take his notes and now wants to make his own notes more readable. To do that he can follow the notes of Monocarp and underline some letters in his own notes in such a way that there is no more ambiguity. If he underlines a 'v', then it can't be mistaken for a part of some 'w', and if the underlines a 'w', then it can't be mistaken for two adjacent letters 'v'.What is the minimum number of letters Polycarp should underline to make his notes unambiguous?InputThe first line contains a single integer t (1 \le t \le 100) — the number of testcases.Each of the next t lines contains a non-empty string in VwV language, which consists only of lowercase Latin letters 'v' and 'w'. The length of the string does not exceed 100.OutputFor each testcase print a single integer: the minimum number of letters Polycarp should underline so that there is no ambiguity in his notes.ExampleInput 5 vv v w vwv vwvvwv Output 1 0 1 1 3 NoteIn the first testcase it's enough to underline any of the two letters 'v'.In the second testcase the letter 'v' is not ambiguous by itself already, so you don't have to underline anything.In the third testcase you have to underline 'w', so that you don't mix it up with two letters 'v'.In the fourth testcase you can underline 'w' to avoid all the ambiguity.In the fifth testcase you can underline both letters 'w' and any of the two letters 'v' between them.
5 vv v w vwv vwvvwv
1 0 1 1 3
2 seconds
256 megabytes
['*special problem', 'implementation', 'two pointers', '*1400']
A. Selling Hamburgerstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n customers in the cafeteria. Each of them wants to buy a hamburger. The i-th customer has a_i coins, and they will buy a hamburger if it costs at most a_i coins.Suppose the cost of the hamburger is m. Then the number of coins the cafeteria earns is m multiplied by the number of people who buy a hamburger if it costs m. Your task is to calculate the maximum number of coins the cafeteria can earn.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.Each test case consists of two lines. The first line contains one integer n (1 \le n \le 100) — the number of customers.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^{12}), where a_i is the number of coins the i-th customer has.OutputFor each test case, print one integer — the maximum number of coins the cafeteria can earn.ExampleInput 6 3 1 1 1 3 4 1 1 3 2 4 2 8 1 2 3 4 5 6 7 8 1 1000000000000 3 1000000000000 999999999999 1 Output 3 4 6 20 1000000000000 1999999999998 NoteExplanations for the test cases of the example: the best price for the hamburger is m = 1, so 3 hamburgers are bought, and the cafeteria earns 3 coins; the best price for the hamburger is m = 4, so 1 hamburger is bought, and the cafeteria earns 4 coins; the best price for the hamburger is m = 2, so 3 hamburgers are bought, and the cafeteria earns 6 coins; the best price for the hamburger is m = 4, so 5 hamburgers are bought, and the cafeteria earns 20 coins; the best price for the hamburger is m = 10^{12}, so 1 hamburger is bought, and the cafeteria earns 10^{12} coins; the best price for the hamburger is m = 10^{12} - 1, so 2 hamburgers are bought, and the cafeteria earns 2 \cdot 10^{12} - 2 coins.
6 3 1 1 1 3 4 1 1 3 2 4 2 8 1 2 3 4 5 6 7 8 1 1000000000000 3 1000000000000 999999999999 1
3 4 6 20 1000000000000 1999999999998
2 seconds
512 megabytes
['*special problem', '*800']
G. Yet Another DAG Problemtime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a directed acyclic graph (a directed graph that does not contain cycles) of n vertices and m arcs. The i-th arc leads from the vertex x_i to the vertex y_i and has the weight w_i.Your task is to select an integer a_v for each vertex v, and then write a number b_i on each arcs i such that b_i = a_{x_i} - a_{y_i}. You must select the numbers so that: all b_i are positive; the value of the expression \sum \limits_{i = 1}^{m} w_i b_i is the lowest possible. It can be shown that for any directed acyclic graph with non-negative w_i, such a way to choose numbers exists.InputThe first line contains two integers n and m (2 \le n \le 18; 0 \le m \le \dfrac{n(n - 1)}{2}).Then m lines follow, the i-th of them contains three integers x_i, y_i and w_i (1 \le x_i, y_i \le n, 1 \le w_i \le 10^5, x_i \ne y_i) — the description of the i-th arc.It is guaranteed that the lines describe m arcs of a directed acyclic graph without multiple arcs between the same pair of vertices.OutputPrint n integers a_1, a_2, ..., a_n (0 \le a_v \le 10^9), which must be written on the vertices so that all b_i are positive, and the value of the expression \sum \limits_{i = 1}^{m} w_i b_i is the lowest possible. If there are several answers, print any of them. It can be shown that the answer always exists, and at least one of the optimal answers satisfies the constraints 0 \le a_v \le 10^9.ExamplesInput 3 2 2 1 4 1 3 2 Output 1 2 0 Input 5 4 1 2 1 2 3 1 1 3 6 4 5 8 Output 43 42 41 1337 1336 Input 5 5 1 2 1 2 3 1 3 4 1 1 5 1 5 4 10 Output 4 3 2 1 2
3 2 2 1 4 1 3 2
1 2 0
2 seconds
1024 megabytes
['bitmasks', 'dfs and similar', 'dp', 'flows', 'graphs', 'math', '*2600']
F. Realistic Gameplaytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently you've discovered a new shooter. They say it has realistic game mechanics.Your character has a gun with magazine size equal to k and should exterminate n waves of monsters. The i-th wave consists of a_i monsters and happens from the l_i-th moment of time up to the r_i-th moments of time. All a_i monsters spawn at moment l_i and you have to exterminate all of them before the moment r_i ends (you can kill monsters right at moment r_i). For every two consecutive waves, the second wave starts not earlier than the first wave ends (though the second wave can start at the same moment when the first wave ends) — formally, the condition r_i \le l_{i + 1} holds. Take a look at the notes for the examples to understand the process better.You are confident in yours and your character's skills so you can assume that aiming and shooting are instant and you need exactly one bullet to kill one monster. But reloading takes exactly 1 unit of time.One of the realistic mechanics is a mechanic of reloading: when you reload you throw away the old magazine with all remaining bullets in it. That's why constant reloads may cost you excessive amounts of spent bullets.You've taken a liking to this mechanic so now you are wondering: what is the minimum possible number of bullets you need to spend (both used and thrown) to exterminate all waves.Note that you don't throw the remaining bullets away after eradicating all monsters, and you start with a full magazine.InputThe first line contains two integers n and k (1 \le n \le 2000; 1 \le k \le 10^9) — the number of waves and magazine size.The next n lines contain descriptions of waves. The i-th line contains three integers l_i, r_i and a_i (1 \le l_i \le r_i \le 10^9; 1 \le a_i \le 10^9) — the period of time when the i-th wave happens and the number of monsters in it.It's guaranteed that waves don't overlap (but may touch) and are given in the order they occur, i. e. r_i \le l_{i + 1}.OutputIf there is no way to clear all waves, print -1. Otherwise, print the minimum possible number of bullets you need to spend (both used and thrown) to clear all waves.ExamplesInput 2 3 2 3 6 3 4 3 Output 9 Input 2 5 3 7 11 10 12 15 Output 30 Input 5 42 42 42 42 42 43 42 43 44 42 44 45 42 45 45 1 Output -1 Input 1 10 100 111 1 Output 1 NoteIn the first example: At the moment 2, the first wave occurs and 6 monsters spawn. You kill 3 monsters and start reloading. At the moment 3, the second wave occurs and 3 more monsters spawn. You kill remaining 3 monsters from the first wave and start reloading. At the moment 4, you kill remaining 3 monsters from the second wave. In total, you'll spend 9 bullets.In the second example: At moment 3, the first wave occurs and 11 monsters spawn. You kill 5 monsters and start reloading. At moment 4, you kill 5 more monsters and start reloading. At moment 5, you kill the last monster and start reloading throwing away old magazine with 4 bullets. At moment 10, the second wave occurs and 15 monsters spawn. You kill 5 monsters and start reloading. At moment 11, you kill 5 more monsters and start reloading. At moment 12, you kill last 5 monsters. In total, you'll spend 30 bullets.
2 3 2 3 6 3 4 3
9
1 second
256 megabytes
['dp', 'greedy', '*2600']
E. String Reversaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the string "aeddba". To accomplish your goal, you can swap the neighboring elements of the string. Your task is to calculate the minimum number of swaps you have to perform to reverse the given string.InputThe first line contains one integer n (2 \le n \le 200\,000) — the length of s.The second line contains s — a string consisting of n lowercase Latin letters.OutputPrint one integer — the minimum number of swaps of neighboring elements you have to perform to reverse the string.ExamplesInput 5 aaaza Output 2 Input 6 cbaabc Output 0 Input 9 icpcsguru Output 30 NoteIn the first example, you have to swap the third and the fourth elements, so the string becomes "aazaa". Then you have to swap the second and the third elements, so the string becomes "azaaa". So, it is possible to reverse the string in two swaps.Since the string in the second example is a palindrome, you don't have to do anything to reverse it.
5 aaaza
2
2 seconds
256 megabytes
['data structures', 'greedy', 'strings', '*1900']
D. String Deletiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a string s consisting of n characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer i from 1 to the length of the string s, then delete the character s_i (the string length gets reduced by 1, the indices of characters to the right of the deleted one also get reduced by 1); if the string s is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string s = 111010, the first operation can be one of the following: select i = 1: we'll get 111010 \rightarrow 11010 \rightarrow 010; select i = 2: we'll get 111010 \rightarrow 11010 \rightarrow 010; select i = 3: we'll get 111010 \rightarrow 11010 \rightarrow 010; select i = 4: we'll get 111010 \rightarrow 11110 \rightarrow 0; select i = 5: we'll get 111010 \rightarrow 11100 \rightarrow 00; select i = 6: we'll get 111010 \rightarrow 11101 \rightarrow 01. You finish performing operations when the string s becomes empty. What is the maximum number of operations you can perform?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the string s.The second line contains string s of n characters. Each character is either 0 or 1.It's guaranteed that the total sum of n over test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the maximum number of operations you can perform.ExampleInput 5 6 111010 1 0 1 1 2 11 6 101010 Output 3 1 1 1 3 NoteIn the first test case, you can, for example, select i = 2 and get string 010 after the first operation. After that, you can select i = 3 and get string 1. Finally, you can only select i = 1 and get empty string.
5 6 111010 1 0 1 1 2 11 6 101010
3 1 1 1 3
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'two pointers', '*1700']
C. Numbers on Whiteboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNumbers 1, 2, 3, \dots n (each integer from 1 to n once) are written on a board. In one operation you can erase any two numbers a and b from the board and write one integer \frac{a + b}{2} rounded up instead.You should perform the given operation n - 1 times and make the resulting number that will be left on the board as small as possible. For example, if n = 4, the following course of action is optimal: choose a = 4 and b = 2, so the new number is 3, and the whiteboard contains [1, 3, 3]; choose a = 3 and b = 3, so the new number is 3, and the whiteboard contains [1, 3]; choose a = 1 and b = 3, so the new number is 2, and the whiteboard contains [2]. It's easy to see that after n - 1 operations, there will be left only one number. Your goal is to minimize it.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.The only line of each test case contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of integers written on the board initially.It's guaranteed that the total sum of n over test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, in the first line, print the minimum possible number left on the board after n - 1 operations. Each of the next n - 1 lines should contain two integers — numbers a and b chosen and erased in each operation.ExampleInput 1 4 Output 2 2 4 3 3 3 1
1 4
2 2 4 3 3 3 1
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', 'implementation', 'math', '*1000']
B. Barrelstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.Some examples: if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0. InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains two integers n and k (1 \le k < n \le 2 \cdot 10^5) — the number of barrels and the number of pourings you can make.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^{9}), where a_i is the initial amount of water the i-th barrel has.It's guaranteed that the total sum of n over test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.ExampleInput 2 4 1 5 5 5 5 3 2 0 0 0 Output 10 0
2 4 1 5 5 5 5 3 2 0 0 0
10 0
2 seconds
256 megabytes
['greedy', 'implementation', 'sortings', '*800']
A. Number of Apartmentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.Monocarp went around the building and counted n windows. Now he is wondering, how many apartments of each type the building may have.Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has n windows. If there are multiple answers, you can print any of them.Here are some examples: if Monocarp has counted 30 windows, there could have been 2 three-room apartments, 2 five-room apartments and 2 seven-room apartments, since 2 \cdot 3 + 2 \cdot 5 + 2 \cdot 7 = 30; if Monocarp has counted 67 windows, there could have been 7 three-room apartments, 5 five-room apartments and 3 seven-room apartments, since 7 \cdot 3 + 5 \cdot 5 + 3 \cdot 7 = 67; if Monocarp has counted 4 windows, he should have mistaken since no building with the aforementioned layout can have 4 windows. InputTh first line contains one integer t (1 \le t \le 1000) — the number of test cases.The only line of each test case contains one integer n (1 \le n \le 1000) — the number of windows in the building.OutputFor each test case, if a building with the new layout and the given number of windows just can't exist, print -1.Otherwise, print three non-negative integers — the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.ExampleInput 4 30 67 4 14 Output 2 2 2 7 5 3 -1 0 0 2
4 30 67 4 14
2 2 2 7 5 3 -1 0 0 2
1 second
256 megabytes
['brute force', 'constructive algorithms', 'math', '*900']
H. Rotary Laser Locktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.To prevent the mischievous rabbits from freely roaming around the zoo, Zookeeper has set up a special lock for the rabbit enclosure. This lock is called the Rotary Laser Lock. The lock consists of n concentric rings numbered from 0 to n-1. The innermost ring is ring 0 and the outermost ring is ring n-1. All rings are split equally into nm sections each. Each of those rings contains a single metal arc that covers exactly m contiguous sections. At the center of the ring is a core and surrounding the entire lock are nm receivers aligned to the nm sections. The core has nm lasers that shine outward from the center, one for each section. The lasers can be blocked by any of the arcs. A display on the outside of the lock shows how many lasers hit the outer receivers. In the example above, there are n=3 rings, each covering m=4 sections. The arcs are colored in green (ring 0), purple (ring 1), and blue (ring 2) while the lasers beams are shown in red. There are nm=12 sections and 3 of the lasers are not blocked by any arc, thus the display will show 3 in this case. Wabbit is trying to open the lock to free the rabbits, but the lock is completely opaque, and he cannot see where any of the arcs are. Given the relative positions of the arcs, Wabbit can open the lock on his own. To be precise, Wabbit needs n-1 integers p_1,p_2,\ldots,p_{n-1} satisfying 0 \leq p_i < nm such that for each i (1 \leq i < n), Wabbit can rotate ring 0 clockwise exactly p_i times such that the sections that ring 0 covers perfectly aligns with the sections that ring i covers. In the example above, the relative positions are p_1 = 1 and p_2 = 7. To operate the lock, he can pick any of the n rings and rotate them by 1 section either clockwise or anti-clockwise. You will see the number on the display after every rotation.Because his paws are small, Wabbit has asked you to help him to find the relative positions of the arcs after all of your rotations are completed. You may perform up to 15000 rotations before Wabbit gets impatient.InputThe first line consists of 2 integers n and m (2 \leq n \leq 100, 2 \leq m \leq 20), indicating the number of rings and the number of sections each ring covers.InteractionTo perform a rotation, print on a single line "? x d" where x (0 \leq x < n) is the ring that you wish to rotate and d (d \in \{-1,1\}) is the direction that you would like to rotate in. d=1 indicates a clockwise rotation by 1 section while d=-1 indicates an anticlockwise rotation by 1 section. For each query, you will receive a single integer a: the number of lasers that are not blocked by any of the arcs after the rotation has been performed.Once you have figured out the relative positions of the arcs, print ! followed by n-1 integers p_1, p_2, \ldots, p_{n-1}. Do note that the positions of the rings are predetermined for each test case and won't change during the interaction process. After printing a query do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded verdict.To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hacks:To hack, use the following format of test: The first line should contain two integers n and m. The next line of should contain n-1 integers p_1,p_2,\ldots,p_{n-1}: relative positions of rings 1,2,\ldots,n-1.ExampleInput 3 4 4 4 3 Output ? 0 1 ? 2 -1 ? 1 1 ! 1 5NoteFor the first test, the configuration is the same as shown on the picture from the statement. After the first rotation (which is rotating ring 0 clockwise by 1 section), we obtain the following configuration: After the second rotation (which is rotating ring 2 counter-clockwise by 1 section), we obtain the following configuration: After the third rotation (which is rotating ring 1 clockwise by 1 section), we obtain the following configuration: If we rotate ring 0 clockwise once, we can see that the sections ring 0 covers will be the same as the sections that ring 1 covers, hence p_1=1.If we rotate ring 0 clockwise five times, the sections ring 0 covers will be the same as the sections that ring 2 covers, hence p_2=5.Note that if we will make a different set of rotations, we can end up with different values of p_1 and p_2 at the end.
3 4 4 4 3
? 0 1 ? 2 -1 ? 1 1 ! 1 5
1 second
256 megabytes
['binary search', 'interactive', '*3500']
G2. Lucky Numbers (Hard Version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference is in the constraint on q. You can make hacks only if all versions of the problem are solved.Zookeeper has been teaching his q sheep how to write and how to add. The i-th sheep has to write exactly k non-negative integers with the sum n_i.Strangely, sheep have superstitions about digits and believe that the digits 3, 6, and 9 are lucky. To them, the fortune of a number depends on the decimal representation of the number; the fortune of a number is equal to the sum of fortunes of its digits, and the fortune of a digit depends on its value and position and can be described by the following table. For example, the number 319 has fortune F_{2} + 3F_{0}. Each sheep wants to maximize the sum of fortune among all its k written integers. Can you help them?InputThe first line contains a single integer k (1 \leq k \leq 999999): the number of numbers each sheep has to write. The next line contains six integers F_0, F_1, F_2, F_3, F_4, F_5 (1 \leq F_i \leq 10^9): the fortune assigned to each digit. The next line contains a single integer q (1 \leq q \leq 100\,000): the number of sheep.Each of the next q lines contains a single integer n_i (1 \leq n_i \leq 999999): the sum of numbers that i-th sheep has to write.OutputPrint q lines, where the i-th line contains the maximum sum of fortune of all numbers of the i-th sheep.ExampleInput 3 1 2 3 4 5 6 2 57 63 Output 11 8 NoteIn the first test case, 57 = 9 + 9 + 39. The three 9's contribute 1 \cdot 3 and 3 at the tens position contributes 2 \cdot 1. Hence the sum of fortune is 11.In the second test case, 63 = 35 + 19 + 9. The sum of fortune is 8.
3 1 2 3 4 5 6 2 57 63
11 8
3 seconds
256 megabytes
['dp', 'greedy', '*3000']
G1. Lucky Numbers (Easy Version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference is that in this version q=1. You can make hacks only if all versions of the problem are solved.Zookeeper has been teaching his q sheep how to write and how to add. The i-th sheep has to write exactly k non-negative integers with the sum n_i.Strangely, sheep have superstitions about digits and believe that the digits 3, 6, and 9 are lucky. To them, the fortune of a number depends on the decimal representation of the number; the fortune of a number is equal to the sum of fortunes of its digits, and the fortune of a digit depends on its value and position and can be described by the following table. For example, the number 319 has fortune F_{2} + 3F_{0}. Each sheep wants to maximize the sum of fortune among all its k written integers. Can you help them?InputThe first line contains a single integer k (1 \leq k \leq 999999): the number of numbers each sheep has to write. The next line contains six integers F_0, F_1, F_2, F_3, F_4, F_5 (1 \leq F_i \leq 10^9): the fortune assigned to each digit. The next line contains a single integer q (q = 1): the number of sheep.Each of the next q lines contains a single integer n_i (1 \leq n_i \leq 999999): the sum of numbers that i-th sheep has to write. In this version, there is only one line.OutputPrint q lines, where the i-th line contains the maximum sum of fortune of all numbers of the i-th sheep. In this version, you should print only one line.ExamplesInput 3 1 2 3 4 5 6 1 57 Output 11Input 3 1 2 3 4 5 6 1 63 Output 8NoteIn the first test case, 57 = 9 + 9 + 39. The three 9's contribute 1 \cdot 3 and 3 at the tens position contributes 2 \cdot 1. Hence the sum of fortune is 11.In the second test case, 63 = 35 + 19 + 9. The sum of fortune is 8.
3 1 2 3 4 5 6 1 57
11
3 seconds
256 megabytes
['dp', 'greedy', '*2900']
F. Fruit Sequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string s_1s_2\ldots s_n of length n. 1 represents an apple and 0 represents an orange.Since wabbit is allergic to eating oranges, Zookeeper would like to find the longest contiguous sequence of apples. Let f(l,r) be the longest contiguous sequence of apples in the substring s_{l}s_{l+1}\ldots s_{r}. Help Zookeeper find \sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r), or the sum of f across all substrings.InputThe first line contains a single integer n (1 \leq n \leq 5 \cdot 10^5). The next line contains a binary string s of length n (s_i \in \{0,1\}) OutputPrint a single integer: \sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r). ExamplesInput 4 0110 Output 12 Input 7 1101001 Output 30 Input 12 011100011100 Output 156 NoteIn the first test, there are ten substrings. The list of them (we let [l,r] be the substring s_l s_{l+1} \ldots s_r): [1,1]: 0 [1,2]: 01 [1,3]: 011 [1,4]: 0110 [2,2]: 1 [2,3]: 11 [2,4]: 110 [3,3]: 1 [3,4]: 10 [4,4]: 0 The lengths of the longest contiguous sequence of ones in each of these ten substrings are 0,1,2,2,1,2,2,1,1,0 respectively. Hence, the answer is 0+1+2+2+1+2+2+1+1+0 = 12.
4 0110
12
2 seconds
256 megabytes
['binary search', 'data structures', 'divide and conquer', 'dp', 'two pointers', '*2400']
E. Carrots for Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, \ldots, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers.Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2.Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots.InputThe first line contains two integers n and k (1 \leq n \leq k \leq 10^5): the initial number of carrots and the number of rabbits.The next line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^6): lengths of carrots.It is guaranteed that the sum of a_i is at least k.OutputOutput one integer: the minimum sum of time taken for rabbits to eat carrots.ExamplesInput 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 NoteFor the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91.
3 6 5 3 1
15
1 second
256 megabytes
['binary search', 'data structures', 'greedy', 'math', 'sortings', '*2200']
D. Bouncing Boomerangstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo improve the boomerang throwing skills of the animals, Zookeeper has set up an n \times n grid with some targets, where each row and each column has at most 2 targets each. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to n from left to right. For each column, Zookeeper will throw a boomerang from the bottom of the column (below the grid) upwards. When the boomerang hits any target, it will bounce off, make a 90 degree turn to the right and fly off in a straight line in its new direction. The boomerang can hit multiple targets and does not stop until it leaves the grid. In the above example, n=6 and the black crosses are the targets. The boomerang in column 1 (blue arrows) bounces 2 times while the boomerang in column 3 (red arrows) bounces 3 times. The boomerang in column i hits exactly a_i targets before flying out of the grid. It is known that a_i \leq 3.However, Zookeeper has lost the original positions of the targets. Thus, he asks you to construct a valid configuration of targets that matches the number of hits for each column, or tell him that no such configuration exists. If multiple valid configurations exist, you may print any of them.InputThe first line contains a single integer n (1 \leq n \leq 10^5). The next line contains n integers a_1,a_2,\ldots,a_n (0 \leq a_i \leq 3).OutputIf no configuration of targets exist, print -1. Otherwise, on the first line print a single integer t (0 \leq t \leq 2n): the number of targets in your configuration. Then print t lines with two spaced integers each per line. Each line should contain two integers r and c (1 \leq r,c \leq n), where r is the target's row and c is the target's column. All targets should be different. Every row and every column in your configuration should have at most two targets each. ExamplesInput 6 2 0 3 0 1 1 Output 5 2 1 2 5 3 3 3 6 5 6 Input 1 0 Output 0 Input 6 3 2 2 2 1 1 Output -1 NoteFor the first test, the answer configuration is the same as in the picture from the statement. For the second test, the boomerang is not supposed to hit anything, so we can place 0 targets. For the third test, the following configuration of targets matches the number of hits, but is not allowed as row 3 has 4 targets. It can be shown for this test case that no valid configuration of targets will result in the given number of target hits.
6 2 0 3 0 1 1
5 2 1 2 5 3 3 3 6 5 6
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*1900']
C. ABBBtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputZookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.For example, Zookeeper can use two such operations: AABABBA \to AABBA \to AAA.Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string?InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 20000)  — the number of test cases. The description of the test cases follows.Each of the next t lines contains a single test case each, consisting of a non-empty string s: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of s are either 'A' or 'B'.It is guaranteed that the sum of |s| (length of s) among all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single integer: the length of the shortest string that Zookeeper can make.ExampleInput 3 AAA BABA AABBBABBBB Output 3 2 0 NoteFor the first test case, you can't make any moves, so the answer is 3.For the second test case, one optimal sequence of moves is BABA \to BA. So, the answer is 2.For the third test case, one optimal sequence of moves is AABBBABBBB \to AABBBABB \to AABBBB \to ABBB \to AB \to (empty string). So, the answer is 0.
3 AAA BABA AABBBABBBB
3 2 0
1 second
256 megabytes
['brute force', 'data structures', 'greedy', 'strings', '*1100']
B. Belted Roomstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the snake exhibition, there are n rooms (numbered 0 to n - 1) arranged in a circle, with a snake in each room. The rooms are connected by n conveyor belts, and the i-th conveyor belt connects the rooms i and (i+1) \bmod n. In the other words, rooms 0 and 1, 1 and 2, \ldots, n-2 and n-1, n-1 and 0 are connected with conveyor belts.The i-th conveyor belt is in one of three states: If it is clockwise, snakes can only go from room i to (i+1) \bmod n. If it is anticlockwise, snakes can only go from room (i+1) \bmod n to i. If it is off, snakes can travel in either direction. Above is an example with 4 rooms, where belts 0 and 3 are off, 1 is clockwise, and 2 is anticlockwise.Each snake wants to leave its room and come back to it later. A room is returnable if the snake there can leave the room, and later come back to it using the conveyor belts. How many such returnable rooms are there?InputEach test contains multiple test cases. The 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 description contains a single integer n (2 \le n \le 300\,000): the number of rooms. The next line of each test case description contains a string s of length n, consisting of only '<', '>' and '-'. If s_{i} = '>', the i-th conveyor belt goes clockwise. If s_{i} = '<', the i-th conveyor belt goes anticlockwise. If s_{i} = '-', the i-th conveyor belt is off. It is guaranteed that the sum of n among all test cases does not exceed 300\,000.OutputFor each test case, output the number of returnable rooms.ExampleInput 4 4 -><- 5 >>>>> 3 <-- 2 <> Output 3 5 3 0 NoteIn the first test case, all rooms are returnable except room 2. The snake in the room 2 is trapped and cannot exit. This test case corresponds to the picture from the problem statement. In the second test case, all rooms are returnable by traveling on the series of clockwise belts.
4 4 -><- 5 >>>>> 3 <-- 2 <>
3 5 3 0
1 second
256 megabytes
['graphs', 'implementation', '*1200']
A. Box is Pulltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2).He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by 1 unit. For example, if the box is at the point (1,2) and Wabbit is standing at the point (2,2), he can pull the box right by 1 unit, with the box ending up at the point (2,2) and Wabbit ending at the point (3,2).Also, Wabbit can move 1 unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly 1 unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.Wabbit can start at any point. It takes 1 second to travel 1 unit right, left, up, or down, regardless of whether he pulls the box while moving.Determine the minimum amount of time he needs to move the box from (x_1,y_1) to (x_2,y_2). Note that the point where Wabbit ends up at does not matter.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 1000): the number of test cases. The description of the test cases follows.Each of the next t lines contains four space-separated integers x_1, y_1, x_2, y_2 (1 \leq x_1, y_1, x_2, y_2 \leq 10^9), describing the next test case.OutputFor each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from (x_1,y_1) to (x_2,y_2).ExampleInput 2 1 2 2 2 1 1 2 2 Output 1 4 NoteIn the first test case, the starting and the ending points of the box are (1,2) and (2,2) respectively. This is the same as the picture in the statement. Wabbit needs only 1 second to move as shown in the picture in the statement.In the second test case, Wabbit can start at the point (2,1). He pulls the box to (2,1) while moving to (3,1). He then moves to (3,2) and then to (2,2) without pulling the box. Then, he pulls the box to (2,2) while moving to (2,3). It takes 4 seconds.
2 1 2 2 2 1 1 2 2
1 4
1 second
256 megabytes
['math', '*800']
H. Prison Breaktime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA prisoner wants to escape from a prison. The prison is represented by the interior of the convex polygon with vertices P_1, P_2, P_3, \ldots, P_{n+1}, P_{n+2}, P_{n+3}. It holds P_1=(0,0), P_{n+1}=(0, h), P_{n+2}=(-10^{18}, h) and P_{n+3}=(-10^{18}, 0). The prison walls P_{n+1}P_{n+2}, P_{n+2}P_{n+3} and P_{n+3}P_1 are very high and the prisoner is not able to climb them. Hence his only chance is to reach a point on one of the walls P_1P_2, P_2P_3,\dots, P_{n}P_{n+1} and escape from there. On the perimeter of the prison, there are two guards. The prisoner moves at speed 1 while the guards move, remaining always on the perimeter of the prison, with speed v.If the prisoner reaches a point of the perimeter where there is a guard, the guard kills the prisoner. If the prisoner reaches a point of the part of the perimeter he is able to climb and there is no guard there, he escapes immediately. Initially the prisoner is at the point (-10^{17}, h/2) and the guards are at P_1. Find the minimum speed v such that the guards can guarantee that the prisoner will not escape (assuming that both the prisoner and the guards move optimally).Notes: At any moment, the guards and the prisoner can see each other. The "climbing part" of the escape takes no time. You may assume that both the prisoner and the guards can change direction and velocity instantly and that they both have perfect reflexes (so they can react instantly to whatever the other one is doing). The two guards can plan ahead how to react to the prisoner movements. InputThe first line of the input contains n (1 \le n \le 50).The following n+1 lines describe P_1, P_2,\dots, P_{n+1}. The i-th of such lines contain two integers x_i, y_i (0\le x_i, y_i\le 1,000) — the coordinates of P_i=(x_i, y_i).It is guaranteed that P_1=(0,0) and x_{n+1}=0. The polygon with vertices P_1,P_2,\dots, P_{n+1}, P_{n+2}, P_{n+3} (where P_{n+2}, P_{n+3} shall be constructed as described in the statement) is guaranteed to be convex and such that there is no line containing three of its vertices.OutputPrint a single real number, the minimum speed v that allows the guards to guarantee that the prisoner will not escape. Your answer will be considered correct if its relative or absolute error does not exceed 10^{-6}.ExamplesInput 2 0 0 223 464 0 749 Output 1 Input 3 0 0 2 2 2 4 0 6 Output 1.0823922 Input 4 0 0 7 3 7 4 5 7 0 8 Output 1.130309669 Input 5 0 0 562 248 460 610 281 702 206 723 0 746 Output 1.148649561 Input 7 0 0 412 36 745 180 747 184 746 268 611 359 213 441 0 450 Output 1.134745994
2 0 0 223 464 0 749
1
4 seconds
256 megabytes
['binary search', 'games', 'geometry', 'ternary search', '*3500']
G. One Billion Shades of Greytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have to paint with shades of grey the tiles of an n\times n wall. The wall has n rows of tiles, each with n tiles.The tiles on the boundary of the wall (i.e., on the first row, last row, first column and last column) are already painted and you shall not change their color. All the other tiles are not painted. Some of the tiles are broken, you shall not paint those tiles. It is guaranteed that the tiles on the boundary are not broken.You shall paint all the non-broken tiles that are not already painted. When you paint a tile you can choose from 10^9 shades of grey, indexed from 1 to 10^9. You can paint multiple tiles with the same shade. Formally, painting the wall is equivalent to assigning a shade (an integer between 1 and 10^9) to each non-broken tile that is not already painted.The contrast between two tiles is the absolute value of the difference between the shades of the two tiles. The total contrast of the wall is the sum of the contrast of all the pairs of adjacent non-broken tiles (two tiles are adjacent if they share a side).Compute the minimum possible total contrast of the wall.InputThe first line contains n (3\le n\le 200) – the number of rows and columns.Then n lines, each containing n integers, follow. The i-th of these lines describe the i-th row of tiles. It contains the n integers a_{ij} (-1\le a_{ij} \le 10^9). The value of a_{ij} described the tile on the i-th row and j-th column: If a_{ij}=0, then the tile is not painted and shall be painted. If a_{ij}=-1, then the tile is broken and shall not be painted. If 1\le a_{ij}\le 10^9, then the tile is already painted with the shade a_{ij}. It is guaranteed that the tiles on the boundary are already painted, the tiles not on the boundary are not already painted, and the tiles on the boundary are not broken.OutputPrint a single integer – the minimum possible total contrast of the wall.ExamplesInput 3 1 7 6 4 0 6 1 1 1 Output 26 Input 3 10 100 1 1 -1 100 10 10 10 Output 396 Input 5 6 6 5 4 4 6 0 0 0 4 7 0 0 0 3 8 0 0 0 2 8 8 1 2 2 Output 34 Input 7 315055237 841510063 581663979 148389224 405375301 243686840 882512379 683199716 -1 -1 0 0 0 346177625 496442279 0 0 0 0 0 815993623 223938231 0 0 -1 0 0 16170511 44132173 0 -1 0 0 0 130735659 212201259 0 0 -1 0 0 166102576 123213235 506794677 467013743 410119347 791447348 80193382 142887538 Output 10129482893 NoteExplanation of the first testcase: The initial configuration of the tiles is (tiles to paint are denoted by ?): 1 7 64 ? 61 1 1 A possible way to paint the tile achieving the minimum possible contrast of 26 is: 1 7 64 5 61 1 1 Explanation of the second testcase: Since all tiles are either painted or broken, there is nothing to do. The total contrast is 396.Explanation of the third testcase: The initial configuration of the tiles is (tiles to paint are denoted by ?): 6 6 5 4 46 ? ? ? 47 ? ? ? 38 ? ? ? 28 8 1 2 2 A possible way to paint the tiles achieving the minimum possible contrast of 34 is: 6 6 5 4 46 6 5 4 47 7 5 3 38 8 2 2 28 8 1 2 2
3 1 7 6 4 0 6 1 1 1
26
3 seconds
256 megabytes
['flows', 'graphs', '*3300']
F. Boring Card Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen they are bored, Federico and Giada often play the following card game with a deck containing 6n cards.Each card contains one number between 1 and 6n and each number appears on exactly one card. Initially the deck is sorted, so the first card contains the number 1, the second card contains the number 2, \dots, and the last one contains the number 6n.Federico and Giada take turns, alternating; Federico starts.In his turn, the player takes 3 contiguous cards from the deck and puts them in his pocket. The order of the cards remaining in the deck is not changed. They play until the deck is empty (after exactly 2n turns). At the end of the game both Federico and Giada have 3n cards in their pockets.You are given the cards in Federico's pocket at the end of the game. Describe a sequence of moves that produces that set of cards in Federico's pocket.InputThe first line of the input contains one integer n (1\le n \le 200).The second line of the input contains 3n numbers x_1, x_2,\ldots, x_{3n} (1 \le x_1 < x_2 <\ldots < x_{3n} \le 6n) – the cards in Federico's pocket at the end of the game. It is guaranteed that for each test there is at least one sequence of moves that produces such set of cards in Federico's pocket.OutputPrint 2n lines, each containing 3 integers.The i-th line should contain, in increasing order, the integers a_i<b_i<c_i written on the three cards taken by the player during the i-th turn (so taken by Federico if i is odd and by Giada if i is even).If there is more than one possible sequence of moves, you can print any.ExamplesInput 2 2 3 4 9 10 11 Output 9 10 11 6 7 8 2 3 4 1 5 12 Input 5 1 2 3 4 5 9 11 12 13 18 19 20 21 22 23 Output 19 20 21 24 25 26 11 12 13 27 28 29 1 2 3 14 15 16 18 22 23 6 7 8 4 5 9 10 17 30 NoteExplanation of the first testcase: Initially the deck has 12 = 2\cdot 6 sorted cards, so the deck is [1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 9\ 10\ 11\ 12]. During turn 1, Federico takes the three cards [9\ 10\ 11]. After his move, the deck is [1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 12]. During turn 2, Giada takes the three cards [6\ 7\ 8]. After her move, the deck is [1\ 2\ 3\ 4\ 5\ 12]. During turn 3, Federico takes the three cards [2\ 3\ 4]. After his move, the deck is [1\ 5\ 12]. During turn 4, Giada takes the three cards [1\ 5\ 12]. After her move, the deck is empty. At the end of the game, the cards in Federico's pocket are [2\ 3\ 4\ 9\ 10\ 11] and the cards in Giada's pocket are [1\ 5\ 6\ 7\ 8\ 12].
2 2 3 4 9 10 11
9 10 11 6 7 8 2 3 4 1 5 12
1 second
256 megabytes
['data structures', 'greedy', 'trees', '*3200']
E. Xumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a blackboard and initially only an odd number x is written on it. Your goal is to write the number 1 on the blackboard.You may write new numbers on the blackboard with the following two operations. You may take two numbers (not necessarily distinct) already on the blackboard and write their sum on the blackboard. The two numbers you have chosen remain on the blackboard. You may take two numbers (not necessarily distinct) already on the blackboard and write their bitwise XOR on the blackboard. The two numbers you have chosen remain on the blackboard. Perform a sequence of operations such that at the end the number 1 is on the blackboard.InputThe single line of the input contains the odd integer x (3 \le x \le 999,999).OutputPrint on the first line the number q of operations you perform. Then q lines should follow, each describing one operation. The "sum" operation is described by the line "a + b", where a, b must be integers already present on the blackboard. The "xor" operation is described by the line "a ^ b", where a, b must be integers already present on the blackboard. The operation symbol (+ or ^) must be separated from a, b by a whitespace.You can perform at most 100,000 operations (that is, q\le 100,000) and all numbers written on the blackboard must be in the range [0, 5\cdot10^{18}]. It can be proven that under such restrictions the required sequence of operations exists. You can output any suitable sequence of operations.ExamplesInput 3 Output 5 3 + 3 3 ^ 6 3 + 5 3 + 6 8 ^ 9 Input 123 Output 10 123 + 123 123 ^ 246 141 + 123 246 + 123 264 ^ 369 121 + 246 367 ^ 369 30 + 30 60 + 60 120 ^ 121
3
5 3 + 3 3 ^ 6 3 + 5 3 + 6 8 ^ 9
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'math', 'matrices', 'number theory', '*2500']
D. Unshuffling a Decktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation. Choose 2 \le k \le n and split the deck in k nonempty contiguous parts D_1, D_2,\dots, D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the following |D_2| cards and so on). Then reverse the order of the parts, transforming the deck into D_k, D_{k-1}, \dots, D_2, D_1 (so, the first |D_k| cards of the new deck are D_k, the following |D_{k-1}| cards are D_{k-1} and so on). The internal order of each packet of cards D_i is unchanged by the operation. You have to obtain a sorted deck (i.e., a deck where the first card is 1, the second is 2 and so on) performing at most n operations. It can be proven that it is always possible to sort the deck performing at most n operations.Examples of operation: The following are three examples of valid operations (on three decks with different sizes). If the deck is [3 6 2 1 4 5 7] (so 3 is the first card and 7 is the last card), we may apply the operation with k=4 and D_1=[3 6], D_2=[2 1 4], D_3=[5], D_4=[7]. Doing so, the deck becomes [7 5 2 1 4 3 6]. If the deck is [3 1 2], we may apply the operation with k=3 and D_1=[3], D_2=[1], D_3=[2]. Doing so, the deck becomes [2 1 3]. If the deck is [5 1 2 4 3 6], we may apply the operation with k=2 and D_1=[5 1], D_2=[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1]. InputThe first line of the input contains one integer n (1\le n\le 52)  — the number of cards in the deck.The second line contains n integers c_1, c_2, \dots, c_n  — the cards in the deck. The first card is c_1, the second is c_2 and so on.It is guaranteed that for all i=1,\dots,n there is exactly one j\in\{1,\dots,n\} such that c_j = i.OutputOn the first line, print the number q of operations you perform (it must hold 0\le q\le n).Then, print q lines, each describing one operation.To describe an operation, print on a single line the number k of parts you are going to split the deck in, followed by the size of the k parts: |D_1|, |D_2|, \dots , |D_k|. It must hold 2\le k\le n, and |D_i|\ge 1 for all i=1,\dots,k, and |D_1|+|D_2|+\cdots + |D_k| = n.It can be proven that it is always possible to sort the deck performing at most n operations. If there are several ways to sort the deck you can output any of them.ExamplesInput 4 3 1 2 4 Output 2 3 1 2 1 2 1 3 Input 6 6 5 4 3 2 1 Output 1 6 1 1 1 1 1 1 Input 1 1 Output 0 NoteExplanation of the first testcase: Initially the deck is [3 1 2 4]. The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3]. The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4]. Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1]. The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6].
4 3 1 2 4
2 3 1 2 1 2 1 3
1 second
256 megabytes
['constructive algorithms', 'implementation', '*2000']
C. The Hard Work of Paparazzitime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are a paparazzi working in Manhattan.Manhattan has r south-to-north streets, denoted by numbers 1, 2,\ldots, r in order from west to east, and r west-to-east streets, denoted by numbers 1,2,\ldots,r in order from south to north. Each of the r south-to-north streets intersects each of the r west-to-east streets; the intersection between the x-th south-to-north street and the y-th west-to-east street is denoted by (x, y). In order to move from the intersection (x,y) to the intersection (x', y') you need |x-x'|+|y-y'| minutes.You know about the presence of n celebrities in the city and you want to take photos of as many of them as possible. More precisely, for each i=1,\dots, n, you know that the i-th celebrity will be at the intersection (x_i, y_i) in exactly t_i minutes from now (and he will stay there for a very short time, so you may take a photo of him only if at the t_i-th minute from now you are at the intersection (x_i, y_i)). You are very good at your job, so you are able to take photos instantaneously. You know that t_i < t_{i+1} for any i=1,2,\ldots, n-1.Currently you are at your office, which is located at the intersection (1, 1). If you plan your working day optimally, what is the maximum number of celebrities you can take a photo of?InputThe first line of the input contains two positive integers r, n (1\le r\le 500, 1\le n\le 100,000) – the number of south-to-north/west-to-east streets and the number of celebrities.Then n lines follow, each describing the appearance of a celebrity. The i-th of these lines contains 3 positive integers t_i, x_i, y_i (1\le t_i\le 1,000,000, 1\le x_i, y_i\le r)  — denoting that the i-th celebrity will appear at the intersection (x_i, y_i) in t_i minutes from now.It is guaranteed that t_i<t_{i+1} for any i=1,2,\ldots, n-1.OutputPrint a single integer, the maximum number of celebrities you can take a photo of.ExamplesInput 10 1 11 6 8 Output 0 Input 6 9 1 2 6 7 5 1 8 5 5 10 3 1 12 4 4 13 6 2 17 6 6 20 1 4 21 5 4 Output 4 Input 10 4 1 2 1 5 10 9 13 8 8 15 9 9 Output 1 Input 500 10 69 477 122 73 186 235 341 101 145 372 77 497 390 117 440 494 471 37 522 300 498 682 149 379 821 486 359 855 157 386 Output 3 NoteExplanation of the first testcase: There is only one celebrity in the city, and he will be at intersection (6,8) exactly 11 minutes after the beginning of the working day. Since you are initially at (1,1) and you need |1-6|+|1-8|=5+7=12 minutes to reach (6,8) you cannot take a photo of the celebrity. Thus you cannot get any photo and the answer is 0.Explanation of the second testcase: One way to take 4 photos (which is the maximum possible) is to take photos of celebrities with indexes 3, 5, 7, 9 (see the image for a visualization of the strategy): To move from the office at (1,1) to the intersection (5,5) you need |1-5|+|1-5|=4+4=8 minutes, so you arrive at minute 8 and you are just in time to take a photo of celebrity 3. Then, just after you have taken a photo of celebrity 3, you move toward the intersection (4,4). You need |5-4|+|5-4|=1+1=2 minutes to go there, so you arrive at minute 8+2=10 and you wait until minute 12, when celebrity 5 appears. Then, just after you have taken a photo of celebrity 5, you go to the intersection (6,6). You need |4-6|+|4-6|=2+2=4 minutes to go there, so you arrive at minute 12+4=16 and you wait until minute 17, when celebrity 7 appears. Then, just after you have taken a photo of celebrity 7, you go to the intersection (5,4). You need |6-5|+|6-4|=1+2=3 minutes to go there, so you arrive at minute 17+3=20 and you wait until minute 21 to take a photo of celebrity 9. Explanation of the third testcase: The only way to take 1 photo (which is the maximum possible) is to take a photo of the celebrity with index 1 (since |2-1|+|1-1|=1, you can be at intersection (2,1) after exactly one minute, hence you are just in time to take a photo of celebrity 1).Explanation of the fourth testcase: One way to take 3 photos (which is the maximum possible) is to take photos of celebrities with indexes 3, 8, 10: To move from the office at (1,1) to the intersection (101,145) you need |1-101|+|1-145|=100+144=244 minutes, so you can manage to be there when the celebrity 3 appears (at minute 341). Then, just after you have taken a photo of celebrity 3, you move toward the intersection (149,379). You need |101-149|+|145-379|=282 minutes to go there, so you arrive at minute 341+282=623 and you wait until minute 682, when celebrity 8 appears. Then, just after you have taken a photo of celebrity 8, you go to the intersection (157,386). You need |149-157|+|379-386|=8+7=15 minutes to go there, so you arrive at minute 682+15=697 and you wait until minute 855 to take a photo of celebrity 10.
10 1 11 6 8
0
2 seconds
256 megabytes
['dp', '*2000']
B. Chess Cheatertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou like playing chess tournaments online.In your last tournament you played n games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get 0 points. When you win you get 1 or 2 points: if you have won also the previous game you get 2 points, otherwise you get 1 point. If you win the very first game of the tournament you get 1 point (since there is not a "previous game").The outcomes of the n games are represented by a string s of length n: the i-th character of s is W if you have won the i-th game, while it is L if you have lost the i-th game.After the tournament, you notice a bug on the website that allows you to change the outcome of at most k of your games (meaning that at most k times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.Compute the maximum score you can get by cheating in the optimal way.InputEach test contains multiple test cases. The first line contains an integer t (1\le t \le 20,000) — the number of test cases. The description of the test cases follows.The first line of each testcase contains two integers n, k (1\le n\le 100,000, 0\le k\le n) – the number of games played and the number of outcomes that you can change.The second line contains a string s of length n containing only the characters W and L. If you have won the i-th game then s_i=\,W, if you have lost the i-th game then s_i=\,L.It is guaranteed that the sum of n over all testcases does not exceed 200,000.OutputFor each testcase, print a single integer – the maximum score you can get by cheating in the optimal way.ExampleInput 8 5 2 WLWLL 6 5 LLLWWL 7 1 LWLWLWL 15 5 WWWLLLWWWLLLWWW 40 7 LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL 1 0 L 1 1 L 6 1 WLLWLW Output 7 11 6 26 46 0 1 6 NoteExplanation of the first testcase. Before changing any outcome, the score is 2. Indeed, you won the first game, so you got 1 point, and you won also the third, so you got another 1 point (and not 2 because you lost the second game).An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is 7=1+2+2+2: 1 point for the first game and 2 points for the second, third and fourth game.Explanation of the second testcase. Before changing any outcome, the score is 3. Indeed, you won the fourth game, so you got 1 point, and you won also the fifth game, so you got 2 more points (since you won also the previous game).An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is 11 = 1+2+2+2+2+2: 1 point for the first game and 2 points for all the other games.
8 5 2 WLWLL 6 5 LLLWWL 7 1 LWLWLWL 15 5 WWWLLLWWWLLLWWW 40 7 LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL 1 0 L 1 1 L 6 1 WLLWLW
7 11 6 26 46 0 1 6
1 second
256 megabytes
['greedy', 'implementation', 'sortings', '*1400']
A. Avoiding Zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n integers a_1,a_2,\dots,a_n.You have to create an array of n integers b_1,b_2,\dots,b_n such that: The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \{a_1,a_2,\dots,a_n\} and \{b_1,b_2,\dots,b_n\} are equal.For example, if a=[1,-1,0,1], then b=[-1,1,1,0] and b=[0,1,-1,1] are rearrangements of a, but b=[1,-1,-1,0] and b=[1,0,2,-3] are not rearrangements of a. For all k=1,2,\dots,n the sum of the first k elements of b is nonzero. Formally, for all k=1,2,\dots,n, it must hold b_1+b_2+\cdots+b_k\not=0\,. If an array b_1,b_2,\dots, b_n with the required properties does not exist, you have to print NO.InputEach test contains multiple test cases. The first line contains an integer t (1\le t \le 1000) — the number of test cases. The description of the test cases follows.The first line of each testcase contains one integer n (1\le n\le 50)  — the length of the array a.The second line of each testcase contains n integers a_1,a_2,\dots, a_n (-50\le a_i\le 50)  — the elements of a.OutputFor each testcase, if there is not an array b_1,b_2,\dots,b_n with the required properties, print a single line with the word NO.Otherwise print a line with the word YES, followed by a line with the n integers b_1,b_2,\dots,b_n. If there is more than one array b_1,b_2,\dots,b_n satisfying the required properties, you can print any of them.ExampleInput 4 4 1 -2 3 -4 3 0 0 0 5 1 -1 1 -1 1 6 40 -31 -9 0 13 -40 Output YES 1 -2 3 -4 NO YES 1 1 -1 1 -1 YES -40 13 40 0 -9 -31 NoteExplanation of the first testcase: An array with the desired properties is b=[1,-2,3,-4]. For this array, it holds: The first element of b is 1. The sum of the first two elements of b is -1. The sum of the first three elements of b is 2. The sum of the first four elements of b is -2. Explanation of the second testcase: Since all values in a are 0, any rearrangement b of a will have all elements equal to 0 and therefore it clearly cannot satisfy the second property described in the statement (for example because b_1=0). Hence in this case the answer is NO.Explanation of the third testcase: An array with the desired properties is b=[1, 1, -1, 1, -1]. For this array, it holds: The first element of b is 1. The sum of the first two elements of b is 2. The sum of the first three elements of b is 1. The sum of the first four elements of b is 2. The sum of the first five elements of b is 1. Explanation of the fourth testcase: An array with the desired properties is b=[-40,13,40,0,-9,-31]. For this array, it holds: The first element of b is -40. The sum of the first two elements of b is -27. The sum of the first three elements of b is 13. The sum of the first four elements of b is 13. The sum of the first five elements of b is 4. The sum of the first six elements of b is -27.
4 4 1 -2 3 -4 3 0 0 0 5 1 -1 1 -1 1 6 40 -31 -9 0 13 -40
YES 1 -2 3 -4 NO YES 1 1 -1 1 -1 YES -40 13 40 0 -9 -31
1 second
256 megabytes
['math', 'sortings', '*900']
F. Number of Subsequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).InputThe first line of the input contains one integer n (3 \le n \le 200\,000) — the length of s.The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".OutputPrint the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.ExamplesInput 6 ac?b?c Output 24 Input 7 ??????? Output 2835 Input 9 cccbbbaaa Output 0 Input 5 a???c Output 46 NoteIn the first example, we can obtain 9 strings: "acabac" — there are 2 subsequences "abc", "acabbc" — there are 4 subsequences "abc", "acabcc" — there are 4 subsequences "abc", "acbbac" — there are 2 subsequences "abc", "acbbbc" — there are 3 subsequences "abc", "acbbcc" — there are 4 subsequences "abc", "accbac" — there is 1 subsequence "abc", "accbbc" — there are 2 subsequences "abc", "accbcc" — there are 2 subsequences "abc". So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
6 ac?b?c
24
1 second
256 megabytes
['combinatorics', 'dp', 'strings', '*2000']
E. Rock, Paper, Scissorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob have decided to play the game "Rock, Paper, Scissors". The game consists of several rounds, each round is independent of each other. In each round, both players show one of the following things at the same time: rock, paper or scissors. If both players showed the same things then the round outcome is a draw. Otherwise, the following rules applied: if one player showed rock and the other one showed scissors, then the player who showed rock is considered the winner and the other one is considered the loser; if one player showed scissors and the other one showed paper, then the player who showed scissors is considered the winner and the other one is considered the loser; if one player showed paper and the other one showed rock, then the player who showed paper is considered the winner and the other one is considered the loser. Alice and Bob decided to play exactly n rounds of the game described above. Alice decided to show rock a_1 times, show scissors a_2 times and show paper a_3 times. Bob decided to show rock b_1 times, show scissors b_2 times and show paper b_3 times. Though, both Alice and Bob did not choose the sequence in which they show things. It is guaranteed that a_1 + a_2 + a_3 = n and b_1 + b_2 + b_3 = n.Your task is to find two numbers: the minimum number of round Alice can win; the maximum number of rounds Alice can win. InputThe first line of the input contains one integer n (1 \le n \le 10^{9}) — the number of rounds.The second line of the input contains three integers a_1, a_2, a_3 (0 \le a_i \le n) — the number of times Alice will show rock, scissors and paper, respectively. It is guaranteed that a_1 + a_2 + a_3 = n.The third line of the input contains three integers b_1, b_2, b_3 (0 \le b_j \le n) — the number of times Bob will show rock, scissors and paper, respectively. It is guaranteed that b_1 + b_2 + b_3 = n.OutputPrint two integers: the minimum and the maximum number of rounds Alice can win.ExamplesInput 2 0 1 1 1 1 0 Output 0 1 Input 15 5 5 5 5 5 5 Output 0 15 Input 3 0 0 3 3 0 0 Output 3 3 Input 686 479 178 29 11 145 530 Output 22 334 Input 319 10 53 256 182 103 34 Output 119 226 NoteIn the first example, Alice will not win any rounds if she shows scissors and then paper and Bob shows rock and then scissors. In the best outcome, Alice will win one round if she shows paper and then scissors, and Bob shows rock and then scissors.In the second example, Alice will not win any rounds if Bob shows the same things as Alice each round.In the third example, Alice always shows paper and Bob always shows rock so Alice will win all three rounds anyway.
2 0 1 1 1 1 0
0 1
1 second
256 megabytes
['brute force', 'constructive algorithms', 'flows', 'greedy', 'math', '*1800']
D. Non-zero Segmentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKolya got an integer array a_1, a_2, \dots, a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros.Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages).Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0.InputThe first line of the input contains one integer n (2 \le n \le 200\,000) — the number of elements in Kolya's array.The second line of the input contains n integers a_1, a_2, \dots, a_n (-10^{9} \le a_i \le 10^{9}, a_i \neq 0) — the description of Kolya's array.OutputPrint the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0.ExamplesInput 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 NoteConsider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array.There are no subsegments having sum 0 in the second example so you don't need to do anything.
4 1 -5 3 2
1
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', 'sortings', '*1500']
C. Increase and Copytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInitially, you have the array a consisting of one element 1 (a = [1]).In one move, you can do one of the following things: Increase some (single) element of a by 1 (choose some i from 1 to the current length of a and increase a_i by one); Append the copy of some (single) element of a to the end of the array (choose some i from 1 to the current length of a and append a_i to the end of the array). For example, consider the sequence of five moves: You take the first element a_1, append its copy to the end of the array and get a = [1, 1]. You take the first element a_1, increase it by 1 and get a = [2, 1]. You take the second element a_2, append its copy to the end of the array and get a = [2, 1, 1]. You take the first element a_1, append its copy to the end of the array and get a = [2, 1, 1, 2]. You take the fourth element a_4, increase it by 1 and get a = [2, 1, 1, 3]. Your task is to find the minimum number of moves required to obtain the array with the sum at least n.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.The only line of the test case contains one integer n (1 \le n \le 10^9) — the lower bound on the sum of the array.OutputFor each test case, print the answer: the minimum number of moves required to obtain the array with the sum at least n.ExampleInput 5 1 5 42 1337 1000000000 Output 0 3 11 72 63244
5 1 5 42 1337 1000000000
0 3 11 72 63244
1 second
256 megabytes
['binary search', 'constructive algorithms', 'math', '*1100']
B. Symmetric Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha has n types of tiles of size 2 \times 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.Masha decides to construct the square of size m \times m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding.Symmetric with respect to the main diagonal matrix is such a square s that for each pair (i, j) the condition s[i][j] = s[j][i] holds. I.e. it is true that the element written in the i-row and j-th column equals to the element written in the j-th row and i-th column.Your task is to determine if Masha can construct a square of size m \times m which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she can not rotate tiles, she can only place them in the orientation they have in the input.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.The first line of the test case contains two integers n and m (1 \le n \le 100, 1 \le m \le 100) — the number of types of tiles and the size of the square Masha wants to construct.The next 2n lines of the test case contain descriptions of tiles types. Types of tiles are written one after another, each type is written on two lines. The first line of the description contains two positive (greater than zero) integers not exceeding 100 — the number written in the top left corner of the tile and the number written in the top right corner of the tile of the current type. The second line of the description contains two positive (greater than zero) integers not exceeding 100 — the number written in the bottom left corner of the tile and the number written in the bottom right corner of the tile of the current type.It is forbidden to rotate tiles, it is only allowed to place them in the orientation they have in the input.OutputFor each test case print the answer: "YES" (without quotes) if Masha can construct the square of size m \times m which is a symmetric matrix. Otherwise, print "NO" (withtout quotes).ExampleInput 6 3 4 1 2 5 6 5 7 7 4 8 9 9 8 2 5 1 1 1 1 2 2 2 2 1 100 10 10 10 10 1 2 4 5 8 4 2 2 1 1 1 1 1 2 3 4 1 2 1 1 1 1 Output YES NO YES NO YES YES NoteThe first test case of the input has three types of tiles, they are shown on the picture below. Masha can construct, for example, the following square of size 4 \times 4 which is a symmetric matrix:
6 3 4 1 2 5 6 5 7 7 4 8 9 9 8 2 5 1 1 1 1 2 2 2 2 1 100 10 10 10 10 1 2 4 5 8 4 2 2 1 1 1 1 1 2 3 4 1 2 1 1 1 1
YES NO YES NO YES YES
1 second
256 megabytes
['implementation', '*900']
A. Floor Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n. There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 \cdot x + 2), and so on.Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.The only line of the test case contains two integers n and x (1 \le n, x \le 1000) — the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).OutputFor each test case, print the answer: the number of floor on which Petya lives.ExampleInput 4 7 3 1 5 22 5 987 13 Output 3 1 5 77 NoteConsider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
4 7 3 1 5 22 5 987 13
3 1 5 77
1 second
256 megabytes
['implementation', 'math', '*800']
I. Impressive Harvesting of The Orchardtime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. Chanek has an orchard structured as a rooted ternary tree with N vertices numbered from 1 to N. The root of the tree is vertex 1. P_i denotes the parent of vertex i, for (2 \le i \le N). Interestingly, the height of the tree is not greater than 10. Height of a tree is defined to be the largest distance from the root to a vertex in the tree.There exist a bush on each vertex of the tree. Initially, all bushes have fruits. Fruits will not grow on bushes that currently already have fruits. The bush at vertex i will grow fruits after A_i days since its last harvest.Mr. Chanek will visit his orchard for Q days. In day i, he will harvest all bushes that have fruits on the subtree of vertex X_i. For each day, determine the sum of distances from every harvested bush to X_i, and the number of harvested bush that day. Harvesting a bush means collecting all fruits on the bush.For example, if Mr. Chanek harvests all fruits on subtree of vertex X, and harvested bushes [Y_1, Y_2, \dots, Y_M], the sum of distances is \sum_{i = 1}^M \text{distance}(X, Y_i)\text{distance}(U, V) in a tree is defined to be the number of edges on the simple path from U to V.InputThe first line contains two integers N and Q (1 \le N,\ Q,\le 5 \cdot 10^4), which denotes the number of vertices and the number of days Mr. Chanek visits the orchard.The second line contains N integers A_i (1 \le A_i \le 5 \cdot 10^4), which denotes the fruits growth speed on the bush at vertex i, for (1 \le i \le N).The third line contains N-1 integers P_i (1 \le P_i \le N, P_i \ne i), which denotes the parent of vertex i in the tree, for (2 \le i \le N). It is guaranteed that each vertex can be the parent of at most 3 other vertices. It is also guaranteed that the height of the tree is not greater than 10.The next Q lines contain a single integer X_i (1 \le X_i \le N), which denotes the start of Mr. Chanek's visit on day i, for (1 \le i \le Q).OutputOutput Q lines, line i gives the sum of distances from the harvested bushes to X_i, and the number of harvested bushes.ExamplesInput 2 3 1 2 1 2 1 1 Output 0 1 0 1 1 2 Input 5 3 2 1 1 3 2 1 2 2 1 1 1 1 Output 6 5 3 2 4 4 NoteFor the first example: On day 1, Mr. Chanek starts at vertex 2 and can harvest the bush at vertex 2. On day 2, Mr. Chanek starts at vertex 1 and only harvest from bush 1 (bush 2's fruit still has not grown yet). On day 3, Mr. Chanek starts at vertex 1 and harvests the fruits on bush 1 and 2. The sum of distances from every harvested bush to 1 is 1. For the second example, Mr. Chanek always starts at vertex 1. The bushes which Mr. Chanek harvests on day one, two, and three are [1, 2, 3, 4, 5], [2, 3], [1, 2, 3, 5], respectively.
2 3 1 2 1 2 1 1
0 1 0 1 1 2
7 seconds
256 megabytes
['data structures', '*2800']
H. Huge Boxes of Animal Toystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputChaneka has a hobby of playing with animal toys. Every toy has a different fun value, a real number. Chaneka has four boxes to store the toys with specification: The first box stores toys with fun values in range of (-\infty,-1]. The second box stores toys with fun values in range of (-1, 0). The third box stores toys with fun values in range of (0, 1). The fourth box stores toys with fun value in range of [1, \infty). Chaneka has A, B, C, D toys in the first, second, third, and fourth box, respectively. One day she decides that she only wants one toy, a super toy. So she begins to create this super toy by sewing all the toys she has.While the number of toys Chaneka has is more than 1, she takes two different toys randomly and then sews them together, creating a new toy. The fun value of this new toy is equal to the multiplication of fun values of the sewn toys. She then puts this new toy in the appropriate box. She repeats this process until she only has one toy. This last toy is the super toy, and the box that stores this toy is the special box.As an observer, you only know the number of toys in each box initially but do not know their fun values. You also don't see the sequence of Chaneka's sewing. Determine which boxes can be the special box after Chaneka found her super toy.InputThe first line has an integer T (1 \le T \le 5 \cdot 10^4), the number of test cases.Every case contains a line with four space-separated integers A B C D (0 \le A, B, C, D \le 10^6, A + B + C + D > 0), which denotes the number of toys in the first, second, third, and fourth box, respectively.OutputFor each case, print four space-separated strings. Each string represents the possibility that the first, second, third, and fourth box can be the special box from left to right.For each box, print "Ya" (Without quotes, Indonesian for yes) if that box can be the special box. Print "Tidak" (Without quotes, Indonesian for No) otherwise.ExampleInput 2 1 2 0 1 0 1 0 0 Output Ya Ya Tidak Tidak Tidak Ya Tidak Tidak NoteFor the first case, here is a scenario where the first box is the special box: The first box had toys with fun values \{-3\}. The second box had toys with fun values \{ -0.5, -0.5 \} The fourth box had toys with fun values \{ 3 \} The sewing sequence: Chaneka sews the toy with fun -0.5 and -0.5 to a toy with fun 0.25 and then put it in the third box. Chaneka sews the toy with fun -3 and 0.25 to a toy with fun -0.75 and then put it in the second box. Chaneka sews the toy with fun -0.75 and 3 to a toy with fun -1.25 and then put it in the first box, which then became the special box. Here is a scenario where the second box ends up being the special box: The first box had toys with fun values \{-3\} The second box had toys with fun values \{ -0.33, -0.25 \}. The fourth box had toys with fun values \{ 3 \}. The sewing sequence: Chaneka sews the toy with fun -3 and -0.33 to a toy with fun 0.99 and then put it in the third box. Chaneka sews the toy with fun 0.99 and 3 to a toy with fun 2.97 and then put in it the fourth box. Chaneka sews the toy with fun 2.97 and -0.25 to a toy with fun -0.7425 and then put it in the second box, which then became the special box. There is only one toy for the second case, so Chaneka does not have to sew anything because that toy, by definition, is the super toy.
2 1 2 0 1 0 1 0 0
Ya Ya Tidak Tidak Tidak Ya Tidak Tidak
2 seconds
256 megabytes
['constructive algorithms', '*1300']
F. Flamingoes of Mysterytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. You have to use a flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java — System.out.flush(), in Pascal — flush(output) and in Python — sys.stdout.flush().Mr. Chanek wants to buy a flamingo to accompany his chickens on his farm. Before going to the pet shop, Mr. Chanek stops at an animal festival to have fun. It turns out there is a carnival game with a flamingo as the prize.There are N mysterious cages, which are numbered from 1 to N. Cage i has A_i (0 \le A_i \le 10^3) flamingoes inside (1 \le i \le N). However, the game master keeps the number of flamingoes inside a secret. To win the flamingo, Mr. Chanek must guess the number of flamingoes in each cage.Coincidentally, Mr. Chanek has N coins. Each coin can be used to ask once, what is the total number of flamingoes inside cages numbered L to R inclusive? With L < R.InputUse standard input to read the responses of your questions.Initially, the judge will give an integer N (3 \le N \le 10^3), the number of cages, and the number of coins Mr. Chanek has.For each of your questions, the jury will give an integer that denotes the number of flamingoes from cage L to R inclusive.If your program does not guess the flamingoes or ask other questions, you will get "Wrong Answer". Of course, if your program asks more questions than the allowed number, your program will get "Wrong Answer".OutputTo ask questions, your program must use standard output.Then, you can ask at most N questions. Questions are asked in the format "? L R", (1 \le L < R \le N). To guess the flamingoes, print a line that starts with "!" followed by N integers where the i-th integer denotes the number of flamingo in cage i. After answering, your program must terminate or will receive the "idle limit exceeded" verdict. You can only guess the flamingoes once.ExamplesInput6 5 15 10 Output ? 1 2 ? 5 6 ? 3 4 ! 1 4 4 6 7 8NoteIn the sample input, the correct flamingoes amount is [1, 4, 4, 6, 7, 8].
Input6 5 15 10 
Output ? 1 2 ? 5 6 ? 3 4 ! 1 4 4 6 7 8
2 seconds
256 megabytes
['interactive', '*1400']
E. Excitation of Atomstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it.There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_i energy. When atom i is excited, it will give A_i energy. You can excite any number of atoms (including zero).These atoms also form a peculiar one-way bond. For each i, (1 \le i < N), if atom i is excited, atom E_i will also be excited at no cost. Initially, E_i = i+1. Note that atom N cannot form a bond to any atom.Mr. Chanek must change exactly K bonds. Exactly K times, Mr. Chanek chooses an atom i, (1 \le i < N) and changes E_i to a different value other than i and the current E_i. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve!note: You must first change exactly K bonds before you can start exciting atoms.InputThe first line contains two integers N K (4 \le N \le 10^5, 0 \le K < N), the number of atoms, and the number of bonds that must be changed.The second line contains N integers A_i (1 \le A_i \le 10^6), which denotes the energy given by atom i when on excited state.The third line contains N integers D_i (1 \le D_i \le 10^6), which denotes the energy needed to excite atom i.OutputA line with an integer that denotes the maximum number of energy that Mr. Chanek can get.ExampleInput 6 1 5 6 7 8 10 2 3 5 6 7 1 10 Output 35 NoteAn optimal solution to change E_5 to 1 and then excite atom 5 with energy 1. It will cause atoms 1, 2, 3, 4, 5 be excited. The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10) - 1 = 35.Another possible way is to change E_3 to 1 and then exciting atom 3 (which will excite atom 1, 2, 3) and exciting atom 4 (which will excite atom 4, 5, 6). The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10 + 2) - (6 + 7) = 25 which is not optimal.
6 1 5 6 7 8 10 2 3 5 6 7 1 10
35
2 seconds
256 megabytes
['greedy', 'implementation', '*2200']
D. Danger of Mad Snakestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. Chanek The Ninja is one day tasked with a mission to handle mad snakes that are attacking a site. Now, Mr. Chanek already arrived at the hills where the destination is right below these hills. The mission area can be divided into a grid of size 1000 \times 1000 squares. There are N mad snakes on the site, the i'th mad snake is located on square (X_i, Y_i) and has a danger level B_i.Mr. Chanek is going to use the Shadow Clone Jutsu and Rasengan that he learned from Lord Seventh to complete this mission. His attack strategy is as follows: Mr. Chanek is going to make M clones. Each clone will choose a mad snake as the attack target. Each clone must pick a different mad snake to attack. All clones jump off the hills and attack their respective chosen target at once with Rasengan of radius R. If the mad snake at square (X, Y) is attacked with a direct Rasengan, it and all mad snakes at squares (X', Y') where max(|X' - X|, |Y' - Y|) \le R will die. The real Mr. Chanek will calculate the score of this attack. The score is defined as the square of the sum of the danger levels of all the killed snakes. Now Mr. Chanek is curious, what is the sum of scores for every possible attack strategy? Because this number can be huge, Mr. Chanek only needs the output modulo 10^9 + 7.InputThe first line contains three integers N M R (1 \le M \le N \le 2 \cdot 10^3, 0 \le R < 10^3), the number of mad snakes, the number of clones, and the radius of the Rasengan.The next N lines each contains three integers, X_i, Y_i, dan B_i (1 \le X_i, Y_i \le 10^3, 1 \le B_i \le 10^6). It is guaranteed that no two mad snakes occupy the same square.OutputA line with an integer that denotes the sum of scores for every possible attack strategy.ExampleInput 4 2 1 1 1 10 2 2 20 2 3 30 5 2 40 Output 33800 NoteHere is the illustration of all six possible attack strategies. The circles denote the chosen mad snakes, and the blue squares denote the region of the Rasengan: So, the total score of all attacks is: 3.600 + 3.600 + 4.900 + 3.600 + 10.000 + 8.100 = 33.800.
4 2 1 1 1 10 2 2 20 2 3 30 5 2 40
33800
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', '*2300']
C. Captain of Knightstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. Chanek just won the national chess tournament and got a huge chessboard of size N \times M. Bored with playing conventional chess, Mr. Chanek now defines a function F(X, Y), which denotes the minimum number of moves to move a knight from square (1, 1) to square (X, Y). It turns out finding F(X, Y) is too simple, so Mr. Chanek defines:G(X, Y) = \sum_{i=X}^{N} \sum_{j=Y}^{M} F(i, j)Given X and Y, you are tasked to find G(X, Y).A knight can move from square (a, b) to square (a', b') if and only if |a - a'| > 0, |b - b'| > 0, and |a - a'| + |b - b'| = 3. Of course, the knight cannot leave the chessboard.InputThe first line contains an integer T (1 \le T \le 100), the number of test cases.Each test case contains a line with four integers X Y N M (3 \leq X \leq N \leq 10^9, 3 \leq Y \leq M \leq 10^9).OutputFor each test case, print a line with the value of G(X, Y) modulo 10^9 + 7.ExampleInput 2 3 4 5 6 5 5 8 8 Output 27 70
2 3 4 5 6 5 5 8 8
27 70
2 seconds
256 megabytes
['math', '*3100']
B. Blue and Red of Our Faculty!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's our faculty's 34th anniversary! To celebrate this great event, the Faculty of Computer Science, University of Indonesia (Fasilkom), held CPC - Coloring Pavements Competition. The gist of CPC is two players color the predetermined routes of Fasilkom in Blue and Red. There are N Checkpoints and M undirected predetermined routes. Routes i connects checkpoint U_i and V_i, for (1 \le i \le M). It is guaranteed that any pair of checkpoints are connected by using one or more routes.The rules of CPC is as follows: Two players play in each round. One player plays as blue, the other plays as red. For simplicity, let's call these players Blue and Red. Blue will color every route in he walks on blue, Red will color the route he walks on red. Both players start at checkpoint number 1. Initially, all routes are gray. Each phase, from their current checkpoint, Blue and Red select a different gray route and moves to the checkpoint on the other end of the route simultaneously. The game ends when Blue or Red can no longer move. That is, there is no two distinct gray routes they can choose to continue moving. Chaneka is interested in participating. However, she does not want to waste much energy. So, She is only interested in the number of final configurations of the routes after each round. Turns out, counting this is also exhausting, so Chaneka asks you to figure this out!Two final configurations are considered different if there is a route U in a different color in the two configurations.InputThe first line contains two integers N and M. N (2 \le N \le 2 \cdot 10^3) denotes the number of checkpoints, M (1 \le M \le 2 \cdot N) denotes the number of routes. It is guaranteed that every checkpoint except checkpoint 1 has exactly two routes connecting it.The next M lines each contains two integers U_i and V_i (1 \le U_i, V_i \le N, U_i \ne V_i), which denotes the checkpoint that route i connects.It is guaranteed that for every pair of checkpoints, there exists a path connecting them directly or indirectly using the routes. OutputOutput a single integer which denotes the number of final configurations after each round of CPC modulo 10^9 + 7ExampleInput 5 6 1 2 2 3 3 4 4 1 1 5 5 1 Output 8 NoteEvery possible final configuration for the example is listed below: The blue-colored numbers give the series of moves Blue took, and the red-colored numbers give the series of moves Red took.
5 6 1 2 2 3 3 4 4 1 1 5 5 1
8
2 seconds
256 megabytes
['divide and conquer', 'dp', '*2600']
A. Arena of Greedtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing N gold coins. The game ends if there are no more gold coins in the chest. In each turn, the players can make one of the following moves: Take one gold coin from the chest. Take half of the gold coins on the chest. This move is only available if the number of coins in the chest is even. Both players will try to maximize the number of coins they have. Mr. Chanek asks your help to find the maximum number of coins he can get at the end of the game if both he and the opponent plays optimally.InputThe first line contains a single integer T (1 \le T \le 10^5) denotes the number of test cases.The next T lines each contain a single integer N (1 \le N \le 10^{18}).OutputT lines, each line is the answer requested by Mr. Chanek.ExampleInput 2 5 6 Output 2 4 NoteFor the first case, the game is as follows: Mr. Chanek takes one coin. The opponent takes two coins. Mr. Chanek takes one coin. The opponent takes one coin. For the second case, the game is as follows: Mr. Chanek takes three coins. The opponent takes one coin. Mr. Chanek takes one coin. The opponent takes one coin.
2 5 6
2 4
2 seconds
256 megabytes
['games', 'greedy', '*1400']
M. Ancient Languagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.InputFirst-line contains two integers: n and k (1 \le n, k \le 10^3) — the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 \le n \lt 10^3) — the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.OutputOutput a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.ExampleInput 3 3 2 b b bbac 0 a aca acba 1 ab c ccb Output acb
3 3 2 b b bbac 0 a aca acba 1 ab c ccb
acb
2 seconds
256 megabytes
['graphs', 'sortings', '*2200']
G. Yearstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring one of the space missions, humans have found an evidence of previous life at one of the planets. They were lucky enough to find a book with birth and death years of each individual that had been living at this planet. What's interesting is that these years are in the range (1, 10^9)! Therefore, the planet was named Longlifer.In order to learn more about Longlifer's previous population, scientists need to determine the year with maximum number of individuals that were alive, as well as the number of alive individuals in that year. Your task is to help scientists solve this problem!InputThe first line contains an integer n (1 \le n \le 10^5) — the number of people.Each of the following n lines contain two integers b and d (1 \le b \lt d \le 10^9) representing birth and death year (respectively) of each individual.OutputPrint two integer numbers separated by blank character, y  — the year with a maximum number of people alive and k  — the number of people alive in year y.In the case of multiple possible solutions, print the solution with minimum year.ExamplesInput 3 1 5 2 4 5 6 Output 2 2 Input 4 3 4 4 5 4 6 8 10 Output 4 2 NoteYou can assume that an individual living from b to d has been born at the beginning of b and died at the beginning of d, and therefore living for d - b years.
3 1 5 2 4 5 6
2 2
1 second
256 megabytes
['data structures', 'sortings', '*1300']
N. BubbleSquare Tokenstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBubbleSquare social network is celebrating 13^{th} anniversary and it is rewarding its members with special edition BubbleSquare tokens. Every member receives one personal token. Also, two additional tokens are awarded to each member for every friend they have on the network. Yet, there is a twist – everyone should end up with different number of tokens from all their friends. Each member may return one received token. Also, each two friends may agree to each return one or two tokens they have obtained on behalf of their friendship.InputFirst line of input contains two integer numbers n and k (2 \leq n \leq 12500, 1 \leq k \leq 1000000) - number of members in network and number of friendships.Next k lines contain two integer numbers a_i and b_i (1 \leq a_i, b_i \leq n, a_i \neq b_i) - meaning members a_i and b_i are friends.OutputFirst line of output should specify the number of members who are keeping their personal token.The second line should contain space separated list of members who are keeping their personal token.Each of the following k lines should contain three space separated numbers, representing friend pairs and number of tokens each of them gets on behalf of their friendship.ExamplesInput 2 1 1 2 Output 1 1 1 2 0 Input 3 3 1 2 1 3 2 3 Output 0 1 2 0 2 3 1 1 3 2 NoteIn the first test case, only the first member will keep its personal token and no tokens will be awarded for friendship between the first and the second member.In the second test case, none of the members will keep their personal token. The first member will receive two tokens (for friendship with the third member), the second member will receive one token (for friendship with the third member) and the third member will receive three tokens (for friendships with the first and the second member).
2 1 1 2
1 1 1 2 0
2 seconds
256 megabytes
['*3500']
M. Milutin's Plumstime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputAs you all know, the plum harvesting season is on! Little Milutin had his plums planted in an orchard that can be represented as an n by m matrix. While he was harvesting, he wrote the heights of all trees in a matrix of dimensions n by m.At night, when he has spare time, he likes to perform various statistics on his trees. This time, he is curious to find out the height of his lowest tree. So far, he has discovered some interesting properties of his orchard. There is one particular property that he thinks is useful for finding the tree with the smallest heigh.Formally, let L(i) be the leftmost tree with the smallest height in the i-th row of his orchard. He knows that L(i) \le L(i+1) for all 1 \le i \le n - 1. Moreover, if he takes a submatrix induced by any subset of rows and any subset of columns, L(i) \le L(i+1) will hold for all 1 \le i \le n'-1, where n' is the number of rows in that submatrix.Since the season is at its peak and he is short on time, he asks you to help him find the plum tree with minimal height.InputThis problem is interactive.The first line of input will contain two integers n and m, representing the number of rows and the number of columns in Milutin's orchard. It is guaranteed that 1 \le n, m \le 10^6.The following lines will contain the answers to your queries.OutputOnce you know have found the minimum value r, you should print ! r to the standard output.InteractionYour code is allowed to query for an entry (i, j) of a matrix (i.e. get the height of the tree which is in the i-th row and j-th column). The query should be formatted as ? i j, so that 1 \le i \le n and 1 \le j \le m.You may assume that the entries of the matrix will be integers between 1 and 10^9.Your solution should use not more than \mathbf{4 \cdot (n + m)} queries.This is an interactive problem. You have to use a flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java — System.out.flush(), in Pascal — flush(output) and in Python — sys.stdout.flush().ExampleInput 5 5 13 15 10 9 15 15 17 12 11 17 10 12 7 6 12 17 19 14 13 19 16 18 13 12 18 Output
5 5 13 15 10 9 15 15 17 12 11 17 10 12 7 6 12 17 19 14 13 19 16 18 13 12 18
null
1 second
1024 megabytes
['interactive', '*2800']
L. Light switchestime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputNikola owns a large warehouse which is illuminated by N light bulbs, numbered 1 to N. At the exit of the warehouse, there are S light switches, numbered 1 to S. Each switch swaps the on/off state for some light bulbs, so if a light bulb is off, flipping the switch turns it on, and if the light bulb is on, flipping the switch turns it off.At the end of the day, Nikola wants to turn all the lights off. To achieve this, he will flip some of the light switches at the exit of the warehouse, but since Nikola is lazy, he wants to flip the _minimum_ number of switches required to turn all the lights off. Since Nikola was not able to calculate the minimum number of switches, he asked you to help him. During a period of D days, Nikola noted which light bulbs were off and which were on at the end of each day. He wants you to tell him the minimum number of switches he needed to flip to turn all the lights off for each of the D days or tell him that it's impossible.InputFirst line contains three integers, N, S and D (1 \leq N \leq 10^3, 1 \leq S \leq 30, 1 \leq D \leq 10^3) – representing number of light bulbs, the number of light switches, and the number of days respectively.The next S lines contain the description of each light switch as follows: The first number in the line, C_i (1 \leq C_i \leq N), represents the number of light bulbs for which the on/off state is swapped by light switch i, the next C_i numbers (sorted in increasing order) represent the indices of those light bulbs.The next D lines contain the description of light bulbs for each day as follows: The first number in the line, T_i (1 \leq T_i \leq N), represents the number of light bulbs which are on at the end of day i, the next T_i numbers (sorted in increasing order) represent the indices of those light bulbs.OutputPrint D lines, one for each day. In the i^{th} line, print the minimum number of switches that need to be flipped on day i, or -1 if it's impossible to turn all the lights off.ExampleInput 4 3 4 2 1 2 2 2 3 1 2 1 1 2 1 3 3 1 2 3 3 1 2 4 Output 2 2 3 -1
4 3 4 2 1 2 2 2 3 1 2 1 1 2 1 3 3 1 2 3 3 1 2 4
2 2 3 -1
3 seconds
1024 megabytes
['meet-in-the-middle', '*2600']
K. Lonely Numberstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.More precisely, two different numbers a and b are friends if gcd(a,b), \frac{a}{gcd(a,b)}, \frac{b}{gcd(a,b)} can form sides of a triangle.Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.In a group of numbers, a number is lonely if it doesn't have any friends in that group.Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?InputThe first line contains a single integer t (1 \leq t \leq 10^6) - number of test cases.On next line there are t numbers, n_i (1 \leq n_i \leq 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.OutputFor each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.ExampleInput 3 1 5 10 Output 1 3 3 NoteFor first test case, 1 is the only number and therefore lonely.For second test case where n=5, numbers 1, 3 and 5 are lonely.For third test case where n=10, numbers 1, 5 and 7 are lonely.
3 1 5 10
1 3 3
1.5 seconds
256 megabytes
['binary search', 'math', 'number theory', 'two pointers', '*1600']
J. Bubble Cup hypothesistime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Bubble Cup hypothesis stood unsolved for 130 years. Who ever proves the hypothesis will be regarded as one of the greatest mathematicians of our time! A famous mathematician Jerry Mao managed to reduce the hypothesis to this problem:Given a number m, how many polynomials P with coefficients in set {\{0,1,2,3,4,5,6,7\}} have: P(2)=m?Help Jerry Mao solve the long standing problem!InputThe first line contains a single integer t (1 \leq t \leq 5\cdot 10^5) - number of test cases.On next line there are t numbers, m_i (1 \leq m_i \leq 10^{18}) - meaning that in case i you should solve for number m_i.OutputFor each test case i, print the answer on separate lines: number of polynomials P as described in statement such that P(2)=m_i, modulo 10^9 + 7.ExampleInput 2 2 4 Output 2 4 NoteIn first case, for m=2, polynomials that satisfy the constraint are x and 2.In second case, for m=4, polynomials that satisfy the constraint are x^2, x + 2, 2x and 4.
2 2 4
2 4
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'dp', 'math', '*2400']
I. Lookup Tablestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn has Q closed intervals of consecutive 2K-bit numbers [l_i, r_i] and one 16-bit value v_i for each interval. (0 \leq i < Q)John wants to implement a function F that maps 2K-bit numbers to 16-bit numbers in such a way that inputs from each interval are mapped to that interval's value. In other words: F(x) = v_i, \; \textrm{for every } 0 \leq i < Q \; \textrm{, and every } x \in [l_i, r_i] The output of F for other inputs is unimportant.John wants to make his implementation of F fast so he has decided to use lookup tables. A single 2K-bit lookup table would be too large to fit in memory, so instead John plans to use two K-bit lookup tables, LSBTable and MSBTable. His implementation will look like this: F(x) = \textrm{LSBTable}[\textrm{lowKBits}(x)] \; \& \; \textrm{MSBTable}[\textrm{highKBits}(x)] In other words it returns the "bitwise and" of results of looking up the K least significant bits in LSBTable and the K most significant bits in MSBTable.John needs your help. Given K, Q and Q intervals [l_i, r_i] and values v_i, find any two lookup tables which can implement F or report that such tables don't exist.InputThe first line contains two integers K and Q ( 1 <= K <= 16, 1 <= Q <= 2\cdot 10^5).Each of the next Q lines contains three integers l_i, r_i and v_i. ( 0 \leq l_i \leq r_i < 2^{2K}, 0 \leq v_i < 2^{16}).OutputOn the first line output "possible" (without quotes) if two tables satisfying the conditions exist, or "impossible" (without quotes) if they don't exist.If a solution exists, in the next 2 \cdot 2^K lines your program should output all values of the two lookup tables (LSBTable and MSBTable) it found. When there are multiple pairs of tables satisfying the conditions, your program may output any such pair. On lines 1 + i output \textrm{LSBTable}[i]. (0 \leq i < 2^K, 0 \leq \textrm{LSBTable}[i] < 2^{16}).On lines 1 + 2^K + i output \textrm{MSBTable}[i]. (0 \leq i < 2^K, 0 \leq \textrm{MSBTable}[i] < 2^{16}).ExamplesInput 1 2 0 2 1 3 3 3 Output possible 1 3 1 3 Input 2 4 4 5 3 6 7 2 0 3 0 12 13 1 Output possible 3 3 2 2 0 3 0 1 Input 2 3 4 4 3 5 6 2 12 14 1 Output impossible NoteA closed interval [a, b] includes both a and b.In the first sample, tables \textrm{LSBTable} = [1,3] and \textrm{MSBTable} = [1,3] satisfy the conditions: F[0] = \textrm{LSBTable}[0] \& \textrm{MSBTable}[0] = 1 \& 1 = 1, F[1] = \textrm{LSBTable}[1] \& \textrm{MSBTable}[0] = 3 \& 1 = 1, F[2] = \textrm{LSBTable}[0] \& \textrm{MSBTable}[1] = 1 \& 3 = 1, F[3] = \textrm{LSBTable}[1] \& \textrm{MSBTable}[1] = 3 \& 3 = 3.In the second sample, tables \textrm{LSBTable} = [3,3,2,2] and \textrm{MSBTable} = [0,3,0,1] satisfy all the conditions.In the third sample there are no two lookup tables which can satisfy the conditions.
1 2 0 2 1 3 3 3
possible 1 3 1 3
1 second
256 megabytes
['bitmasks', '*3000']
H. Virustime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Bubbleland a group of special programming forces gets a top secret job to calculate the number of potentially infected people by a new unknown virus. The state has a population of n people and every day there is new information about new contacts between people. The job of special programming forces is to calculate how many contacts in the last k days a given person had. The new virus has an incubation period of k days, and after that time people consider as non-infectious. Because the new virus is an extremely dangerous, government mark as suspicious everybody who had direct or indirect contact in the last k days, independently of the order of contacts.This virus is very strange, and people can't get durable immunity.You need to help special programming forces to calculate the number of suspicious people for a given person (number of people who had contact with a given person).There are 3 given inputs on beginning n where n is population, q number of queries, k virus incubation time in days. Each query is one of three types: (x, y) person x and person y met that day (x \neq y). (z) return the number of people in contact with z, counting himself. The end of the current day moves on to the next day. InputThe first line of input contains three integers n (1 \le n\le 10^5) the number of people in the state, q (1 \le q\le 5×10^5) number of queries and k (1 \le k\le 10^5) virus incubation time in days.Each of the next q lines starts with an integer t (1 \le t\le 3) the type of the query.A pair of integers x and y (1 \le x, y \le n) follows in the query of the first type (x \neq y).An integer i (1 \le i\le n) follows in the query of the second type. Query of third type does not have the following number.OutputFor the queries of the second type print on a separate line the current number of people in contact with a given person.ExamplesInput 5 12 1 1 1 2 1 1 3 1 3 4 2 4 2 5 3 2 1 1 1 2 1 3 2 2 1 3 2 1 Output 4 1 1 3 1 Input 5 12 2 1 1 2 1 1 3 1 3 4 2 4 2 5 3 2 1 1 1 2 1 3 2 2 1 3 2 1 Output 4 1 4 4 3 Input 10 25 2 1 9 3 2 5 1 1 3 1 3 1 2 2 1 8 3 1 5 6 3 1 9 2 1 8 3 2 9 1 3 1 2 5 1 6 4 3 3 2 4 3 1 10 9 1 1 7 3 2 2 3 1 5 6 1 1 4 Output 1 1 5 2 1 1 NotePay attention if persons 1 and 2 had contact first day and next day persons 1 and 3 had contact, for k>1 number of contacts of person 3 is 3(persons:1,2,3).
5 12 1 1 1 2 1 1 3 1 3 4 2 4 2 5 3 2 1 1 1 2 1 3 2 2 1 3 2 1
4 1 1 3 1
5 seconds
256 megabytes
['data structures', 'divide and conquer', 'dsu', 'graphs', '*2500']
G. Growing flowerstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N.Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}.In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type.You will be given Q queries and each of those queries will be of the following two types: You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection.InputFirst line contains two integers N and Q \;(1 \leq N, Q \leq 10^5)\, — number of flowers and the number of queries, respectively.The second line contains N integers A_1, A_2, ..., A_N\;(1 \leq A_i \leq 10^9)\, — where A_i represents type of the i-th flower.Each of the next Q lines describe queries and start with integer T\in\{1, 2\}. If T = 1, there will be three more integers in the line L, R, X\;(1 \leq L, R \leq N;\; 1 \leq X \leq 10^9)\, — L and R describing boundaries and X describing the flower type If T = 2, there will be one more integer in the line K\;(1 \leq K \leq N)\, — resident's width of view OutputFor each query of the second type print the beautiness B of the collection.ExampleInput 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 NoteLet's look at the example.Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9.After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6After the fourth query, the collection becomes [5, 5, 5, 5, 5].For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2
9 6 4
4 seconds
256 megabytes
['data structures', '*3500']
F. Coinstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them:All of them take a sit at their round table, some of them with the golden coins they have just stolen. At each iteration of the game if one of them has equal or more than 2 coins, he is eligible to the splitting and he gives one coin to each pirate sitting next to him. If there are more candidates (pirates with equal or more than 2 coins) then You are the one that chooses which one of them will do the splitting in that iteration. The game ends when there are no more candidates eligible to do the splitting. Pirates can call it a day, only when the game ends. Since they are beings with a finite amount of time at their disposal, they would prefer if the game that they are playing can end after finite iterations, and if so, they call it a good game. On the other hand, if no matter how You do the splitting, the game cannot end in finite iterations, they call it a bad game. Can You help them figure out before they start playing if the game will be good or bad?InputThe first line of input contains two integer numbers n and k (1 \le n \le 10^{9}, 0 \le k \le 2\cdot10^5), where n denotes total number of pirates and k is the number of pirates that have any coins.The next k lines of input contain integers a_i and b_i (1 \le a_i \le n, 1 \le b_i \le 10^{9}), where a_i denotes the index of the pirate sitting at the round table (n and 1 are neighbours) and b_i the total number of coins that pirate a_i has at the start of the game. OutputPrint 1 if the game is a good game: There is a way to do the splitting so the game ends after finite number of iterations.Print -1 if the game is a bad game: No matter how You do the splitting the game does not end in finite number of iterations.ExamplesInput 4 2 1 2 2 2 Output 1Input 6 2 2 3 4 1 Output 1Input 3 2 1 1 2 2 Output -1NoteIn the third example the game has no end, because You always only have only one candidate, after whose splitting you end up in the same position as the starting one.
4 2 1 2 2 2
1
1 second
256 megabytes
['math', '*2700']
E. 5G Antenna Towerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter making a strategic plan with carriers for expansion of mobile network throughout the whole country, the government decided to cover rural areas with the last generation of 5G network.Since 5G antenna towers will be built in the area of mainly private properties, the government needs an easy way to find information about landowners for each property partially or fully contained in the planned building area. The planned building area is represented as a rectangle with sides width and height.Every 5G antenna tower occupies a circle with a center in (x,y) and radius r. There is a database of Geodetic Institute containing information about each property. Each property is defined with its identification number and polygon represented as an array of (x,y) points in the counter-clockwise direction. Your task is to build an IT system which can handle queries of type (x, y, r) in which (x,y) represents a circle center, while r represents its radius. The IT system should return the total area of properties that need to be acquired for the building of a tower so that the government can estimate the price. Furthermore, the system should return a list of identification numbers of these properties (so that the owners can be contacted for land acquisition).A property needs to be acquired if the circle of the antenna tower is intersecting or touching it. InputThe first line contains the size of the building area as double values width, height, and an integer n — the number of properties in the database. Each of the next n lines contains the description of a single property in the form of an integer number v (3 \le v \le 40) — the number of points that define a property, as well as 2*v double numbers — the coordinates (x,y) of each property point. Line i (0 \le i \le n-1) contains the information for property with id i.The next line contains an integer q — the number of queries. Each of the next q lines contains double values x, y, r — the coordinates of an antenna circle center (x, y) and its radius r.1 \le n * q \le 10^6OutputFor each of the q queries, your program should output a line containing the total area of all the properties that need to be acquired, an integer representing the number of such properties, as well as the list of ids of these properties (separated by blank characters, arbitrary order).ExampleInput 10 10 3 4 2 2 3 2 3 3 2 3 3 3.5 2 4.5 2 4.5 3 4 7 8 7.5 8.5 8 8 7.5 9 5 2 3.5 0.5 3.3 2 0.4 5 2.5 0.5 7.5 8.5 0.5 3 7 0.5 Output 1.000000 1 0 1.500000 2 0 1 0.500000 1 1 0.250000 1 2 0.000000 0 NoteYou can assume that the land not covered with properties (polygons) is under the government's ownership and therefore doesn't need to be acquired. Properties do not intersect with each other.Precision being used for solution checking is 10^{-4}.
10 10 3 4 2 2 3 2 3 3 2 3 3 3.5 2 4.5 2 4.5 3 4 7 8 7.5 8.5 8 8 7.5 9 5 2 3.5 0.5 3.3 2 0.4 5 2.5 0.5 7.5 8.5 0.5 3 7 0.5
1.000000 1 0 1.500000 2 0 1 0.500000 1 1 0.250000 1 2 0.000000 0
2 seconds
256 megabytes
['geometry', '*2700']
D. Does anyone else hate the wind?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMark and his crew are sailing across the sea of Aeolus (in Greek mythology Aeolus was the keeper of the winds). They have the map which represents the NxM matrix with land and sea fields and they want to get to the port (the port is considered as sea field). They are in a hurry because the wind there is very strong and changeable and they have the food for only K days on the sea (that is the maximum that they can carry on the ship). John, the guy from Mark's crew, knows how to predict the direction of the wind on daily basis for W days which is enough time for them to reach the port or to run out of the food. Mark can move the ship in four directions (north, east, south, west) by one field for one day, but he can also stay in the same place. Wind can blow in four directions (north, east, south, west) or just not blow that day. The wind is so strong at the sea of Aeolus that it moves the ship for one whole field in the direction which it blows at. The ship's resulting movement is the sum of the ship's action and wind from that day. Mark must be careful in order to keep the ship on the sea, the resulting movement must end on the sea field and there must be a 4-connected path through the sea from the starting field. A 4-connected path is a path where you can go from one cell to another only if they share a side.For example in the following image, the ship can't move to the port as there is no 4-connected path through the sea. In the next image, the ship can move to the port as there is a 4-connected path through the sea as shown with the red arrow. Furthermore, the ship can move to the port in one move if one of the following happens. Wind is blowing east and Mark moves the ship north, or wind is blowing north and Mark moves the ship east. In either of these scenarios the ship will end up in the port in one move. Mark must also keep the ship on the map because he doesn't know what is outside. Lucky for Mark and his crew, there are T fish shops at the sea where they can replenish their food supplies to the maximum, but each shop is working on only one day. That means that Mark and his crew must be at the shop's position on the exact working day in order to replenish their food supplies. Help Mark to find the minimum of days that he and his crew need to reach the port or print -1 if that is impossible with the food supplies that they have.InputFirst line contains two integer numbers N and M (1 \leq N, M \leq 200) - representing the number of rows and number of columns of the map. Second line contains three integers, K (0 \leq K \leq 200) which is the number of days with the available food supplies, T (0 \leq T \leq 20) which is the number of fields with additional food supplies and W (0 \leq W \leq 10^6) which is the number of days with wind information.Next is the NxM char matrix filled with the values of 'L', 'S', 'P' or 'M'. 'L' is for the land and 'S' is for the sea parts. 'P' is for the port field and 'M' is the starting field for the ship.Next line contains W chars with the wind direction information for every day. The possible inputs are 'N' - north, 'S' - south, 'E' - east, 'W' - west and 'C' - no wind. If Mark's crew can reach the port, it is guaranteed that they will not need more than W days to reach it.In the end there are T lines with the food supplies positions. Each line contains three integers, Y_i and X_i (0 \leq Y_i < N, 0 \leq X_i < M) representing the coordinates (Y is row number and X is column number) of the food supply and F_i (0 \leq F_i \leq 10^6) representing the number of days from the starting day on which the food supply is available.OutputOne integer number representing the minimal days to reach the port or -1 if that is impossible.ExamplesInput 3 3 5 2 15 M S S S S S S S P S W N N N N N N N N N N N N N 2 1 0 1 2 0 Output -1Input 3 3 5 2 15 M S S S S S S S P S E N N N N N N N N N N N N N 2 1 0 1 2 0 Output 2Input 5 5 4 1 15 M S S S S S S S S L S S S L L S S S S S S S S S P C C C C S S E E C C C C C C C 0 1 4 Output 8
3 3 5 2 15 M S S S S S S S P S W N N N N N N N N N N N N N 2 1 0 1 2 0
-1
1 second
256 megabytes
['*3100']
C. Dušan's Railwaytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you may already know, Dušan is keen on playing with railway models. He has a big map with cities that are connected with railways. His map can be seen as a graph where vertices are cities and the railways connecting them are the edges. So far, the graph corresponding to his map is a tree. As you already know, a tree is a connected acyclic undirected graph.He is curious to find out whether his railway can be optimized somehow. He wants to add so-called shortcuts, which are also railways connecting pairs of cities. This shortcut will represent the railways in the unique path in the tree between the pair of cities it connects. Since Dušan doesn't like repeating the railways, he has also defined good paths in his newly obtained network (notice that after adding the shortcuts, his graph is no more a tree). He calls a path good, if no edge appears more than once, either as a regular railway edge or as an edge represented by some shortcut (Every shortcut in a good path has length 1, but uses up all the edges it represents - they can't appear again in that path). Having defined good paths, he defines good distance between two cities to be the length of the shortest good path between them. Finally, the shortcutting diameter of his network is the largest good distance between any two cities.Now he is curious to find out whether it is possible to achieve shortcutting diameter less or equal than k, while adding as few shortcuts as possible.Your solution should add no more than \mathbf{10 \cdot n} shortcuts.InputThe first line in the standard input contains an integer n (1 \le n \le 10^4), representing the number of the cities in Dušan's railway map, and an integer k (3 \le k \le n) representing the shortcutting diameter that he wants to achieve.Each of the following n - 1 lines will contain two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \neq v_i), meaning that there is a railway between cities u_i and v_i.OutputThe first line of the output should contain a number t representing the number of the shortcuts that were added.Each of the following t lines should contain two integers u_i and v_i, signifying that a shortcut is added between cities u_i and v_i.ExampleInput 10 3 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 Output 8 3 7 3 5 3 6 3 1 7 9 7 10 7 4 7 5 NoteNotice that adding a shortcut between all cities and city 1 will make a graph theoretic diameter become 2. On the other hand, the paths obtained that way might not be good, since some of the edges might get duplicated. In the example, adding a shortcut between all cities and city 1 doesn't create a valid solution, because for cities 5 and 10 the path that uses shortcuts 5-1 and 1-10 is not valid because it uses edges 1-2, 2-3, 3-4, 4-5 twice.
10 3 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10
8 3 7 3 5 3 6 3 1 7 9 7 10 7 4 7 5
1 second
256 megabytes
['divide and conquer', 'graphs', 'trees', '*3500']
B. Valuable Papertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.InputThe first line contains two integers N (1 \leq N \leq 10^4) - number of airports/factories, and M (1 \leq M \leq 10^5) - number of available pairs to build a road between.On next M lines, there are three integers u, v (1 \leq u,v \leq N), d (1 \leq d \leq 10^9) - meaning that you can build a road between airport u and factory v for d days.OutputIf there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.ExampleInput 3 5 1 2 1 2 3 2 3 3 3 2 1 4 2 2 5 Output 4
3 5 1 2 1 2 3 2 3 3 3 2 1 4 2 2 5
4
2 seconds
256 megabytes
['binary search', 'flows', 'graph matchings', 'graphs', '*1900']
A. Wakanda Forevertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the Kingdom of Wakanda, the 2020 economic crisis has made a great impact on each city and its surrounding area. Cities have made a plan to build a fast train rail between them to boost the economy, but because of the insufficient funds, each city can only build a rail with one other city, and they want to do it together.Cities which are paired up in the plan will share the cost of building the rail between them, and one city might need to pay more than the other. Each city knows the estimated cost of building their part of the rail to every other city. One city can not have the same cost of building the rail with two different cities.If in a plan, there are two cities that are not connected, but the cost to create a rail between them is lower for each of them than the cost to build the rail with their current pairs, then that plan is not acceptable and the collaboration won't go on. Your task is to create a suitable plan for the cities (pairing of the cities) or say that such plan doesn't exist.InputFirst line contains one integer N \;(2 \leq N \leq 10^3)\, — the number of cities.Each of the next N lines contains N-1 integers A_{i,1}, A_{i,2}, ..., A_{i,i-1}, A_{i,i+1}, ..., A_{i,N-1}\; (1 \leq A_{i,j} \leq 10^9)\, — where A_{i,j} represents the cost for city i to build the rail to city j. Note that in each line A_{i,i} is skipped.OutputOutput should contain N integers O_{1}, O_{2}, ..., O_N, where O_i represents the city with which city i should build the rail with, or -1 if it is not possible to find the stable pairing.ExamplesInput 4 35 19 20 76 14 75 23 43 78 14 76 98 Output 3 4 1 2 Input 4 2 5 8 7 1 12 4 6 7 8 4 5 Output -1
4 35 19 20 76 14 75 23 43 78 14 76 98
3 4 1 2
1 second
256 megabytes
['*3500']
F. Boring Queriestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYura owns a quite ordinary and boring array a of length n. You think there is nothing more boring than that, but Vladik doesn't agree!In order to make Yura's array even more boring, Vladik makes q boring queries. Each query consists of two integers x and y. Before answering a query, the bounds l and r for this query are calculated: l = (last + x) \bmod n + 1, r = (last + y) \bmod n + 1, where last is the answer on the previous query (zero initially), and \bmod is the remainder operation. Whenever l > r, they are swapped.After Vladik computes l and r for a query, he is to compute the least common multiple (LCM) on the segment [l; r] of the initial array a modulo 10^9 + 7. LCM of a multiset of integers is the smallest positive integer that is divisible by all the elements of the multiset. The obtained LCM is the answer for this query.Help Vladik and compute the answer for each query!InputThe first line contains a single integer n (1 \le n \le 10^5) — the length of the array.The second line contains n integers a_i (1 \le a_i \le 2 \cdot 10^5) — the elements of the array.The third line contains a single integer q (1 \le q \le 10^5) — the number of queries.The next q lines contain two integers x and y each (1 \le x, y \le n) — the description of the corresponding query.OutputPrint q integers — the answers for the queries.ExampleInput 3 2 3 5 4 1 3 3 3 2 3 2 3 Output 6 2 15 30 NoteConsider the example: boundaries for first query are (0 + 1) \bmod 3 + 1 = 2 and (0 + 3) \bmod 3 + 1 = 1. LCM for segment [1, 2] is equal to 6; boundaries for second query are (6 + 3) \bmod 3 + 1 = 1 and (6 + 3) \bmod 3 + 1 = 1. LCM for segment [1, 1] is equal to 2; boundaries for third query are (2 + 2) \bmod 3 + 1 = 2 and (2 + 3) \bmod 3 + 1 = 3. LCM for segment [2, 3] is equal to 15; boundaries for fourth query are (15 + 2) \bmod 3 + 1 = 3 and (15 + 3) \bmod 3 + 1 = 1. LCM for segment [1, 3] is equal to 30.
3 2 3 5 4 1 3 3 3 2 3 2 3
6 2 15 30
3 seconds
512 megabytes
['data structures', 'math', 'number theory', '*2700']
E. Minlexestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSome time ago Lesha found an entertaining string s consisting of lowercase English letters. Lesha immediately developed an unique algorithm for this string and shared it with you. The algorithm is as follows.Lesha chooses an arbitrary (possibly zero) number of pairs on positions (i, i + 1) in such a way that the following conditions are satisfied: for each pair (i, i + 1) the inequality 0 \le i < |s| - 1 holds; for each pair (i, i + 1) the equality s_i = s_{i + 1} holds; there is no index that is contained in more than one pair. After that Lesha removes all characters on indexes contained in these pairs and the algorithm is over. Lesha is interested in the lexicographically smallest strings he can obtain by applying the algorithm to the suffixes of the given string.InputThe only line contains the string s (1 \le |s| \le 10^5) — the initial string consisting of lowercase English letters only.OutputIn |s| lines print the lengths of the answers and the answers themselves, starting with the answer for the longest suffix. The output can be large, so, when some answer is longer than 10 characters, instead print the first 5 characters, then "...", then the last 2 characters of the answer.ExamplesInput abcdd Output 3 abc 2 bc 1 c 0 1 d Input abbcdddeaaffdfouurtytwoo Output 18 abbcd...tw 17 bbcdd...tw 16 bcddd...tw 15 cddde...tw 14 dddea...tw 13 ddeaa...tw 12 deaad...tw 11 eaadf...tw 10 aadfortytw 9 adfortytw 8 dfortytw 9 fdfortytw 8 dfortytw 7 fortytw 6 ortytw 5 rtytw 6 urtytw 5 rtytw 4 tytw 3 ytw 2 tw 1 w 0 1 o NoteConsider the first example. The longest suffix is the whole string "abcdd". Choosing one pair (4, 5), Lesha obtains "abc". The next longest suffix is "bcdd". Choosing one pair (3, 4), we obtain "bc". The next longest suffix is "cdd". Choosing one pair (2, 3), we obtain "c". The next longest suffix is "dd". Choosing one pair (1, 2), we obtain "" (an empty string). The last suffix is the string "d". No pair can be chosen, so the answer is "d". In the second example, for the longest suffix "abbcdddeaaffdfouurtytwoo" choose three pairs (11, 12), (16, 17), (23, 24) and we obtain "abbcdddeaadfortytw"
abcdd
3 abc 2 bc 1 c 0 1 d
1 second
256 megabytes
['dp', 'greedy', 'implementation', 'strings', '*2700']
D. Returning Hometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city.Let's represent the city as an area of n \times n square blocks. Yura needs to move from the block with coordinates (s_x,s_y) to the block with coordinates (f_x,f_y). In one minute Yura can move to any neighboring by side block; in other words, he can move in four directions. Also, there are m instant-movement locations in the city. Their coordinates are known to you and Yura. Yura can move to an instant-movement location in no time if he is located in a block with the same coordinate x or with the same coordinate y as the location.Help Yura to find the smallest time needed to get home.InputThe first line contains two integers n and m — the size of the city and the number of instant-movement locations (1 \le n \le 10^9, 0 \le m \le 10^5).The next line contains four integers s_x s_y f_x f_y — the coordinates of Yura's initial position and the coordinates of his home ( 1 \le s_x, s_y, f_x, f_y \le n).Each of the next m lines contains two integers x_i y_i — coordinates of the i-th instant-movement location (1 \le x_i, y_i \le n).OutputIn the only line print the minimum time required to get home.ExamplesInput 5 3 1 1 5 5 1 2 4 1 3 3 Output 5 Input 84 5 67 59 41 2 39 56 7 2 15 3 74 18 22 7 Output 42 NoteIn the first example Yura needs to reach (5, 5) from (1, 1). He can do that in 5 minutes by first using the second instant-movement location (because its y coordinate is equal to Yura's y coordinate), and then walking (4, 1) \to (4, 2) \to (4, 3) \to (5, 3) \to (5, 4) \to (5, 5).
5 3 1 1 5 5 1 2 4 1 3 3
5
2 seconds
256 megabytes
['graphs', 'shortest paths', 'sortings', '*2300']
C. Bargaintime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSometimes it is not easy to come to an agreement in a bargain. Right now Sasha and Vova can't come to an agreement: Sasha names a price as high as possible, then Vova wants to remove as many digits from the price as possible. In more details, Sasha names some integer price n, Vova removes a non-empty substring of (consecutive) digits from the price, the remaining digits close the gap, and the resulting integer is the price.For example, is Sasha names 1213121, Vova can remove the substring 1312, and the result is 121.It is allowed for result to contain leading zeros. If Vova removes all digits, the price is considered to be 0.Sasha wants to come up with some constraints so that Vova can't just remove all digits, but he needs some arguments supporting the constraints. To start with, he wants to compute the sum of all possible resulting prices after Vova's move.Help Sasha to compute this sum. Since the answer can be very large, print it modulo 10^9 + 7.InputThe first and only line contains a single integer n (1 \le n < 10^{10^5}).OutputIn the only line print the required sum modulo 10^9 + 7.ExamplesInput 107 Output 42 Input 100500100500 Output 428101984 NoteConsider the first example.Vova can choose to remove 1, 0, 7, 10, 07, or 107. The results are 07, 17, 10, 7, 1, 0. Their sum is 42.
107
42
1 second
256 megabytes
['combinatorics', 'dp', 'math', '*1700']
B. Nice Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA matrix of size n \times m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a_1, a_2, \dots , a_k) is a palindrome, if for any integer i (1 \le i \le k) the equality a_i = a_{k - i + 1} holds.Sasha owns a matrix a of size n \times m. In one operation he can increase or decrease any number in the matrix by one. Sasha wants to make the matrix nice. He is interested what is the minimum number of operations he needs.Help him!InputThe first line contains a single integer t — the number of test cases (1 \le t \le 10). The t tests follow.The first line of each test contains two integers n and m (1 \le n, m \le 100) — the size of the matrix.Each of the next n lines contains m integers a_{i, j} (0 \le a_{i, j} \le 10^9) — the elements of the matrix.OutputFor each test output the smallest number of operations required to make the matrix nice.ExampleInput 2 4 2 4 2 2 4 4 2 2 4 3 4 1 2 3 4 5 6 7 8 9 10 11 18 Output 8 42 NoteIn the first test case we can, for example, obtain the following nice matrix in 8 operations:2 24 44 42 2In the second test case we can, for example, obtain the following nice matrix in 42 operations:5 6 6 56 6 6 65 6 6 5
2 4 2 4 2 2 4 4 2 2 4 3 4 1 2 3 4 5 6 7 8 9 10 11 18
8 42
1 second
256 megabytes
['greedy', 'implementation', 'math', '*1300']
A. Fencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths a, b, and c. Now he needs to find out some possible integer length d of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to a, b, c, and d. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.InputThe first line contains a single integer t — the number of test cases (1 \le t \le 1000). The next t lines describe the test cases.Each line contains three integers a, b, and c — the lengths of the three fence segments (1 \le a, b, c \le 10^9).OutputFor each test case print a single integer d — the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.ExampleInput 2 1 2 3 12 34 56 Output 4 42 NoteWe can build a quadrilateral with sides 1, 2, 3, 4.We can build a quadrilateral with sides 12, 34, 56, 42.
2 1 2 3 12 34 56
4 42
1 second
256 megabytes
['geometry', 'math', '*800']
E. Swedish Heroestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile playing yet another strategy game, Mans has recruited n Swedish heroes, whose powers which can be represented as an array a.Unfortunately, not all of those mighty heroes were created as capable as he wanted, so that he decided to do something about it. In order to accomplish his goal, he can pick two consecutive heroes, with powers a_i and a_{i+1}, remove them and insert a hero with power -(a_i+a_{i+1}) back in the same position. For example if the array contains the elements [5, 6, 7, 8], he can pick 6 and 7 and get [5, -(6+7), 8] = [5, -13, 8].After he will perform this operation n-1 times, Mans will end up having only one hero. He wants his power to be as big as possible. What's the largest possible power he can achieve?InputThe first line contains a single integer n (1 \le n \le 200000).The second line contains n integers a_1, a_2, \ldots, a_n (-10^9 \le a_i \le 10^9) — powers of the heroes.OutputPrint the largest possible power he can achieve after n-1 operations.ExamplesInput 4 5 6 7 8 Output 26 Input 5 4 -5 9 -2 1 Output 15 NoteSuitable list of operations for the first sample:[5, 6, 7, 8] \rightarrow [-11, 7, 8] \rightarrow [-11, -15] \rightarrow [26]
4 5 6 7 8
26
2 seconds
256 megabytes
['brute force', 'dp', 'implementation', '*2700']
D. Hexagonstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLindsey Buckingham told Stevie Nicks "Go your own way". Nicks is now sad and wants to go away as quickly as possible, but she lives in a 2D hexagonal world.Consider a hexagonal tiling of the plane as on the picture below. Nicks wishes to go from the cell marked (0, 0) to a certain cell given by the coordinates. She may go from a hexagon to any of its six neighbors you want, but there is a cost associated with each of them. The costs depend only on the direction in which you travel. Going from (0, 0) to (1, 1) will take the exact same cost as going from (-2, -1) to (-1, 0). The costs are given in the input in the order c_1, c_2, c_3, c_4, c_5, c_6 as in the picture below. Print the smallest cost of a path from the origin which has coordinates (0, 0) to the given cell.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^{4}). Description of the test cases follows.The first line of each test case contains two integers x and y (-10^{9} \le x, y \le 10^{9}) representing the coordinates of the target hexagon.The second line of each test case contains six integers c_1, c_2, c_3, c_4, c_5, c_6 (1 \le c_1, c_2, c_3, c_4, c_5, c_6 \le 10^{9}) representing the six costs of the making one step in a particular direction (refer to the picture above to see which edge is for each value).OutputFor each testcase output the smallest cost of a path from the origin to the given cell.ExampleInput 2 -3 1 1 3 5 7 9 11 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 Output 18 1000000000000000000 NoteThe picture below shows the solution for the first sample. The cost 18 is reached by taking c_3 3 times and c_2 once, amounting to 5+5+5+3=18.
2 -3 1 1 3 5 7 9 11 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000
18 1000000000000000000
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'greedy', 'implementation', 'math', 'shortest paths', '*1900']
C. Palindromifiertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRingo found a string s of length n in his yellow submarine. The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string s into a palindrome by applying two types of operations to the string. The first operation allows him to choose i (2 \le i \le n-1) and to append the substring s_2s_3 \ldots s_i (i - 1 characters) reversed to the front of s.The second operation allows him to choose i (2 \le i \le n-1) and to append the substring s_i s_{i + 1}\ldots s_{n - 1} (n - i characters) reversed to the end of s.Note that characters in the string in this problem are indexed from 1.For example suppose s=abcdef. If he performs the first operation with i=3 then he appends cb to the front of s and the result will be cbabcdef. Performing the second operation on the resulted string with i=5 will yield cbabcdefedc.Your task is to help Ringo make the entire string a palindrome by applying any of the two operations (in total) at most 30 times. The length of the resulting palindrome must not exceed 10^6It is guaranteed that under these constraints there always is a solution. Also note you do not have to minimize neither the number of operations applied, nor the length of the resulting string, but they have to fit into the constraints.InputThe only line contains the string S (3 \le |s| \le 10^5) of lowercase letters from the English alphabet.OutputThe first line should contain k (0\le k \le 30)  — the number of operations performed.Each of the following k lines should describe an operation in form L i or R i. L represents the first operation, R represents the second operation, i represents the index chosen.The length of the resulting palindrome must not exceed 10^6.ExamplesInput abac Output 2 R 2 R 5 Input acccc Output 2 L 4 L 2 Input hannah Output 0NoteFor the first example the following operations are performed:abac \to abacab \to abacabaThe second sample performs the following operations: acccc \to cccacccc \to ccccaccccThe third example is already a palindrome so no operations are required.
abac
2 R 2 R 5
1 second
256 megabytes
['constructive algorithms', 'strings', '*1400']
B. Putting Bricks in the Walltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size n\times n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it.Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'.For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n).We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 50). Description of the test cases follows.The first line of each test case contains one integers n (3 \le n \le 200).The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'.The sum of values of n doesn't exceed 200.OutputFor each test case output on the first line an integer c (0 \le c \le 2)  — the number of inverted cells.In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n).ExampleInput 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F
1 3 4 2 1 2 2 1 0
1 second
256 megabytes
['constructive algorithms', 'implementation', '*1100']
A. XORwicetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.Tzuyu gave Sana two integers a and b and a really important quest.In order to complete the quest, Sana has to output the smallest possible value of (a \oplus x) + (b \oplus x) for any given x, where \oplus denotes the bitwise XOR operation. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^{4}). Description of the test cases follows.The only line of each test case contains two integers a and b (1 \le a, b \le 10^{9}).OutputFor each testcase, output the smallest possible value of the given expression.ExampleInput 6 6 12 4 9 59 832 28 14 4925 2912 1 1 Output 10 13 891 18 6237 0 NoteFor the first test case Sana can choose x=4 and the value will be (6 \oplus 4) + (12 \oplus 4) = 2 + 8 = 10. It can be shown that this is the smallest possible value.
6 6 12 4 9 59 832 28 14 4925 2912 1 1
10 13 891 18 6237 0
1 second
256 megabytes
['bitmasks', 'greedy', 'math', '*800']
E. Battle Lemmingstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA lighthouse keeper Peter commands an army of n battle lemmings. He ordered his army to stand in a line and numbered the lemmings from 1 to n from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield.The more protected Peter's army is, the better. To calculate the protection of the army, he finds the number of protected pairs of lemmings, that is such pairs that both lemmings in the pair don't hold a shield, but there is a lemming with a shield between them.Now it's time to prepare for defence and increase the protection of the army. To do this, Peter can give orders. He chooses a lemming with a shield and gives him one of the two orders: give the shield to the left neighbor if it exists and doesn't have a shield; give the shield to the right neighbor if it exists and doesn't have a shield. In one second Peter can give exactly one order.It's not clear how much time Peter has before the defence. So he decided to determine the maximal value of army protection for each k from 0 to \frac{n(n-1)}2, if he gives no more that k orders. Help Peter to calculate it!InputFirst line contains a single integer n (1 \le n \le 80), the number of lemmings in Peter's army.Second line contains n integers a_i (0 \le a_i \le 1). If a_i = 1, then the i-th lemming has a shield, otherwise a_i = 0.OutputPrint \frac{n(n-1)}2 + 1 numbers, the greatest possible protection after no more than 0, 1, \dots, \frac{n(n-1)}2 orders.ExamplesInput 5 1 0 0 0 1 Output 0 2 3 3 3 3 3 3 3 3 3 Input 12 0 0 0 0 1 1 1 1 0 1 1 0 Output 9 12 13 14 14 14 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 NoteConsider the first example.The protection is initially equal to zero, because for each pair of lemmings without shields there is no lemmings with shield.In one second Peter can order the first lemming give his shield to the right neighbor. In this case, the protection is two, as there are two protected pairs of lemmings, (1, 3) and (1, 4).In two seconds Peter can act in the following way. First, he orders the fifth lemming to give a shield to the left neighbor. Then, he orders the first lemming to give a shield to the right neighbor. In this case Peter has three protected pairs of lemmings — (1, 3), (1, 5) and (3, 5).You can make sure that it's impossible to give orders in such a way that the protection becomes greater than three.
5 1 0 0 0 1
0 2 3 3 3 3 3 3 3 3 3
2 seconds
512 megabytes
['dp', 'greedy', '*2500']
D. Rescue Nibel!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOri and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened.Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional defence for the door.There are n lamps with Spirit Tree's light. Sein knows the time of turning on and off for the i-th lamp — l_i and r_i respectively. To open the door you have to choose k lamps in such a way that there will be a moment of time when they all will be turned on.While Sein decides which of the k lamps to pick, Ori is interested: how many ways there are to pick such k lamps that the door will open? It may happen that Sein may be wrong and there are no such k lamps. The answer might be large, so print it modulo 998\,244\,353.InputFirst line contains two integers n and k (1 \le n \le 3 \cdot 10^5, 1 \le k \le n) — total number of lamps and the number of lamps that must be turned on simultaneously.Next n lines contain two integers l_i ans r_i (1 \le l_i \le r_i \le 10^9) — period of time when i-th lamp is turned on.OutputPrint one integer — the answer to the task modulo 998\,244\,353.ExamplesInput 7 3 1 7 3 8 4 5 6 7 1 3 5 10 8 9 Output 9Input 3 1 1 1 2 2 3 3 Output 3Input 3 2 1 1 2 2 3 3 Output 0Input 3 3 1 3 2 3 3 3 Output 1Input 5 2 1 3 2 4 3 5 4 6 5 7 Output 7NoteIn first test case there are nine sets of k lamps: (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 3, 6), (1, 4, 6), (2, 3, 6), (2, 4, 6), (2, 6, 7).In second test case k=1, so the answer is 3.In third test case there are no such pairs of lamps.In forth test case all lamps are turned on in a time 3, so the answer is 1.In fifth test case there are seven sets of k lamps: (1, 2), (1, 3), (2, 3), (2, 4), (3, 4), (3, 5), (4, 5).
7 3 1 7 3 8 4 5 6 7 1 3 5 10 8 9
9
2 seconds
256 megabytes
['combinatorics', 'data structures', 'sortings', '*1800']
C2. Pokémon Army (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 \le b_1 < b_2 < \dots < b_k \le n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, \dots, a_{b_k}.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots.Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!InputEach test contains multiple test cases.The first line contains one positive integer t (1 \le t \le 10^3) denoting the number of test cases. Description of the test cases follows.The first line of each test case contains two integers n and q (1 \le n \le 3 \cdot 10^5, 0 \le q \le 3 \cdot 10^5) denoting the number of pokémon and number of operations respectively.The second line contains n distinct positive integers a_1, a_2, \dots, a_n (1 \le a_i \le n) denoting the strengths of the pokémon.i-th of the last q lines contains two positive integers l_i and r_i (1 \le l_i \le r_i \le n) denoting the indices of pokémon that were swapped in the i-th operation.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5, and the sum of q over all test cases does not exceed 3 \cdot 10^5. OutputFor each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.ExampleInput 3 3 1 1 3 2 1 2 2 2 1 2 1 2 1 2 7 5 1 2 5 4 3 6 7 1 2 6 7 3 4 1 2 2 3 Output 3 4 2 2 2 9 10 10 10 9 11 NoteLet's look at the third test case:Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
3 3 1 1 3 2 1 2 2 2 1 2 1 2 1 2 7 5 1 2 5 4 3 6 7 1 2 6 7 3 4 1 2 2 3
3 4 2 2 2 9 10 10 10 9 11
2 seconds
256 megabytes
['data structures', 'divide and conquer', 'dp', 'greedy', 'implementation', '*2100']
C1. Pokémon Army (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 \le b_1 < b_2 < \dots < b_k \le n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, \dots, a_{b_k}.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots.Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.Note: q=0 in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!InputEach test contains multiple test cases.The first line contains one positive integer t (1 \le t \le 10^3) denoting the number of test cases. Description of the test cases follows.The first line of each test case contains two integers n and q (1 \le n \le 3 \cdot 10^5, q = 0) denoting the number of pokémon and number of operations respectively.The second line contains n distinct positive integers a_1, a_2, \dots, a_n (1 \le a_i \le n) denoting the strengths of the pokémon.i-th of the last q lines contains two positive integers l_i and r_i (1 \le l_i \le r_i \le n) denoting the indices of pokémon that were swapped in the i-th operation.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5, and the sum of q over all test cases does not exceed 3 \cdot 10^5. OutputFor each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.ExampleInput 3 3 0 1 3 2 2 0 1 2 7 0 1 2 5 4 3 6 7 Output 3 2 9 NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5−3+7=9.
3 3 0 1 3 2 2 0 1 2 7 0 1 2 5 4 3 6 7
3 2 9
2 seconds
256 megabytes
['constructive algorithms', 'dp', 'greedy', '*1300']
B. Rock and Levertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer n, and an array a of positive integers. The task is to calculate the number of such pairs (i,j) that i<j and a_i \& a_j \ge a_i \oplus a_j, where \& denotes the bitwise AND operation, and \oplus denotes the bitwise XOR operation.Danik has solved this task. But can you solve it?InputEach test contains multiple test cases.The first line contains one positive integer t (1 \le t \le 10) denoting the number of test cases. Description of the test cases follows.The first line of each test case contains one positive integer n (1 \le n \le 10^5) — length of the array.The second line contains n positive integers a_i (1 \le a_i \le 10^9) — elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor every test case print one non-negative integer — the answer to the problem.ExampleInput 5 5 1 4 3 7 10 3 1 1 1 4 6 2 5 3 2 2 4 1 1 Output 1 3 2 0 0 NoteIn the first test case there is only one pair: (4,7): for it 4 \& 7 = 4, and 4 \oplus 7 = 3.In the second test case all pairs are good.In the third test case there are two pairs: (6,5) and (2,3).In the fourth test case there are no good pairs.
5 5 1 4 3 7 10 3 1 1 1 4 6 2 5 3 2 2 4 1 1
1 3 2 0 0
1 second
256 megabytes
['bitmasks', 'math', '*1200']
A. Cubes Sortingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got one hour! Solve it! Wheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absent — cubes.For completing the chamber Wheatley needs n cubes. i-th cube has a volume a_i.Wheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each i>1, a_{i-1} \le a_i must hold.To achieve his goal, Wheatley can exchange two neighbouring cubes. It means that for any i>1 you can exchange cubes on positions i-1 and i.But there is a problem: Wheatley is very impatient. If Wheatley needs more than \frac{n \cdot (n-1)}{2}-1 exchange operations, he won't do this boring work.Wheatly wants to know: can cubes be sorted under this conditions?InputEach test contains multiple test cases.The first line contains one positive integer t (1 \le t \le 1000), denoting the number of test cases. Description of the test cases follows.The first line of each test case contains one positive integer n (2 \le n \le 5 \cdot 10^4) — number of cubes.The second line contains n positive integers a_i (1 \le a_i \le 10^9) — volumes of cubes.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print a word in a single line: "YES" (without quotation marks) if the cubes can be sorted and "NO" (without quotation marks) otherwise.ExampleInput 3 5 5 3 2 1 4 6 2 2 2 2 2 2 2 2 1 Output YES YES NO NoteIn the first test case it is possible to sort all the cubes in 7 exchanges.In the second test case the cubes are already sorted.In the third test case we can make 0 exchanges, but the cubes are not sorted yet, so the answer is "NO".
3 5 5 3 2 1 4 6 2 2 2 2 2 2 2 2 1
YES YES NO
1 second
256 megabytes
['math', 'sortings', '*900']
F. Rain of Firetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n detachments on the surface, numbered from 1 to n, the i-th detachment is placed in a point with coordinates (x_i, y_i). All detachments are placed in different points.Brimstone should visit each detachment at least once. You can choose the detachment where Brimstone starts.To move from one detachment to another he should first choose one of four directions of movement (up, right, left or down) and then start moving with the constant speed of one unit interval in a second until he comes to a detachment. After he reaches an arbitrary detachment, he can repeat the same process.Each t seconds an orbital strike covers the whole surface, so at that moment Brimstone should be in a point where some detachment is located. He can stay with any detachment as long as needed.Brimstone is a good commander, that's why he can create at most one detachment and place it in any empty point with integer coordinates he wants before his trip. Keep in mind that Brimstone will need to visit this detachment, too.Help Brimstone and find such minimal t that it is possible to check each detachment. If there is no such t report about it.InputThe first line contains a single integer n (2 \le n \le 1000) — the number of detachments.In each of the next n lines there is a pair of integers x_i, y_i (|x_i|, |y_i| \le 10^9) — the coordinates of i-th detachment.It is guaranteed that all points are different.OutputOutput such minimal integer t that it is possible to check all the detachments adding at most one new detachment.If there is no such t, print -1.ExamplesInput 4 100 0 0 100 -100 0 0 -100 Output 100Input 7 0 2 1 0 -3 0 0 -2 -1 -1 -1 -3 -2 -3 Output -1Input 5 0 0 0 -1 3 0 -2 0 -2 1 Output 2Input 5 0 0 2 0 0 -1 -2 0 -2 1 Output 2NoteIn the first test it is possible to place a detachment in (0, 0), so that it is possible to check all the detachments for t = 100. It can be proven that it is impossible to check all detachments for t < 100; thus the answer is 100.In the second test, there is no such t that it is possible to check all detachments, even with adding at most one new detachment, so the answer is -1.In the third test, it is possible to place a detachment in (1, 0), so that Brimstone can check all the detachments for t = 2. It can be proven that it is the minimal such t.In the fourth test, there is no need to add any detachments, because the answer will not get better (t = 2). It can be proven that it is the minimal such t.
4 100 0 0 100 -100 0 0 -100
100
2 seconds
256 megabytes
['binary search', 'data structures', 'dfs and similar', 'dsu', 'graphs', 'implementation', '*2800']
E. Decryptiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn agent called Cypher is decrypting a message, that contains a composite number n. All divisors of n, which are greater than 1, are placed in a circle. Cypher can choose the initial order of numbers in the circle.In one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed.A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that.InputThe first line contains an integer t (1 \le t \le 100) — the number of test cases. Next t lines describe each test case.In a single line of each test case description, there is a single composite number n (4 \le n \le 10^9) — the number from the message.It's guaranteed that the total number of divisors of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case in the first line output the initial order of divisors, which are greater than 1, in the circle. In the second line output, the minimal number of moves needed to decrypt the message.If there are different possible orders with a correct answer, print any of them.ExampleInput 3 6 4 30 Output 2 3 6 1 2 4 0 2 30 6 3 15 5 10 0 NoteIn the first test case 6 has three divisors, which are greater than 1: 2, 3, 6. Regardless of the initial order, numbers 2 and 3 are adjacent, so it's needed to place their least common multiple between them. After that the circle becomes 2, 6, 3, 6, and every two adjacent numbers are not coprime.In the second test case 4 has two divisors greater than 1: 2, 4, and they are not coprime, so any initial order is correct, and it's not needed to place any least common multiples.In the third test case all divisors of 30 greater than 1 can be placed in some order so that there are no two adjacent numbers that are coprime.
3 6 4 30
2 3 6 1 2 4 0 2 30 6 3 15 5 10 0
1 second
256 megabytes
['constructive algorithms', 'implementation', 'math', 'number theory', '*2100']
D2. Sage's Birthday (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row and they are numbered from 1 to n from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of ice spheres in the shop.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the prices of ice spheres.OutputIn the first line print the maximum number of ice spheres that Sage can buy.In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.ExampleInput 7 1 3 2 2 4 5 4 Output 3 3 1 4 2 4 2 5 NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy 4 of them. If the spheres are placed in the order (3, 1, 4, 2, 4, 2, 5), then Sage will buy one sphere for 1 and two spheres for 2 each.
7 1 3 2 2 4 5 4
3 3 1 4 2 4 2 5
1 second
256 megabytes
['binary search', 'brute force', 'constructive algorithms', 'greedy', 'sortings', 'two pointers', '*1500']
D1. Sage's Birthday (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row and they are numbered from 1 to n from left to right. Each ice sphere has a positive integer price. In this version all prices are different.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of ice spheres in the shop.The second line contains n different integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the prices of ice spheres.OutputIn the first line print the maximum number of ice spheres that Sage can buy.In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.ExampleInput 5 1 2 3 4 5 Output 2 3 1 4 2 5 NoteIn the example it's not possible to place ice spheres in any order so that Sage would buy 3 of them. If the ice spheres are placed like this (3, 1, 4, 2, 5), then Sage will buy two spheres: one for 1 and one for 2, because they are cheap.
5 1 2 3 4 5
2 3 1 4 2 5
1 second
256 megabytes
['binary search', 'constructive algorithms', 'greedy', 'sortings', '*1000']
C. Killjoytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).Killjoy's account is already infected and has a rating equal to x. Its rating is constant. There are n accounts except hers, numbered from 1 to n. The i-th account's initial rating is a_i. Any infected account (initially the only infected account is Killjoy's) instantly infects any uninfected account if their ratings are equal. This can happen at the beginning (before any rating changes) and after each contest. If an account is infected, it can not be healed.Contests are regularly held on Codeforces. In each contest, any of these n accounts (including infected ones) can participate. Killjoy can't participate. After each contest ratings are changed this way: each participant's rating is changed by an integer, but the sum of all changes must be equal to zero. New ratings can be any integer.Find out the minimal number of contests needed to infect all accounts. You can choose which accounts will participate in each contest and how the ratings will change.It can be proven that all accounts can be infected in some finite number of contests.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases. The next 2t lines contain the descriptions of all test cases.The first line of each test case contains two integers n and x (2 \le n \le 10^3, -4000 \le x \le 4000) — the number of accounts on Codeforces and the rating of Killjoy's account.The second line of each test case contains n integers a_1, a_2, \dots, a_n (-4000 \le a_i \le 4000) — the ratings of other accounts.OutputFor each test case output the minimal number of contests needed to infect all accounts.ExampleInput 3 2 69 68 70 6 4 4 4 4 4 4 4 9 38 -21 83 50 -59 -77 15 -71 -78 20 Output 1 0 2 NoteIn the first test case it's possible to make all ratings equal to 69. First account's rating will increase by 1, and second account's rating will decrease by 1, so the sum of all changes will be equal to zero.In the second test case all accounts will be instantly infected, because all ratings (including Killjoy's account's rating) are equal to 4.
3 2 69 68 70 6 4 4 4 4 4 4 4 9 38 -21 83 50 -59 -77 15 -71 -78 20
1 0 2
1 second
256 megabytes
['greedy', 'implementation', 'math', '*1500']
B. Stairstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has n stairs, then it is made of n columns, the first column is 1 cell high, the second column is 2 cells high, \ldots, the n-th column if n cells high. The lowest cells of all stairs must be in the same row.A staircase with n stairs is called nice, if it may be covered by n disjoint squares made of cells. All squares should fully consist of cells of a staircase. This is how a nice covered staircase with 7 stairs looks like: Find out the maximal number of different nice staircases, that can be built, using no more than x cells, in total. No cell can be used more than once.InputThe first line contains a single integer t (1 \le t \le 1000)  — the number of test cases.The description of each test case contains a single integer x (1 \le x \le 10^{18})  — the number of cells for building staircases.OutputFor each test case output a single integer  — the number of different nice staircases, that can be built, using not more than x cells, in total.ExampleInput 4 1 8 6 1000000000000000000 Output 1 2 1 30 NoteIn the first test case, it is possible to build only one staircase, that consists of 1 stair. It's nice. That's why the answer is 1.In the second test case, it is possible to build two different nice staircases: one consists of 1 stair, and another consists of 3 stairs. This will cost 7 cells. In this case, there is one cell left, but it is not possible to use it for building any nice staircases, that have not been built yet. That's why the answer is 2.In the third test case, it is possible to build only one of two nice staircases: with 1 stair or with 3 stairs. In the first case, there will be 5 cells left, that may be used only to build a staircase with 2 stairs. This staircase is not nice, and Jett only builds nice staircases. That's why in this case the answer is 1. If Jett builds a staircase with 3 stairs, then there are no more cells left, so the answer is 1 again.
4 1 8 6 1000000000000000000
1 2 1 30
1 second
256 megabytes
['brute force', 'constructive algorithms', 'greedy', 'implementation', 'math', '*1200']
A. Digit Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEveryone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game...In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated from 1 to n from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with n digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of t matches find out, which agent wins, if both of them want to win and play optimally.InputFirst line of input contains an integer t (1 \le t \le 100)  — the number of matches.The first line of each match description contains an integer n (1 \le n \le 10^3)  — the number of digits of the generated number.The second line of each match description contains an n-digit positive integer without leading zeros.OutputFor each match print 1, if Raze wins, and 2, if Breach wins.ExampleInput 4 1 2 1 3 3 102 4 2069 Output 2 1 1 2 NoteIn the first match no one can make a turn, the only digit left is 2, it's even, so Breach wins.In the second match the only digit left is 3, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark 0. 1 will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark 9, and in the end there will be digit 0. It's even, so Breach wins.
4 1 2 1 3 3 102 4 2069
2 1 1 2
1 second
256 megabytes
['games', 'greedy', 'implementation', '*900']
G. Three Occurrencestime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. We denote the subarray a[l..r] as the array [a_l, a_{l + 1}, \dots, a_r] (1 \le l \le r \le n).A subarray is considered good if every integer that occurs in this subarray occurs there exactly thrice. For example, the array [1, 2, 2, 2, 1, 1, 2, 2, 2] has three good subarrays: a[1..6] = [1, 2, 2, 2, 1, 1]; a[2..4] = [2, 2, 2]; a[7..9] = [2, 2, 2]. Calculate the number of good subarrays of the given array a.InputThe first line contains one integer n (1 \le n \le 5 \cdot 10^5).The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le n).OutputPrint one integer — the number of good subarrays of the array a.ExamplesInput 9 1 2 2 2 1 1 2 2 2 Output 3 Input 10 1 2 3 4 1 2 3 1 2 3 Output 0 Input 12 1 2 3 4 3 4 2 1 3 4 2 1 Output 1
9 1 2 2 2 1 1 2 2 2
3
5 seconds
512 megabytes
['data structures', 'divide and conquer', 'hashing', 'two pointers', '*2500']
F. Equal Producttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given four integers n, m, l and r.Let's name a tuple (x_1, y_1, x_2, y_2) as good if: 1 \le x_1 < x_2 \le n; 1 \le y_2 < y_1 \le m; x_1 \cdot y_1 = x_2 \cdot y_2; l \le x_1 \cdot y_1 \le r. Find any good tuple for each x_1 from 1 to n inclusive.InputThe first line contains two integers n and m (1 \le n, m \le 2 \cdot 10^5).The second line contains two integers l and r (1 \le l \le r \le nm).OutputFor each x_1 from 1 to n inclusive: if there are no such four integers, print -1; otherwise, print four integers x_1, y_1, x_2 and y_2. If there are multiple answers, print any of them. ExamplesInput 8 20 91 100 Output -1 -1 -1 -1 -1 6 16 8 12 -1 -1 Input 4 5 1 10 Output 1 2 2 1 2 3 3 2 -1 -1 Input 5 12 16 60 Output -1 2 9 3 6 3 8 4 6 4 5 5 4 -1
8 20 91 100
-1 -1 -1 -1 -1 6 16 8 12 -1 -1
2 seconds
256 megabytes
['data structures', 'math', 'number theory', 'two pointers', '*3000']
E. Expected Damagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a computer game. In this game, you have to fight n monsters.To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes: if a = 0, then you receive d damage; if a > 0 and d \ge b, you receive no damage, but the current durability of the shield decreases by 1; if a > 0 and d < b, nothing happens. The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.InputThe first line contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the number of monsters and the number of shields, respectively.The second line contains n integers d_1, d_2, ..., d_n (1 \le d_i \le 10^9), where d_i is the strength of the i-th monster.Then m lines follow, the i-th of them contains two integers a_i and b_i (1 \le a_i \le n; 1 \le b_i \le 10^9) — the description of the i-th shield.OutputPrint m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction \dfrac{x}{y}, where y is coprime with 998244353. You have to print the value of x \cdot y^{-1} \bmod 998244353, where y^{-1} is the inverse element for y (y \cdot y^{-1} \bmod 998244353 = 1).ExamplesInput 3 2 1 3 1 2 1 1 2 Output 665496237 1 Input 3 3 4 2 6 3 1 1 2 2 3 Output 0 8 665496236
3 2 1 3 1 2 1 1 2
665496237 1
2 seconds
256 megabytes
['binary search', 'combinatorics', 'probabilities', '*2400']