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
F. Phoenix and Earthquaketime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPhoenix's homeland, the Fire Nation had n cities that were connected by m roads, but the roads were all destroyed by an earthquake. The Fire Nation wishes to repair n-1 of these roads so that all the cities are connected again. The i-th city has a_i tons of asphalt. x tons of asphalt are used up when repairing a road, and to repair a road between i and j, cities i and j must have at least x tons of asphalt between them. In other words, if city i had a_i tons of asphalt and city j had a_j tons, there would remain a_i+a_j-x tons after repairing the road between them. Asphalt can be moved between cities if the road between them is already repaired.Please determine if it is possible to connect all the cities, and if so, output any sequence of roads to repair.InputThe first line contains integers n, m, and x (2 \le n \le 3 \cdot 10^5; n-1 \le m \le 3 \cdot 10^5; 1 \le x \le 10^9) — the number of cities, number of roads, and amount of asphalt needed to repair one road.The next line contains n space-separated integer a_i (0 \le a_i \le 10^9) — the amount of asphalt initially at city i.The next m lines contains two integers x_i and y_i (x_i\ne y_i; 1 \le x_i, y_i \le n) — the cities connected by the i-th road. It is guaranteed that there is at most one road between each pair of cities, and that the city was originally connected before the earthquake.OutputIf it is not possible to connect all the cities, print NO. Otherwise, print YES followed by n-1 integers e_1, e_2, \dots, e_{n-1}, the order in which the roads should be repaired. e_i is the index of the i-th road to repair. If there are multiple solutions, print any.ExamplesInput 5 4 1 0 0 0 4 0 1 2 2 3 3 4 4 5 Output YES 3 2 1 4 Input 2 1 2 1 1 1 2 Output YES 1 Input 2 1 2 0 1 1 2 Output NO Input 5 6 5 0 9 4 0 10 1 2 1 3 2 3 3 4 1 4 4 5 Output YES 6 4 1 2 NoteIn the first example, the roads are repaired in the following order: Road 3 is repaired, connecting cities 3 and 4. City 4 originally had 4 tons of asphalt. After this road is constructed, 3 tons remain. Road 2 is repaired, connecting cities 2 and 3. The asphalt from city 4 can be transported to city 3 and used for the road. 2 tons remain. Road 1 is repaired, connecting cities 1 and 2. The asphalt is transported to city 2 and used for the road. 1 ton remain. Road 4 is repaired, connecting cities 4 and 5. The asphalt is transported to city 4 and used for the road. No asphalt remains. All the cities are now connected.In the second example, cities 1 and 2 use all their asphalt together to build the road. They each have 1 ton, so together they have 2 tons, which is enough.In the third example, there isn't enough asphalt to connect cities 1 and 2.
5 4 1 0 0 0 4 0 1 2 2 3 3 4 4 5
YES 3 2 1 4
3 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'trees', '*2600']
E. Phoenix and Computerstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n computers in a row, all originally off, and Phoenix wants to turn all of them on. He will manually turn on computers one at a time. At any point, if computer i-1 and computer i+1 are both on, computer i (2 \le i \le n-1) will turn on automatically if it is not already on. Note that Phoenix cannot manually turn on a computer that already turned on automatically.If we only consider the sequence of computers that Phoenix turns on manually, how many ways can he turn on all the computers? Two sequences are distinct if either the set of computers turned on manually is distinct, or the order of computers turned on manually is distinct. Since this number may be large, please print it modulo M.InputThe first line contains two integers n and M (3 \le n \le 400; 10^8 \le M \le 10^9) — the number of computers and the modulo. It is guaranteed that M is prime.OutputPrint one integer — the number of ways to turn on the computers modulo M.ExamplesInput 3 100000007 Output 6 Input 4 100000007 Output 20 Input 400 234567899 Output 20914007 NoteIn the first example, these are the 6 orders in which Phoenix can turn on all computers: [1,3]. Turn on computer 1, then 3. Note that computer 2 turns on automatically after computer 3 is turned on manually, but we only consider the sequence of computers that are turned on manually. [3,1]. Turn on computer 3, then 1. [1,2,3]. Turn on computer 1, 2, then 3. [2,1,3] [2,3,1] [3,2,1]
3 100000007
6
3 seconds
256 megabytes
['combinatorics', 'dp', 'math', '*2200']
D. Phoenix and Sockstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo satisfy his love of matching socks, Phoenix has brought his n socks (n is even) to the sock store. Each of his socks has a color c_i and is either a left sock or right sock. Phoenix can pay one dollar to the sock store to either: recolor a sock to any color c' (1 \le c' \le n) turn a left sock into a right sock turn a right sock into a left sock The sock store may perform each of these changes any number of times. Note that the color of a left sock doesn't change when it turns into a right sock, and vice versa. A matching pair of socks is a left and right sock with the same color. What is the minimum cost for Phoenix to make n/2 matching pairs? Each sock must be included in exactly one matching pair.InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains three integers n, l, and r (2 \le n \le 2 \cdot 10^5; n is even; 0 \le l, r \le n; l+r=n) — the total number of socks, and the number of left and right socks, respectively.The next line contains n integers c_i (1 \le c_i \le n) — the colors of the socks. The first l socks are left socks, while the next r socks are right socks.It is guaranteed that the sum of n across all the test cases will not exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the minimum cost for Phoenix to make n/2 matching pairs. Each sock must be included in exactly one matching pair.ExampleInput 4 6 3 3 1 2 3 2 2 2 6 2 4 1 1 2 2 2 2 6 5 1 6 5 4 3 2 1 4 0 4 4 4 4 3 Output 2 3 5 3 NoteIn the first test case, Phoenix can pay 2 dollars to: recolor sock 1 to color 2 recolor sock 3 to color 2 There are now 3 matching pairs. For example, pairs (1, 4), (2, 5), and (3, 6) are matching.In the second test case, Phoenix can pay 3 dollars to: turn sock 6 from a right sock to a left sock recolor sock 3 to color 1 recolor sock 4 to color 1 There are now 3 matching pairs. For example, pairs (1, 3), (2, 4), and (5, 6) are matching.
4 6 3 3 1 2 3 2 2 2 6 2 4 1 1 2 2 2 2 6 5 1 6 5 4 3 2 1 4 0 4 4 4 4 3
2 3 5 3
2 seconds
256 megabytes
['greedy', 'sortings', 'two pointers', '*1500']
C. Phoenix and Towerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPhoenix has n blocks of height h_1, h_2, \dots, h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x. Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains three integers n, m, and x (1 \le m \le n \le 10^5; 1 \le x \le 10^4) — the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively. The second line of each test case contains n space-separated integers (1 \le h_i \le x) — the heights of the blocks. It is guaranteed that the sum of n over all the test cases will not exceed 10^5.OutputFor each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, \dots, y_n, where y_i (1 \le y_i \le m) is the index of the tower that the i-th block is placed in.If there are multiple solutions, print any of them.ExampleInput 2 5 2 3 1 2 3 1 2 4 3 3 1 1 2 3 Output YES 1 1 1 2 2 YES 1 2 2 3NoteIn the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful.
2 5 2 3 1 2 3 1 2 4 3 3 1 1 2 3
YES 1 1 1 2 2 YES 1 2 2 3
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', '*1400']
B. Phoenix and Puzzletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPhoenix is playing with a new puzzle, which consists of n identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below. A puzzle piece The goal of the puzzle is to create a square using the n pieces. He is allowed to rotate and move the pieces around, but none of them can overlap and all n pieces must be used (of course, the square shouldn't contain any holes as well). Can he do it?InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains an integer n (1 \le n \le 10^9) — the number of puzzle pieces.OutputFor each test case, if Phoenix can create a square with the n puzzle pieces, print YES. Otherwise, print NO.ExampleInput 3 2 4 6 Output YES YES NO NoteFor n=2, Phoenix can create a square like this: For n=4, Phoenix can create a square like this: For n=6, it is impossible for Phoenix to create a square.
3 2 4 6
YES YES NO
2 seconds
256 megabytes
['brute force', 'geometry', 'math', 'number theory', '*1000']
A. Phoenix and Goldtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPhoenix has collected n pieces of gold, and he wants to weigh them together so he can feel rich. The i-th piece of gold has weight w_i. All weights are distinct. He will put his n pieces of gold on a weight scale, one piece at a time. The scale has an unusual defect: if the total weight on it is exactly x, it will explode. Can he put all n gold pieces onto the scale in some order, without the scale exploding during the process? If so, help him find some possible order. Formally, rearrange the array w so that for each i (1 \le i \le n), \sum\limits_{j = 1}^{i}w_j \ne x.InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains two integers n and x (1 \le n \le 100; 1 \le x \le 10^4) — the number of gold pieces that Phoenix has and the weight to avoid, respectively. The second line of each test case contains n space-separated integers (1 \le w_i \le 100) — the weights of the gold pieces. It is guaranteed that the weights are pairwise distinct.OutputFor each test case, if Phoenix cannot place all n pieces without the scale exploding, print NO. Otherwise, print YES followed by the rearranged array w. If there are multiple solutions, print any.ExampleInput 3 3 2 3 2 1 5 3 1 2 3 4 8 1 5 5 Output YES 3 2 1 YES 8 1 2 3 4 NO NoteIn the first test case, Phoenix puts the gold piece with weight 3 on the scale first, then the piece with weight 2, and finally the piece with weight 1. The total weight on the scale is 3, then 5, then 6. The scale does not explode because the total weight on the scale is never 2.In the second test case, the total weight on the scale is 8, 9, 11, 14, then 18. It is never 3.In the third test case, Phoenix must put the gold piece with weight 5 on the scale, and the scale will always explode.
3 3 2 3 2 1 5 3 1 2 3 4 8 1 5 5
YES 3 2 1 YES 8 1 2 3 4 NO
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', '*800']
E. Baby Ehab's Hyper Apartmenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Baby Ehab loves crawling around his apartment. It has n rooms numbered from 0 to n-1. For every pair of rooms, a and b, there's either a direct passage from room a to room b, or from room b to room a, but never both.Baby Ehab wants to go play with Baby Badawy. He wants to know if he could get to him. However, he doesn't know anything about his apartment except the number of rooms. He can ask the baby sitter two types of questions: is the passage between room a and room b directed from a to b or the other way around? does room x have a passage towards any of the rooms s_1, s_2, ..., s_k? He can ask at most 9n queries of the first type and at most 2n queries of the second type.After asking some questions, he wants to know for every pair of rooms a and b whether there's a path from a to b or not. A path from a to b is a sequence of passages that starts from room a and ends at room b.InputThe first line contains an integer t (1 \le t \le 30) — the number of test cases you need to solve.Then each test case starts with an integer n (4 \le n \le 100) — the number of rooms.The sum of n across the test cases doesn't exceed 500.OutputTo print the answer for a test case, print a line containing "3", followed by n lines, each containing a binary string of length n. The j-th character of the i-th string should be 1 if there's a path from room i to room j, and 0 if there isn't. The i-th character of the i-th string should be 1 for each valid i.After printing the answer, we will respond with a single integer. If it's 1, you printed a correct answer and should keep solving the test cases (or exit if it is the last one). If it's -1, you printed a wrong answer and should terminate to get Wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.InteractionTo ask a question of the first type, use the format: 1 a b (0 \le a,b \le n-1, a \neq b). we will answer with 1 if the passage is from a to b, and 0 if it is from b to a. you can ask at most 9n questions of this type in each test case. To ask a question of the second type, use the format: 2 x k s_1 s_2 ... s_k (0 \le x,s_i \le n-1, 0 \le k < n, x \neq s_i, elements of s are pairwise distinct). we will answer with 1 if there's a passage from x to any of the rooms in s, and 0 otherwise. you can ask at most 2n questions of this type in each test case. If we answer with -1 instead of a valid answer, that means you exceeded the number of queries or made an invalid query. Exit immediately after receiving -1 and you will see Wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.After printing a query, do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.Hacks:The first line should contain an integer t — the number of test cases.The first line of each test case should contain an integer n (4 \le n \le 100) — the number of rooms.Each of the next n lines should contain a binary string of length n. The j-th character of the i-th string should be 1 if there's a passage from room i to room j, 0 otherwise. The i-th character of the i-th string should be 0.ExampleInput 1 4 0 0 1 1 1Output 2 3 3 0 1 2 1 0 1 1 0 2 2 2 1 1 3 1111 1111 1111 0001NoteIn the given example:The first query asks whether there's a passage from room 3 to any of the other rooms.The second query asks about the direction of the passage between rooms 0 and 1.After a couple other queries, we concluded that you can go from any room to any other room except if you start at room 3, and you can't get out of this room, so we printed the matrix:1111111111110001The interactor answered with 1, telling us the answer is correct.
1 4 0 0 1 1 1
2 3 3 0 1 2 1 0 1 1 0 2 2 2 1 1 3 1111 1111 1111 0001
1 second
256 megabytes
['binary search', 'graphs', 'interactive', 'sortings', 'two pointers', '*2700']
D. Cut and Sticktime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBaby Ehab has a piece of Cut and Stick with an array a of length n written on it. He plans to grab a pair of scissors and do the following to it: pick a range (l, r) and cut out every element a_l, a_{l + 1}, ..., a_r in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence a_l, a_{l + 1}, ..., a_r into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length x, then no value occurs strictly more than \lceil \frac{x}{2} \rceil times in it.He didn't pick a range yet, so he's wondering: for q ranges (l, r), what is the minimum number of pieces he needs to partition the elements a_l, a_{l + 1}, ..., a_r into so that the partitioning is beautiful.A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly zero) elements. Note that it does not have to be contiguous.InputThe first line contains two integers n and q (1 \le n,q \le 3 \cdot 10^5) — the length of the array a and the number of queries.The second line contains n integers a_1, a_2, ..., a_{n} (1 \le a_i \le n) — the elements of the array a.Each of the next q lines contains two integers l and r (1 \le l \le r \le n) — the range of this query.OutputFor each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists.ExampleInput 6 2 1 3 2 3 3 2 1 6 2 5 Output 1 2 NoteIn the first query, you can just put the whole array in one subsequence, since its length is 6, and no value occurs more than 3 times in it.In the second query, the elements of the query range are [3,2,3,3]. You can't put them all in one subsequence, since its length is 4, and 3 occurs more than 2 times. However, you can partition it into two subsequences: [3] and [2,3,3].
6 2 1 3 2 3 3 2 1 6 2 5
1 2
3 seconds
512 megabytes
['binary search', 'data structures', 'greedy', 'implementation', 'sortings', '*2000']
C. Product 1 Modulo Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow you get Baby Ehab's first words: "Given an integer n, find the longest subsequence of [1,2, \ldots, n-1] whose product is 1 modulo n." Please solve the problem.A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly all) elements. The product of an empty subsequence is equal to 1.InputThe only line contains the integer n (2 \le n \le 10^5).OutputThe first line should contain a single integer, the length of the longest subsequence.The second line should contain the elements of the subsequence, in increasing order.If there are multiple solutions, you can print any.ExamplesInput 5 Output 3 1 2 3 Input 8 Output 4 1 3 5 7 NoteIn the first example, the product of the elements is 6 which is congruent to 1 modulo 5. The only longer subsequence is [1,2,3,4]. Its product is 24 which is congruent to 4 modulo 5. Hence, the answer is [1,2,3].
5
3 1 2 3
1 second
256 megabytes
['greedy', 'number theory', '*1600']
B. AND 0, Sum Bigtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBaby Badawy's first words were "AND 0 SUM BIG", so he decided to solve the following problem. Given two integers n and k, count the number of arrays of length n such that: all its elements are integers between 0 and 2^k-1 (inclusive); the bitwise AND of all its elements is 0; the sum of its elements is as large as possible. Since the answer can be very large, print its remainder when divided by 10^9+7.InputThe first line contains an integer t (1 \le t \le 10) — the number of test cases you need to solve.Each test case consists of a line containing two integers n and k (1 \le n \le 10^{5}, 1 \le k \le 20).OutputFor each test case, print the number of arrays satisfying the conditions. Since the answer can be very large, print its remainder when divided by 10^9+7.ExampleInput 2 2 2 100000 20 Output 4 226732710 NoteIn the first example, the 4 arrays are: [3,0], [0,3], [1,2], [2,1].
2 2 2 100000 20
4 226732710
2 seconds
256 megabytes
['bitmasks', 'combinatorics', 'math', '*1200']
A. Perfectly Imperfect Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array a of length n, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly zero) elements.InputThe first line contains an integer t (1 \le t \le 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 100) — the length of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_{n} (1 \le a_i \le 10^4) — the elements of the array a.OutputIf there's a subsequence of a whose product isn't a perfect square, print "YES". Otherwise, print "NO".ExampleInput 2 3 1 5 4 2 100 10000 Output YES NO NoteIn the first example, the product of the whole array (20) isn't a perfect square.In the second example, all subsequences have a perfect square product.
2 3 1 5 4 2 100 10000
YES NO
1 second
256 megabytes
['math', 'number theory', '*800']
F. Swapping Problemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given 2 arrays a and b, both of size n. You can swap two elements in b at most once (or leave it as it is), and you are required to minimize the value \sum_{i}|a_{i}-b_{i}|.Find the minimum possible value of this sum.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le {10^9}). The third line contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le {10^9}).OutputOutput the minimum value of \sum_{i}|a_{i}-b_{i}|.ExamplesInput 5 5 4 3 2 1 1 2 3 4 5 Output 4Input 2 1 3 4 2 Output 2NoteIn the first example, we can swap the first and fifth element in array b, so that it becomes [ 5, 2, 3, 4, 1 ].Therefore, the minimum possible value of this sum would be |5-5| + |4-2| + |3-3| + |2-4| + |1-1| = 4.In the second example, we can swap the first and second elements. So, our answer would be 2.
5 5 4 3 2 1 1 2 3 4 5
4
2 seconds
512 megabytes
['brute force', 'constructive algorithms', 'data structures', 'sortings', '*2500']
E. Cost Equilibriumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array is called beautiful if all the elements in the array are equal.You can transform an array using the following steps any number of times: Choose two indices i and j (1 \leq i,j \leq n), and an integer x (1 \leq x \leq a_i). Let i be the source index and j be the sink index. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively. The cost of this operation is x \cdot |j-i| . Now the i-th index can no longer be the sink and the j-th index can no longer be the source. The total cost of a transformation is the sum of all the costs in step 3.For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 \cdot |1-3| + 1 \cdot |1-4| = 5.An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.You are given an array a_1, a_2, \ldots, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7.InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the size of the array. The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9).OutputOutput a single integer — the number of balanced permutations modulo 10^9+7.ExamplesInput 3 1 2 3 Output 6Input 4 0 4 0 4 Output 2Input 5 0 11 12 13 14 Output 120NoteIn the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too.In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations.In the third example, all permutations are balanced.
3 1 2 3
6
1 second
256 megabytes
['combinatorics', 'constructive algorithms', 'math', 'sortings', '*2300']
D. GCD and MSTtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n (n \geq 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner: If gcd(a_i, a_{i+1}, a_{i+2}, \dots, a_{j}) = min(a_i, a_{i+1}, a_{i+2}, \dots, a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, \dots, a_j) between i and j. If i+1=j, then there is an edge of weight p between i and j. Here gcd(x, y, \ldots) denotes the greatest common divisor (GCD) of integers x, y, ....Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.The goal is to find the weight of the minimum spanning tree of this graph.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases.The first line of each test case contains two integers n (2 \leq n \leq 2 \cdot 10^5) and p (1 \leq p \leq 10^9) — the number of nodes and the parameter p.The second line contains n integers a_1, a_2, a_3, \dots, a_n (1 \leq a_i \leq 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5. OutputOutput t lines. For each test case print the weight of the corresponding graph.ExampleInput 4 2 5 10 10 2 5 3 3 4 5 5 2 4 9 8 8 5 3 3 6 10 100 9 15 Output 5 3 12 46 NoteHere are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):For test case 1 For test case 2 For test case 3 For test case 4
4 2 5 10 10 2 5 3 3 4 5 5 2 4 9 8 8 5 3 3 6 10 100 9 15
5 3 12 46
2 seconds
256 megabytes
['constructive algorithms', 'dsu', 'graphs', 'greedy', 'number theory', 'sortings', '*2000']
C. Add Onetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n. You have to apply m operations to it.In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.InputThe first line contains a single integer t (1 \le t \le 2 \cdot 10^5) — the number of test cases.The only line of each test case contains two integers n (1 \le n \le 10^9) and m (1 \le m \le 2 \cdot 10^5) — the initial number and the number of operations. OutputFor each test case output the length of the resulting number modulo 10^9+7.ExampleInput 5 1912 1 5 6 999 1 88 2 12 100 Output 5 2 6 4 2115 NoteFor the first test, 1912 becomes 21023 after 1 operation which is of length 5.For the second test, 5 becomes 21 after 6 operations which is of length 2.For the third test, 999 becomes 101010 after 1 operation which is of length 6.For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
5 1912 1 5 6 999 1 88 2 12 100
5 2 6 4 2115
1 second
256 megabytes
['dp', 'matrices', '*1600']
B. AND Sequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of n non-negative integers (n \ge 2) a_1, a_2, \dots, a_n is called good if for all i from 1 to n-1 the following condition holds true: a_1 \: \& \: a_2 \: \& \: \dots \: \& \: a_i = a_{i+1} \: \& \: a_{i+2} \: \& \: \dots \: \& \: a_n, where \& denotes the bitwise AND operation.You are given an array a of size n (n \geq 2). Find the number of permutations p of numbers ranging from 1 to n, for which the sequence a_{p_1}, a_{p_2}, ... ,a_{p_n} is good. Since this number can be large, output it modulo 10^9+7.InputThe first line contains a single integer t (1 \leq t \leq 10^4), denoting the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the size of the array.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — the elements of the array.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputOutput t lines, where the i-th line contains the number of good permutations in the i-th test case modulo 10^9 + 7.ExampleInput 4 3 1 1 1 5 1 2 3 4 5 5 0 2 0 3 0 4 1 3 5 1 Output 6 0 36 4 NoteIn the first test case, since all the numbers are equal, whatever permutation we take, the sequence is good. There are a total of 6 permutations possible with numbers from 1 to 3: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1].In the second test case, it can be proved that no permutation exists for which the sequence is good.In the third test case, there are a total of 36 permutations for which the sequence is good. One of them is the permutation [1,5,4,2,3] which results in the sequence s=[0,0,3,2,0]. This is a good sequence because s_1 = s_2 \: \& \: s_3 \: \& \: s_4 \: \& \: s_5 = 0, s_1 \: \& \: s_2 = s_3 \: \& \: s_4 \: \& \: s_5 = 0, s_1 \: \& \: s_2 \: \& \: s_3 = s_4 \: \& \: s_5 = 0, s_1 \: \& \: s_2 \: \& \: s_3 \: \& \: s_4 = s_5 = 0.
4 3 1 1 1 5 1 2 3 4 5 5 0 2 0 3 0 4 1 3 5 1
6 0 36 4
2 seconds
256 megabytes
['bitmasks', 'combinatorics', 'constructive algorithms', 'math', '*1400']
A. Array and Peakstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.Given two integers n and k, construct a permutation a of numbers from 1 to n which has exactly k peaks. An index i of an array a of size n is said to be a peak if 1 < i < n and a_i \gt a_{i-1} and a_i \gt a_{i+1}. If such permutation is not possible, then print -1.InputThe first line contains an integer t (1 \leq t \leq 100) — the number of test cases.Then t lines follow, each containing two space-separated integers n (1 \leq n \leq 100) and k (0 \leq k \leq n) — the length of an array and the required number of peaks.OutputOutput t lines. For each test case, if there is no permutation with given length and number of peaks, then print -1. Otherwise print a line containing n space-separated integers which forms a permutation of numbers from 1 to n and contains exactly k peaks. If there are multiple answers, print any.ExampleInput 5 1 0 5 2 6 6 2 1 6 1 Output 1 2 4 1 5 3 -1 -1 1 3 6 5 4 2 NoteIn the second test case of the example, we have array a = [2,4,1,5,3]. Here, indices i=2 and i=4 are the peaks of the array. This is because (a_{2} \gt a_{1} , a_{2} \gt a_{3}) and (a_{4} \gt a_{3}, a_{4} \gt a_{5}).
5 1 0 5 2 6 6 2 1 6 1
1 2 4 1 5 3 -1 -1 1 3 6 5 4 2
1 second
256 megabytes
['constructive algorithms', 'implementation', '*800']
G. Short Tasktime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet us denote by d(n) the sum of all divisors of the number n, i.e. d(n) = \sum\limits_{k | n} k.For example, d(1) = 1, d(4) = 1+2+4=7, d(6) = 1+2+3+6=12.For a given number c, find the minimum n such that d(n) = c.InputThe first line contains one integer t (1 \le t \le 10^4). Then t test cases follow.Each test case is characterized by one integer c (1 \le c \le 10^7).OutputFor each test case, output: "-1" if there is no such n that d(n) = c; n, otherwise. ExampleInput 12 1 2 3 4 5 6 7 8 9 10 39 691 Output 1 -1 2 3 -1 5 4 7 -1 -1 18 -1
12 1 2 3 4 5 6 7 8 9 10 39 691
1 -1 2 3 -1 5 4 7 -1 -1 18 -1
2 seconds
512 megabytes
['brute force', 'dp', 'math', 'number theory', '*1700']
F. Educationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is wondering about buying a new computer, which costs c tugriks. To do this, he wants to get a job as a programmer in a big company.There are n positions in Polycarp's company, numbered starting from one. An employee in position i earns a[i] tugriks every day. The higher the position number, the more tugriks the employee receives. Initially, Polycarp gets a position with the number 1 and has 0 tugriks.Each day Polycarp can do one of two things: If Polycarp is in the position of x, then he can earn a[x] tugriks. If Polycarp is in the position of x (x < n) and has at least b[x] tugriks, then he can spend b[x] tugriks on an online course and move to the position x+1. For example, if n=4, c=15, a=[1, 3, 10, 11], b=[1, 2, 7], then Polycarp can act like this: On the first day, Polycarp is in the 1-st position and earns 1 tugrik. Now he has 1 tugrik; On the second day, Polycarp is in the 1-st position and move to the 2-nd position. Now he has 0 tugriks; On the third day, Polycarp is in the 2-nd position and earns 3 tugriks. Now he has 3 tugriks; On the fourth day, Polycarp is in the 2-nd position and is transferred to the 3-rd position. Now he has 1 tugriks; On the fifth day, Polycarp is in the 3-rd position and earns 10 tugriks. Now he has 11 tugriks; On the sixth day, Polycarp is in the 3-rd position and earns 10 tugriks. Now he has 21 tugriks; Six days later, Polycarp can buy himself a new computer. Find the minimum number of days after which Polycarp will be able to buy himself a new computer.InputThe first line contains a single integer t (1 \le t \le 10^4). Then t test cases follow.The first line of each test case contains two integers n and c (2 \le n \le 2 \cdot 10^5, 1 \le c \le 10^9) — the number of positions in the company and the cost of a new computer.The second line of each test case contains n integers a_1 \le a_2 \le \ldots \le a_n (1 \le a_i \le 10^9).The third line of each test case contains n - 1 integer b_1, b_2, \ldots, b_{n-1} (1 \le b_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the minimum number of days after which Polycarp will be able to buy a new computer.ExampleInput 3 4 15 1 3 10 11 1 2 7 4 100 1 5 10 50 3 14 12 2 1000000000 1 1 1 Output 6 13 1000000000
3 4 15 1 3 10 11 1 2 7 4 100 1 5 10 50 3 14 12 2 1000000000 1 1 1
6 13 1000000000
2 seconds
256 megabytes
['brute force', 'dp', 'greedy', 'implementation', '*1900']
E. Permutation by Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation is a sequence of n integers from 1 to n, in which all the numbers occur exactly once. For example, [1], [3, 5, 2, 1, 4], [1, 3, 2] are permutations, and [2, 3, 2], [4, 3, 1], [0] are not.Polycarp was given four integers n, l, r (1 \le l \le r \le n) and s (1 \le s \le \frac{n (n+1)}{2}) and asked to find a permutation p of numbers from 1 to n that satisfies the following condition: s = p_l + p_{l+1} + \ldots + p_r. For example, for n=5, l=3, r=5, and s=8, the following permutations are suitable (not all options are listed): p = [3, 4, 5, 2, 1]; p = [5, 2, 4, 3, 1]; p = [5, 2, 1, 3, 4]. But, for example, there is no permutation suitable for the condition above for n=4, l=1, r=1, and s=5.Help Polycarp, for the given n, l, r, and s, find a permutation of numbers from 1 to n that fits the condition above. If there are several suitable permutations, print any of them.InputThe first line contains a single integer t (1 \le t \le 500). Then t test cases follow.Each test case consist of one line with four integers n (1 \le n \le 500), l (1 \le l \le n), r (l \le r \le n), s (1 \le s \le \frac{n (n+1)}{2}).It is guaranteed that the sum of n for all input data sets does not exceed 500.OutputFor each test case, output on a separate line: n integers — a permutation of length n that fits the condition above if such a permutation exists; -1, otherwise. If there are several suitable permutations, print any of them.ExampleInput 5 5 2 3 5 5 3 4 1 3 1 2 4 2 2 2 2 2 1 1 3 Output 1 2 3 4 5 -1 1 3 2 1 2 -1
5 5 2 3 5 5 3 4 1 3 1 2 4 2 2 2 2 2 1 1 3
1 2 3 4 5 -1 1 3 2 1 2 -1
2 seconds
256 megabytes
['brute force', 'greedy', 'math', '*1600']
D. Corrupted Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a number n and an array b_1, b_2, \ldots, b_{n+2}, obtained according to the following algorithm: some array a_1, a_2, \ldots, a_n was guessed; array a was written to array b, i.e. b_i = a_i (1 \le i \le n); The (n+1)-th element of the array b is the sum of the numbers in the array a, i.e. b_{n+1} = a_1+a_2+\ldots+a_n; The (n+2)-th element of the array b was written some number x (1 \le x \le 10^9), i.e. b_{n+2} = x; The array b was shuffled. For example, the array b=[2, 3, 7, 12 ,2] it could be obtained in the following ways: a=[2, 2, 3] and x=12; a=[3, 2, 7] and x=2. For the given array b, find any array a that could have been guessed initially.InputThe first line contains a single integer t (1 \le t \le 10^4). Then t test cases follow.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5).The second row of each test case contains n+2 integers b_1, b_2, \ldots, b_{n+2} (1 \le b_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output: "-1", if the array b could not be obtained from any array a; n integers a_1, a_2, \ldots, a_n, otherwise. If there are several arrays of a, you can output any.ExampleInput 4 3 2 3 7 12 2 4 9 1 7 1 6 5 5 18 2 2 3 2 9 2 3 2 6 9 2 1 Output 2 3 7 -1 2 2 2 3 9 1 2 6
4 3 2 3 7 12 2 4 9 1 7 1 6 5 5 18 2 2 3 2 9 2 3 2 6 9 2 1
2 3 7 -1 2 2 2 3 9 1 2 6
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', '*1200']
C. A-B Palindrometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string s by '0' or '1' so that the string becomes a palindrome and has exactly a characters '0' and exactly b characters '1'. Note that each of the characters '?' is replaced independently from the others.A string t of length n is called a palindrome if the equality t[i] = t[n-i+1] is true for all i (1 \le i \le n).For example, if s="01?????0", a=4 and b=4, then you can replace the characters '?' in the following ways: "01011010"; "01100110". For the given string s and the numbers a and b, replace all the characters with '?' in the string s by '0' or '1' so that the string becomes a palindrome and has exactly a characters '0' and exactly b characters '1'.InputThe first line contains a single integer t (1 \le t \le 10^4). Then t test cases follow.The first line of each test case contains two integers a and b (0 \le a, b \le 2 \cdot 10^5, a + b \ge 1).The second line of each test case contains the string s of length a+b, consisting of the characters '0', '1', and '?'.It is guaranteed that the sum of the string lengths of s over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output: "-1", if you can't replace all the characters '?' in the string s by '0' or '1' so that the string becomes a palindrome and that it contains exactly a characters '0' and exactly b characters '1'; the string that is obtained as a result of the replacement, otherwise. If there are several suitable ways to replace characters, you can output any.ExampleInput 9 4 4 01?????0 3 3 ?????? 1 0 ? 2 2 0101 2 2 01?0 0 1 0 0 3 1?1 2 2 ?00? 4 3 ??010?0 Output 01011010 -1 0 -1 0110 -1 111 1001 0101010
9 4 4 01?????0 3 3 ?????? 1 0 ? 2 2 0101 2 2 01?0 0 1 0 0 3 1?1 2 2 ?00? 4 3 ??010?0
01011010 -1 0 -1 0110 -1 111 1001 0101010
2 seconds
256 megabytes
['constructive algorithms', 'implementation', 'strings', '*1200']
B. Almost Rectangletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a square field of size n \times n in which two cells are marked. These cells can be in the same row or column.You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes.For example, if n=4 and a rectangular field looks like this (there are asterisks in the marked cells): \begin{matrix} . & . & * & . \\ . & . & . & . \\ * & . & . & . \\ . & . & . & . \\ \end{matrix} Then you can mark two more cells as follows \begin{matrix} * & . & * & . \\ . & . & . & . \\ * & . & * & . \\ . & . & . & . \\ \end{matrix} If there are several possible solutions, then print any of them.InputThe first line contains a single integer t (1 \le t \le 400). Then t test cases follow.The first row of each test case contains a single integer n (2 \le n \le 400) — the number of rows and columns in the table.The following n lines each contain n characters '.' or '*' denoting empty and marked cells, respectively.It is guaranteed that the sums of n for all test cases do not exceed 400.It is guaranteed that there are exactly two asterisks on the field. They can be in the same row/column.It is guaranteed that the solution exists.OutputFor each test case, output n rows of n characters — a field with four asterisks marked corresponding to the statements. If there multiple correct answers, print any of them.ExampleInput 6 4 ..*. .... *... .... 2 *. .* 2 .* .* 3 *.* ... ... 5 ..... ..*.. ..... .*... ..... 4 .... .... *... *... Output *.*. .... *.*. .... ** ** ** ** *.* *.* ... ..... .**.. ..... .**.. ..... .... .... **.. **..
6 4 ..*. .... *... .... 2 *. .* 2 .* .* 3 *.* ... ... 5 ..... ..*.. ..... .*... ..... 4 .... .... *... *...
*.*. .... *.*. .... ** ** ** ** *.* *.* ... ..... .**.. ..... .**.. ..... .... .... **.. **..
2 seconds
256 megabytes
['implementation', '*800']
A. Spy Detected!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n (n \ge 3) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array [4, 11, 4, 4] all numbers except one are equal to 4).Print the index of the element that does not equal others. The numbers in the array are numbered from one.InputThe first line contains a single integer t (1 \le t \le 100). Then t test cases follow.The first line of each test case contains a single integer n (3 \le n \le 100) — the length of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 100).It is guaranteed that all the numbers except one in the a array are the same.OutputFor each test case, output a single integer — the index of the element that is not equal to others.ExampleInput 4 4 11 13 11 11 5 1 4 4 4 4 10 3 3 3 3 10 3 3 3 3 3 3 20 20 10 Output 2 1 5 3
4 4 11 13 11 11 5 1 4 4 4 4 10 3 3 3 3 10 3 3 3 3 3 3 20 20 10
2 1 5 3
2 seconds
256 megabytes
['brute force', 'implementation', '*800']
G. Chips on a Boardtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice and Bob have a rectangular board consisting of n rows and m columns. Each row contains exactly one chip.Alice and Bob play the following game. They choose two integers l and r such that 1 \le l \le r \le m and cut the board in such a way that only the part of it between column l and column r (inclusive) remains. So, all columns to the left of column l and all columns to the right of column r no longer belong to the board.After cutting the board, they move chips on the remaining part of the board (the part from column l to column r). They make alternating moves, and the player which cannot make a move loses the game. The first move is made by Alice, the second — by Bob, the third — by Alice, and so on. During their move, the player must choose one of the chips from the board and move it any positive number of cells to the left (so, if the chip was in column i, it can move to any column j < i, and the chips in the leftmost column cannot be chosen).Alice and Bob have q pairs of numbers L_i and R_i. For each such pair, they want to determine who will be the winner of the game if l = L_i and r = R_i. Note that these games should be considered independently (they don't affect the state of the board for the next games), and both Alice and Bob play optimally.InputThe first line contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the number of rows and columns on the board, respectively.The second line contains n integers c_1, c_2, \dots, c_n (1 \le c_i \le m), where c_i is the index of the column where the chip in the i-th row is located (so, the chip in the i-th row is in the c_i-th column).The third line contains one integer q (1 \le q \le 2 \cdot 10^5).Then q lines follow, the i-th of them contains two integers L_i and R_i (1 \le L_i \le R_i \le m).OutputPrint a string of q characters. The i-th character should be A if Alice wins the game with l = L_i and r = R_i, or B if Bob wins it.ExampleInput 8 10 1 3 3 7 4 2 6 9 7 2 3 1 3 1 4 1 10 5 10 8 10 9 10 Output BAAAAAB
8 10 1 3 3 7 4 2 6 9 7 2 3 1 3 1 4 1 10 5 10 8 10 9 10
BAAAAAB
5 seconds
512 megabytes
['bitmasks', 'brute force', 'data structures', 'dp', 'games', 'two pointers', '*2700']
F. Chainwordtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA chainword is a special type of crossword. As most of the crosswords do, it has cells that you put the letters in and some sort of hints to what these letters should be.The letter cells in a chainword are put in a single row. We will consider chainwords of length m in this task.A hint to a chainword is a sequence of segments such that the segments don't intersect with each other and cover all m letter cells. Each segment contains a description of the word in the corresponding cells.The twist is that there are actually two hints: one sequence is the row above the letter cells and the other sequence is the row below the letter cells. When the sequences are different, they provide a way to resolve the ambiguity in the answers.You are provided with a dictionary of n words, each word consists of lowercase Latin letters. All words are pairwise distinct.An instance of a chainword is the following triple: a string of m lowercase Latin letters; the first hint: a sequence of segments such that the letters that correspond to each segment spell a word from the dictionary; the second hint: another sequence of segments such that the letters that correspond to each segment spell a word from the dictionary. Note that the sequences of segments don't necessarily have to be distinct.Two instances of chainwords are considered different if they have different strings, different first hints or different second hints.Count the number of different instances of chainwords. Since the number might be pretty large, output it modulo 998\,244\,353.InputThe first line contains two integers n and m (1 \le n \le 8, 1 \le m \le 10^9) — the number of words in the dictionary and the number of letter cells.Each of the next n lines contains a word — a non-empty string of no more than 5 lowercase Latin letters. All words are pairwise distinct. OutputPrint a single integer — the number of different instances of chainwords of length m for the given dictionary modulo 998\,244\,353.ExamplesInput 3 5 ababa ab a Output 11 Input 2 4 ab cd Output 4 Input 5 100 a aa aaa aaaa aaaaa Output 142528942 NoteHere are all the instances of the valid chainwords for the first example: The red lines above the letters denote the segments of the first hint, the blue lines below the letters denote the segments of the second hint.In the second example the possible strings are: "abab", "abcd", "cdab" and "cdcd". All the hints are segments that cover the first two letters and the last two letters.
3 5 ababa ab a
11
3 seconds
256 megabytes
['brute force', 'data structures', 'dp', 'matrices', 'string suffix structures', 'strings', '*2700']
E. Colorings and Dominoestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have a large rectangular board which is divided into n \times m cells (the board has n rows and m columns). Each cell is either white or black.You paint each white cell either red or blue. Obviously, the number of different ways to paint them is 2^w, where w is the number of white cells.After painting the white cells of the board, you want to place the maximum number of dominoes on it, according to the following rules: each domino covers two adjacent cells; each cell is covered by at most one domino; if a domino is placed horizontally (it covers two adjacent cells in one of the rows), it should cover only red cells; if a domino is placed vertically (it covers two adjacent cells in one of the columns), it should cover only blue cells. Let the value of the board be the maximum number of dominoes you can place. Calculate the sum of values of the board over all 2^w possible ways to paint it. Since it can be huge, print it modulo 998\,244\,353.InputThe first line contains two integers n and m (1 \le n, m \le 3 \cdot 10^5; nm \le 3 \cdot 10^5) — the number of rows and columns, respectively.Then n lines follow, each line contains a string of m characters. The j-th character in the i-th string is * if the j-th cell in the i-th row is black; otherwise, that character is o.OutputPrint one integer — the sum of values of the board over all 2^w possible ways to paint it, taken modulo 998\,244\,353.ExamplesInput 3 4 **oo oo*o **oo Output 144 Input 3 4 **oo oo** **oo Output 48 Input 2 2 oo o* Output 4 Input 1 4 oooo Output 9
3 4 **oo oo*o **oo
144
3 seconds
512 megabytes
['combinatorics', 'dp', 'greedy', 'math', '*2100']
D. Min Cost Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define the cost of a string s as the number of index pairs i and j (1 \le i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost — find any of them.InputThe only line contains two integers n and k (1 \le n \le 2 \cdot 10^5; 1 \le k \le 26).OutputPrint the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings — print any of them.ExamplesInput 9 4 Output aabacadbb Input 5 1 Output aaaaaInput 10 26 Output codeforces
9 4
aabacadbb
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'graphs', 'greedy', 'strings', '*1600']
C. Yet Another Card Decktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a card deck of n cards, numbered from top to bottom, i. e. the top card has index 1 and bottom card — index n. Each card has its color: the i-th card has color a_i.You should process q queries. The j-th query is described by integer t_j. For each query you should: find the highest card in the deck with color t_j, i. e. the card with minimum index; print the position of the card you found; take the card and place it on top of the deck. InputThe first line contains two integers n and q (2 \le n \le 3 \cdot 10^5; 1 \le q \le 3 \cdot 10^5) — the number of cards in the deck and the number of queries.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 50) — the colors of cards.The third line contains q integers t_1, t_2, \dots, t_q (1 \le t_j \le 50) — the query colors. It's guaranteed that queries ask only colors that are present in the deck.OutputPrint q integers — the answers for each query.ExampleInput 7 5 2 1 1 4 3 3 1 3 2 1 1 4 Output 5 2 3 1 5 NoteDescription of the sample: the deck is [2, 1, 1, 4, \underline{3}, 3, 1] and the first card with color t_1 = 3 has position 5; the deck is [3, \underline{2}, 1, 1, 4, 3, 1] and the first card with color t_2 = 2 has position 2; the deck is [2, 3, \underline{1}, 1, 4, 3, 1] and the first card with color t_3 = 1 has position 3; the deck is [\underline{1}, 2, 3, 1, 4, 3, 1] and the first card with color t_4 = 1 has position 1; the deck is [1, 2, 3, 1, \underline{4}, 3, 1] and the first card with color t_5 = 4 has position 5.
7 5 2 1 1 4 3 3 1 3 2 1 1 4
5 2 3 1 5
2 seconds
256 megabytes
['brute force', 'data structures', 'implementation', 'trees', '*1100']
B. GCD Lengthtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a, b and c.Find two positive integers x and y (x > 0, y > 0) such that: the decimal representation of x without leading zeroes consists of a digits; the decimal representation of y without leading zeroes consists of b digits; the decimal representation of gcd(x, y) without leading zeroes consists of c digits. gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y.Output x and y. If there are multiple answers, output any of them.InputThe first line contains a single integer t (1 \le t \le 285) — the number of testcases.Each of the next t lines contains three integers a, b and c (1 \le a, b \le 9, 1 \le c \le min(a, b)) — the required lengths of the numbers.It can be shown that the answer exists for all testcases under the given constraints.Additional constraint on the input: all testcases are different.OutputFor each testcase print two positive integers — x and y (x > 0, y > 0) such that the decimal representation of x without leading zeroes consists of a digits; the decimal representation of y without leading zeroes consists of b digits; the decimal representation of gcd(x, y) without leading zeroes consists of c digits. ExampleInput 4 2 3 1 2 2 2 6 6 2 1 1 1 Output 11 492 13 26 140133 160776 1 1 NoteIn the example: gcd(11, 492) = 1 gcd(13, 26) = 13 gcd(140133, 160776) = 21 gcd(1, 1) = 1
4 2 3 1 2 2 2 6 6 2 1 1 1
11 492 13 26 140133 160776 1 1
2 seconds
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1100']
A. Review Sitetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press — upvote and downvote.However, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes.n reviewers enter the site one by one. Each reviewer is one of the following types: type 1: a reviewer has watched the movie, and they like it — they press the upvote button; type 2: a reviewer has watched the movie, and they dislike it — they press the downvote button; type 3: a reviewer hasn't watched the movie — they look at the current number of upvotes and downvotes of the movie on the server they are in and decide what button to press. If there are more downvotes than upvotes, then a reviewer downvotes the movie. Otherwise, they upvote the movie. Each reviewer votes on the movie exactly once.Since you have two servers, you can actually manipulate the votes so that your movie gets as many upvotes as possible. When a reviewer enters a site, you know their type, and you can send them either to the first server or to the second one.What is the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.Then the descriptions of t testcases follow.The first line of each testcase contains a single integer n (1 \le n \le 50) — the number of reviewers.The second line of each testcase contains n integers r_1, r_2, \dots, r_n (1 \le r_i \le 3) — the types of the reviewers in the same order they enter the site.OutputFor each testcase print a single integer — the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to.ExampleInput 4 1 2 3 1 2 3 5 1 1 1 1 1 3 3 3 2 Output 0 2 5 2 NoteIn the first testcase of the example you can send the only reviewer to either of the servers — they'll downvote anyway. The movie won't receive any upvotes.In the second testcase of the example you can send all reviewers to the first server: the first reviewer upvotes; the second reviewer downvotes; the last reviewer sees that the number of downvotes is not greater than the number of upvotes — upvote themselves. There are two upvotes in total. Alternatevely, you can send the first and the second reviewers to the first server and the last reviewer — to the second server: the first reviewer upvotes on the first server; the second reviewer downvotes on the first server; the last reviewer sees no upvotes or downvotes on the second server — upvote themselves.
4 1 2 3 1 2 3 5 1 1 1 1 1 3 3 3 2
0 2 5 2
2 seconds
256 megabytes
['greedy', '*800']
K. King's Tasktime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe brave Knight came to the King and asked permission to marry the princess. The King knew that the Knight was brave, but he also wanted to know if he was smart enough. So he asked him to solve the following task.There is a permutation p_i of numbers from 1 to 2n. You can make two types of operations. Swap p_1 and p_2, p_3 and p_4, ..., p_{2n-1} and p_{2n}. Swap p_1 and p_{n+1}, p_2 and p_{n+2}, ..., p_{n} and p_{2n}. The task is to find the minimal number of operations required to sort the given permutation.The Knight was not that smart actually, but quite charming, so the princess asks you to help him to solve the King's task.InputThe first line contains the integer n (1\le n\le 1000). The second line contains 2n integers p_i — the permutation of numbers from 1 to 2n.OutputPrint one integer — the minimal number of operations required to sort the permutation. If it is impossible to sort the permutation using these operations, print -1.ExamplesInput 3 6 3 2 5 4 1 Output 3 Input 2 3 4 2 1 Output -1 Input 4 1 2 3 4 5 6 7 8 Output 0 NoteIn the first example, you can sort the permutation in three operations: Make operation 1: 3, 6, 5, 2, 1, 4. Make operation 2: 2, 1, 4, 3, 6, 5. Make operation 1: 1, 2, 3, 4, 5, 6.
3 6 3 2 5 4 1
3
3 seconds
512 megabytes
['brute force', 'graphs', 'implementation', '*1200']
J. Japanese Gametime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputJoseph really likes the culture of Japan. Last year he learned Japanese traditional clothes and visual arts and now he is trying to find out the secret of the Japanese game called Nonogram.In the one-dimensional version of the game, there is a row of n empty cells, some of which are to be filled with a pen. There is a description of a solution called a profile — a sequence of positive integers denoting the lengths of consecutive sets of filled cells. For example, the profile of [4, 3, 1] means that there are sets of four, three, and one filled cell, in that order, with at least one empty cell between successive sets. A suitable solution for n = 12 and p = [4, 3, 1]. A wrong solution: the first four filled cells should be consecutive. A wrong solution: there should be at least one empty cell before the last filled cell. Joseph found out that for some numbers n and profiles p there are lots of ways to fill the cells to satisfy the profile. Now he is in the process of solving a nonogram consisting of n cells and a profile p. He has already created a mask of p — he has filled all the cells that must be filled in every solution of the nonogram. The mask for n = 12 and p = [4, 3, 1]: all the filled cells above are filled in every solution. After a break, he lost the source profile p. He only has n and the mask m. Help Joseph find any profile p' with the mask m or say that there is no such profile and Joseph has made a mistake.InputThe only line contains a string m — the mask of the source profile p. The length of m is n (1 \le n \le 100\,000). The string m consists of symbols # and _ — denoting filled and empty cells respectively.OutputIf there is no profile with the mask m, output the number -1. Otherwise, on the first line, output an integer k — the number of integers in the profile p'. On the second line, output k integers of the profile p'.ExamplesInput __#_____ Output 2 3 2 Input _# Output -1 Input ___ Output 0
__#_____
2 3 2
3 seconds
512 megabytes
['constructive algorithms', 'math', '*2700']
I. Is It Rated?time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe popular improv website Interpretation Impetus hosts regular improv contests and maintains a rating of the best performers. However, since improv can often go horribly wrong, the website is notorious for declaring improv contests unrated. It now holds a wager before each improv contest where the participants try to predict whether it will be rated or unrated, and they are now more popular than the improv itself.Izzy and n other participants take part in each wager. First, they each make their prediction, expressed as 1 ("rated") or 0 ("unrated"). Izzy always goes last, so she knows the predictions of the other participants when making her own. Then, the actual competition takes place and it is declared either rated or unrated.You need to write a program that will interactively play as Izzy. There will be m wagers held in 2021, and Izzy's goal is to have at most 1.3\cdot b + 100 wrong predictions after all those wagers, where b is the smallest number of wrong predictions that any other wager participant will have after all those wagers. The number b is not known in advance. Izzy also knows nothing about the other participants — they might somehow always guess correctly, or their predictions might be correlated. Izzy's predictions, though, do not affect the predictions of the other participants and the decision on the contest being rated or not — in other words, in each test case, your program always receives the same inputs, no matter what it outputs.InteractionFirst, a solution must read two integers n (1 \le n \le 1000) and m (1 \le m \le 10\,000). Then, the solution must process m wagers. For each of them, the solution must first read a string consisting of n 0s and 1s, in which the i-th character denotes the guess of the i-th participant. Then, the solution must print Izzy's guess as 0 or 1. Don't forget to flush the output after printing it! Then, the solution must read the actual outcome, also as 0 or 1, and then proceed to the next wager, if this wasn't the last one. Your solution will be considered correct if it makes at most 1.3\cdot b + 100 mistakes, where b is the smallest number of mistakes made by any other participant. Note that if a solution outputs anything except 0 or 1 for a wager, it will be considered incorrect even if it made no other mistakes. There are 200 test cases in this problem.ExampleInput 3 4 000 1 100 1 001 0 111 1 Output 0 0 1 1 NoteIn the example, the participants made 1, 2, and 3 mistakes respectively, therefore b=1 (the smallest of these numbers). Izzy made 3 mistakes, which were not more than 1.3\cdot b + 100=101.3, so these outputs are good enough to pass this test case (as are any other valid outputs).
3 4 000 1 100 1 001 0 111 1
0 0 1 1
3 seconds
512 megabytes
['greedy', 'interactive', 'math', 'probabilities', '*2700']
H. Hard Optimizationtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of n segments on a line [L_i; R_i]. All 2n segment endpoints are pairwise distinct integers.The set is laminar — any two segments are either disjoint or one of them contains the other.Choose a non-empty subsegment [l_i, r_i] with integer endpoints in each segment (L_i \le l_i < r_i \le R_i) in such a way that no two subsegments intersect (they are allowed to have common endpoints though) and the sum of their lengths (\sum_{i=1}^n r_i - l_i) is maximized.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^3) — the number of segments.The i-th of the next n lines contains two integers L_i and R_i (0 \le L_i < R_i \le 10^9) — the endpoints of the i-th segment.All the given 2n segment endpoints are distinct. The set of segments is laminar.OutputOn the first line, output the maximum possible sum of subsegment lengths.On the i-th of the next n lines, output two integers l_i and r_i (L_i \le l_i < r_i \le R_i), denoting the chosen subsegment of the i-th segment.ExampleInput 4 1 10 2 3 5 9 6 7 Output 7 3 6 2 3 7 9 6 7 NoteThe example input and the example output are illustrated below.
4 1 10 2 3 5 9 6 7
7 3 6 2 3 7 9 6 7
3 seconds
512 megabytes
['dp', '*3200']
F. Fiber Shapetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputImagine a board with n pins put into it, the i-th pin is located at (x_i, y_i). For simplicity, we will restrict the problem to the case where the pins are placed in vertices of a convex polygon.Then, take a non-stretchable string of length l, and put it around all the pins. Place a pencil inside the string and draw a curve around the pins, trying to pull the string in every possible direction. The picture below shows an example of a string tied around the pins and pulled by a pencil (a point P). Your task is to find an area inside this curve. Formally, for a given convex polygon S and a length l let's define a fiber shape F(S, l) as a set of points t such that the perimeter of the convex hull of S \cup \{t\} does not exceed l. Find an area of F(S, l).InputThe first line contains two integers n and l (3 \le n \le 10^4; 1 \le l \le 8 \cdot 10^5) — the number of vertices of the polygon S and the length of the string. Next n lines contain integers x_i and y_i (-10^5 \le x_i, y_i \le 10^5) — coordinates of polygon's vertices in counterclockwise order. All internal angles of the polygon are strictly less than \pi. The length l exceeds the perimeter of the polygon by at least 10^{-3}.OutputOutput a single floating-point number — the area of the fiber shape F(S, l). Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. ExamplesInput 3 4 0 0 1 0 0 1 Output 3.012712585980357 Input 4 5 0 0 1 0 1 1 0 1 Output 5.682061989789656 Input 5 17 0 0 2 -1 3 0 4 3 -1 4 Output 37.719371276930820 NoteThe following pictures illustrate the example tests.
3 4 0 0 1 0 0 1
3.012712585980357
3 seconds
512 megabytes
['*2800']
D. Digitstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDiana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.InputThe first line contains the integers n and d (1\le n\le 10^5, 0\le d\le 9). The second line contains n integers a_i (1\le a_i\le 1000). OutputOn the first line, print the number of chosen cards k (1\le k\le n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.ExamplesInput 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 NoteIn the first example, 1 \times 2 \times 4 \times 11 \times 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.In the fourth example, 9 \times 11 \times 17 = 1683, which ends with the digit 3. In the fifth example, 2 \times 2 \times 2 \times 2 = 16, which ends with the digit 6.
6 4 4 11 8 2 1 13
5 1 2 4 11 13
3 seconds
512 megabytes
['dp', 'math', 'number theory', '*2100']
C. Cactus Not Enoughtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere was no problem about a cactus at the NERC 2020 online round. That's a bad mistake, so judges decided to fix it. You shall not pass to the World Finals 2021 without solving a problem about a cactus!A cactus is a connected undirected graph in which every edge lies on at most one simple cycle. Intuitively, a cactus is a generalization of a tree where some cycles are allowed. Multiedges (multiple edges between a pair of vertices) and loops (edges that connect a vertex to itself) are not allowed in a cactus. Cher has got a cactus. She calls cactus strong if it is impossible to add an edge to it in such a way that it still remains a cactus. But Cher thinks her cactus is not strong enough. She wants to add the smallest possible number of edges to it to make it strong, i. e. to create a new cactus with the same vertices, so that the original cactus is a subgraph of the new one, and it is impossible to add another edge to it so that the graph remains a cactus. Cher hired you to do this job for her. So... it's on you!InputThe input consists of one or more independent test cases.The first line of each test case contains two integers n and m (1 \le n \le 10^5, 0 \le m \le 10^5), where n is the number of vertices in the graph. Vertices are numbered from 1 to n. Edges of the graph are represented by a set of edge-distinct paths, where m is the number of such paths. Each of the following m lines contains a path in the graph. A path starts with an integer number s_i (2 \le s_i \le 1000) followed by s_i integers from 1 to n. These s_i integers represent vertices of a path. Adjacent vertices in a path are distinct. The path can go through the same vertex multiple times, but every edge is traversed exactly once in the whole test case. There are no multiedges in the graph (there is at most one edge between any two vertices).The last line of the input after all test cases always contains two zeros. It does not define a test case. It just marks the end of the input and does not require any output.All graphs in the input are cacti. The total sum of all values of n and the total sum of all values of m throughout the input both do not exceed 10^5.OutputFor each test case, first output the line with the minimal possible number of additional edges A. Then output A lines, each describing one edge as u_i v_i, where u_i and v_i are the numbers of vertices to connect. After adding these edges, the resulting graph must be a strong cactus.ExampleInput 6 1 7 1 2 5 6 2 3 4 3 1 4 1 2 3 1 5 2 3 1 3 5 3 1 2 4 7 2 6 1 2 3 4 5 3 3 6 5 7 0 0 Output 1 1 4 0 1 5 4 2 1 3 6 7
6 1 7 1 2 5 6 2 3 4 3 1 4 1 2 3 1 5 2 3 1 3 5 3 1 2 4 7 2 6 1 2 3 4 5 3 3 6 5 7 0 0
1 1 4 0 1 5 4 2 1 3 6 7
3 seconds
512 megabytes
['dfs and similar', 'graph matchings', 'graphs', '*2900']
B. Button Locktime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are standing in front of the room with great treasures. The only thing stopping you is the door with a push-button combination lock. This lock has d buttons with digits from 0 to d - 1. Whenever you press a button, it stays pushed down. You can not pop back up just one button, but there is a "RESET" button — pressing it pops up all other buttons. Initially, no buttons are pushed down.The door instantly opens when some specific set of digits is pushed down. Sadly, you don't know the password for it. Having read the documentation for this specific lock, you found out that there are n possible passwords for this particular lock. Find the shortest sequence of button presses, such that all possible passwords appear at least once during its execution. Any shortest correct sequence of button presses will be accepted.InputThe first line contains two integers d and n (1 \le d \le 10; 1 \le n \le 2^d - 1). Next n lines describe possible passwords. Each line contains a string s_i of d zeros and ones: for all j from 1 to d the j-th character is 1 iff the button with the digit j - 1 must be pushed down.All strings s_i are different, and each string contains at least one 1.OutputOn the first line, print the number k — the minimum number of button presses. On the second line, print k tokens, describing the sequence. Whenever you press a button with a digit, print that digit. Whenever you press "RESET", print "R".ExamplesInput 2 2 10 11 Output 2 0 1 Input 3 4 001 111 101 011 Output 6 2 0 R 1 2 0 NoteIn the second example, the sequence 1 2 R 2 0 1 is also possible.
2 2 10 11
2 0 1
3 seconds
512 megabytes
['flows', 'graph matchings', 'graphs', '*2600']
C. The Sports Festivaltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe student council is preparing for the relay race at the sports festival.The council consists of n members. They will run one after the other in the race, the speed of member i is s_i. The discrepancy d_i of the i-th stage is the difference between the maximum and the minimum running speed among the first i members who ran. Formally, if a_i denotes the speed of the i-th member who participated in the race, then d_i = \max(a_1, a_2, \dots, a_i) - \min(a_1, a_2, \dots, a_i).You want to minimize the sum of the discrepancies d_1 + d_2 + \dots + d_n. To do this, you are allowed to change the order in which the members run. What is the minimum possible sum that can be achieved?InputThe first line contains a single integer n (1 \le n \le 2000)  — the number of members of the student council.The second line contains n integers s_1, s_2, \dots, s_n (1 \le s_i \le 10^9)  – the running speeds of the members.OutputPrint a single integer  — the minimum possible value of d_1 + d_2 + \dots + d_n after choosing the order of the members.ExamplesInput 3 3 1 2 Output 3 Input 1 5 Output 0 Input 6 1 6 3 3 6 3 Output 11 Input 6 104 943872923 6589 889921234 1000000000 69 Output 2833800505 NoteIn the first test case, we may choose to make the third member run first, followed by the first member, and finally the second. Thus a_1 = 2, a_2 = 3, and a_3 = 1. We have: d_1 = \max(2) - \min(2) = 2 - 2 = 0. d_2 = \max(2, 3) - \min(2, 3) = 3 - 2 = 1. d_3 = \max(2, 3, 1) - \min(2, 3, 1) = 3 - 1 = 2. The resulting sum is d_1 + d_2 + d_3 = 0 + 1 + 2 = 3. It can be shown that it is impossible to achieve a smaller value.In the second test case, the only possible rearrangement gives d_1 = 0, so the minimum possible result is 0.
3 3 1 2
3
1 second
256 megabytes
['dp', 'greedy', '*1800']
B. TMT Documenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it.However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to figure out whether the document has malfunctioned. Specifically, he is given a string of length n whose characters are all either T or M, and he wants to figure out if it is possible to partition it into some number of disjoint subsequences, all of which are equal to TMT. That is, each character of the string should belong to exactly one of the subsequences.A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero) characters.InputThe first line contains an integer t (1 \le t \le 5000)  — the number of test cases.The first line of each test case contains an integer n (3 \le n < 10^5), the number of characters in the string entered in the document. It is guaranteed that n is divisible by 3.The second line of each test case contains a string of length n consisting of only the characters T and M.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print a single line containing YES if the described partition exists, and a single line containing NO otherwise.ExampleInput 5 3 TMT 3 MTT 6 TMTMTT 6 TMTTTT 6 TTMMTT Output YES NO YES NO YES NoteIn the first test case, the string itself is already a sequence equal to TMT.In the third test case, we may partition the string into the subsequences TMTMTT. Both the bolded and the non-bolded subsequences are equal to TMT.
5 3 TMT 3 MTT 6 TMTMTT 6 TMTTTT 6 TTMMTT
YES NO YES NO YES
1 second
256 megabytes
['greedy', '*1100']
A. Average Heighttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSayaka Saeki is a member of the student council, which has n other members (excluding Sayaka). The i-th member has a height of a_i millimeters.It's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, she wants to arrange all the members in a line such that the amount of photogenic consecutive pairs of members is as large as possible.A pair of two consecutive members u and v on a line is considered photogenic if their average height is an integer, i.e. \frac{a_u + a_v}{2} is an integer.Help Sayaka arrange the other members to maximize the number of photogenic consecutive pairs.InputThe first line contains a single integer t (1\le t\le 500) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 2000)  — the number of other council members.The second line of each test case contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 2 \cdot 10^5)  — the heights of each of the other members in millimeters.It is guaranteed that the sum of n over all test cases does not exceed 2000.OutputFor each test case, output on one line n integers representing the heights of the other members in the order, which gives the largest number of photogenic consecutive pairs. If there are multiple such orders, output any of them.ExampleInput 4 3 1 1 2 3 1 1 1 8 10 9 13 15 3 16 9 13 2 18 9 Output 1 1 2 1 1 1 13 9 13 15 3 9 16 10 9 18 NoteIn the first test case, there is one photogenic pair: (1, 1) is photogenic, as \frac{1+1}{2}=1 is integer, while (1, 2) isn't, as \frac{1+2}{2}=1.5 isn't integer.In the second test case, both pairs are photogenic.
4 3 1 1 2 3 1 1 1 8 10 9 13 15 3 16 9 13 2 18 9
1 1 2 1 1 1 13 9 13 15 3 9 16 10 9 18
1 second
256 megabytes
['constructive algorithms', '*800']
F. Optimal Encodingtime limit per test7 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTouko's favorite sequence of numbers is a permutation a_1, a_2, \dots, a_n of 1, 2, \dots, n, and she wants some collection of permutations that are similar to her favorite permutation.She has a collection of q intervals of the form [l_i, r_i] with 1 \le l_i \le r_i \le n. To create permutations that are similar to her favorite permutation, she coined the following definition: A permutation b_1, b_2, \dots, b_n allows an interval [l', r'] to holds its shape if for any pair of integers (x, y) such that l' \le x < y \le r', we have b_x < b_y if and only if a_x < a_y. A permutation b_1, b_2, \dots, b_n is k-similar if b allows all intervals [l_i, r_i] for all 1 \le i \le k to hold their shapes. Yuu wants to figure out all k-similar permutations for Touko, but it turns out this is a very hard task; instead, Yuu will encode the set of all k-similar permutations with directed acylic graphs (DAG). Yuu also coined the following definitions for herself: A permutation b_1, b_2, \dots, b_n satisfies a DAG G' if for all edge u \to v in G', we must have b_u < b_v. A k-encoding is a DAG G_k on the set of vertices 1, 2, \dots, n such that a permutation b_1, b_2, \dots, b_n satisfies G_k if and only if b is k-similar. Since Yuu is free today, she wants to figure out the minimum number of edges among all k-encodings for each k from 1 to q.InputThe first line contains two integers n and q (1 \le n \le 25\,000, 1 \le q \le 100\,000).The second line contains n integers a_1, a_2, \dots, a_n which form a permutation of 1, 2, \dots, n.The i-th of the following q lines contains two integers l_i and r_i. (1 \le l_i \le r_i \le n).OutputPrint q lines. The k-th of them should contain a single integer  — The minimum number of edges among all k-encodings.ExamplesInput 4 3 2 4 1 3 1 3 2 4 1 4 Output 2 4 3 Input 8 4 3 7 4 8 1 5 2 6 3 6 1 6 3 8 1 8 Output 3 5 9 7 Input 10 10 10 5 1 2 7 3 9 4 6 8 2 2 4 5 6 8 4 10 4 4 2 7 2 2 7 8 3 7 2 10 Output 0 1 3 6 6 9 9 9 9 8 NoteFor the first test case: All 1-similar permutations must allow the interval [1, 3] to hold its shape. Therefore, the set of all 1-similar permutations is \{[3, 4, 2, 1], [3, 4, 1, 2], [2, 4, 1, 3], [2, 3, 1, 4]\}. The optimal encoding of these permutations is All 2-similar permutations must allow the intervals [1, 3] and [2, 4] to hold their shapes. Therefore, the set of all 2-similar permutations is \{[3, 4, 1, 2], [2, 4, 1, 3]\}. The optimal encoding of these permutations is All 3-similar permutations must allow the intervals [1, 3], [2, 4], and [1, 4] to hold their shapes. Therefore, the set of all 3-similar permutations only includes [2, 4, 1, 3]. The optimal encoding of this permutation is
4 3 2 4 1 3 1 3 2 4 1 4
2 4 3
7 seconds
1024 megabytes
['brute force', 'data structures', '*3500']
E. Tree Calendartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYuu Koito and Touko Nanami are newlyweds! On the wedding day, Yuu gifted Touko a directed tree with n nodes and rooted at 1, and a labeling a which is some DFS order of the tree. Every edge in this tree is directed away from the root.After calling dfs(1) the following algorithm returns a as a DFS order of a tree rooted at 1 :order := 0a := array of length n function dfs(u): order := order + 1 a[u] := order for all v such that there is a directed edge (u -> v): dfs(v)Note that there may be different DFS orders for a given tree.Touko likes the present so much she decided to play with it! On each day following the wedding day, Touko performs this procedure once: Among all directed edges u \rightarrow v such that a_u < a_v, select the edge u' \rightarrow v' with the lexicographically smallest pair (a_{u'}, a_{v'}). Swap a_{u'} and a_{v'}.Days have passed since their wedding, and Touko has somehow forgotten which date the wedding was and what was the original labeling a! Fearing that Yuu might get angry, Touko decided to ask you to derive these two pieces of information using the current labeling.Being her good friend, you need to find the number of days that have passed since the wedding, and the original labeling of the tree. However, there is a chance that Touko might have messed up her procedures, which result in the current labeling being impossible to obtain from some original labeling; in that case, please inform Touko as well.InputThe first line of the input contains an integer n (2 \le n \le 3 \cdot 10^5) — the number of nodes on the tree.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le n, all a_i are distinct) — the current labeling of the tree.Each of the next n - 1 lines contains two integers u_i and v_i (1 \le u, v \le n, u \neq v), describing an directed edge from u_i to v_i. The edges form a directed tree rooted at 1.OutputIf the current labeling is impossible to arrive at from any DFS order, print NO.Else, on the first line, print YES. On the second line, print a single integer denoting the number of days since the wedding. On the third line, print n numbers space-separated denoting the original labeling of the tree. If there are multiple correct outputs, print any. This means: you are allowed to output any pair (DFS order, number of days), such that we get the current configuration from the DFS order you provided in exactly the number of days you provided.ExamplesInput 7 4 5 2 1 7 6 3 1 5 7 6 1 2 2 7 3 4 1 3 Output YES 5 1 4 2 3 7 6 5 Input 7 7 6 5 3 1 4 2 4 3 2 5 3 7 1 4 7 2 2 6 Output NO NoteThe following animation showcases the first sample test case. The white label inside the node represents the index of the node i, while the boxed orange label represents the value a_i.
7 4 5 2 1 7 6 3 1 5 7 6 1 2 2 7 3 4 1 3
YES 5 1 4 2 3 7 6 5
2 seconds
512 megabytes
['brute force', 'constructive algorithms', 'data structures', 'dfs and similar', 'sortings', 'trees', '*3100']
D. Swap Passtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBased on a peculiar incident at basketball practice, Akari came up with the following competitive programming problem!You are given n points on the plane, no three of which are collinear. The i-th point initially has a label a_i, in such a way that the labels a_1, a_2, \dots, a_n form a permutation of 1, 2, \dots, n.You are allowed to modify the labels through the following operation: Choose two distinct integers i and j between 1 and n. Swap the labels of points i and j, and finally Draw the segment between points i and j. A sequence of operations is valid if after applying all of the operations in the sequence in order, the k-th point ends up having the label k for all k between 1 and n inclusive, and the drawn segments don't intersect each other internally. Formally, if two of the segments intersect, then they must do so at a common endpoint of both segments.In particular, all drawn segments must be distinct.Find any valid sequence of operations, or say that none exist. InputThe first line contains an integer n (3 \le n \le 2000)  — the number of points.The i-th of the following n lines contains three integers x_i, y_i, a_i (-10^6 \le x_i, y_i \le 10^6, 1 \le a_i \le n), representing that the i-th point has coordinates (x_i, y_i) and initially has label a_i.It is guaranteed that all points are distinct, no three points are collinear, and the labels a_1, a_2, \dots, a_n form a permutation of 1, 2, \dots, n.OutputIf it is impossible to perform a valid sequence of operations, print -1.Otherwise, print an integer k (0 \le k \le \frac{n(n - 1)}{2})  — the number of operations to perform, followed by k lines, each containing two integers i and j (1 \le i, j \le n, i\neq j)  — the indices of the points chosen for the operation.Note that you are not required to minimize or maximize the value of k.If there are multiple possible answers, you may print any of them.ExamplesInput 5 -1 -2 2 3 0 5 1 3 4 4 -3 3 5 2 1 Output 5 1 2 5 3 4 5 1 5 1 3 Input 3 5 4 1 0 0 2 -3 -2 3 Output 0 NoteThe following animation showcases the first sample test case. The black numbers represent the indices of the points, while the boxed orange numbers represent their labels. In the second test case, all labels are already in their correct positions, so no operations are necessary.
5 -1 -2 2 3 0 5 1 3 4 4 -3 3 5 2 1
5 1 2 5 3 4 5 1 5 1 3
2 seconds
256 megabytes
['constructive algorithms', 'geometry', 'sortings', '*3000']
C. Complete the MSTtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows.You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with non-negative weights so that in the resulting fully-assigned complete graph the XOR sum of all weights would be equal to 0.Define the ugliness of a fully-assigned complete graph the weight of its minimum spanning tree, where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible.As a reminder, an undirected complete graph with n nodes contains all edges (u, v) with 1 \le u < v \le n; such a graph has \frac{n(n-1)}{2} edges.She is not sure how to solve this problem, so she asks you to solve it for her.InputThe first line contains two integers n and m (2 \le n \le 2 \cdot 10^5, 0 \le m \le \min(2 \cdot 10^5, \frac{n(n-1)}{2} - 1))  — the number of nodes and the number of pre-assigned edges. The inputs are given so that there is at least one unassigned edge.The i-th of the following m lines contains three integers u_i, v_i, and w_i (1 \le u_i, v_i \le n, u \ne v, 1 \le w_i < 2^{30}), representing the edge from u_i to v_i has been pre-assigned with the weight w_i. No edge appears in the input more than once.OutputPrint on one line one integer  — the minimum ugliness among all weight assignments with XOR sum equal to 0.ExamplesInput 4 4 2 1 14 1 4 14 3 2 15 4 3 8 Output 15 Input 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 Output 0 Input 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 5 6 Output 6 NoteThe following image showcases the first test case. The black weights are pre-assigned from the statement, the red weights are assigned by us, and the minimum spanning tree is denoted by the blue edges.
4 4 2 1 14 1 4 14 3 2 15 4 3 8
15
3 seconds
256 megabytes
['bitmasks', 'brute force', 'data structures', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'trees', '*2500']
B. Almost Sortedtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSeiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations.A permutation a_1, a_2, \dots, a_n of 1, 2, \dots, n is said to be almost sorted if the condition a_{i + 1} \ge a_i - 1 holds for all i between 1 and n - 1 inclusive.Maki is considering the list of all almost sorted permutations of 1, 2, \dots, n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation?Permutation p is lexicographically smaller than a permutation q if and only if the following holds: in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q.InputThe first line contains a single integer t (1\le t\le 1000) — the number of test cases.Each test case consists of a single line containing two integers n and k (1 \le n \le 10^5, 1 \le k \le 10^{18}).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist.ExampleInput 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 NoteFor the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}.For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}.
5 1 1 1 2 3 3 6 5 3 4
1 -1 2 1 3 1 2 4 3 5 6 3 2 1
2 seconds
256 megabytes
['binary search', 'combinatorics', 'constructive algorithms', 'implementation', '*1800']
A. Binary Literaturetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA bitstring is a string that contains only the characters 0 and 1.Koyomi Kanou is working hard towards her dream of becoming a writer. To practice, she decided to participate in the Binary Novel Writing Contest. The writing prompt for the contest consists of three bitstrings of length 2n. A valid novel for the contest is a bitstring of length at most 3n that contains at least two of the three given strings as subsequences.Koyomi has just received the three prompt strings from the contest organizers. Help her write a valid novel for the contest.A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero) characters.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 10^5).Each of the following three lines contains a bitstring of length 2n. It is guaranteed that these three strings are pairwise distinct.It is guaranteed that the sum of n across all test cases does not exceed 10^5.OutputFor each test case, print a single line containing a bitstring of length at most 3n that has at least two of the given bitstrings as subsequences.It can be proven that under the constraints of the problem, such a bitstring always exists.If there are multiple possible answers, you may output any of them.ExampleInput 2 1 00 11 01 3 011001 111010 010001 Output 010 011001010 NoteIn the first test case, the bitstrings 00 and 01 are subsequences of the output string: 010 and 010. Note that 11 is not a subsequence of the output string, but this is not required.In the second test case all three input strings are subsequences of the output string: 011001010, 011001010 and 011001010.
2 1 00 11 01 3 011001 111010 010001
010 011001010
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'strings', 'two pointers', '*1900']
G. Maximize the Remaining Stringtime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting of lowercase Latin letters. While there is at least one character in the string s that is repeated at least twice, you perform the following operation: you choose the index i (1 \le i \le |s|) such that the character at position i occurs at least two times in the string s, and delete the character at position i, that is, replace s with s_1 s_2 \ldots s_{i-1} s_{i+1} s_{i+2} \ldots s_n. For example, if s="codeforces", then you can apply the following sequence of operations: i=6 \Rightarrow s="codefrces"; i=1 \Rightarrow s="odefrces"; i=7 \Rightarrow s="odefrcs"; Given a given string s, find the lexicographically maximum string that can be obtained after applying a certain sequence of operations after which all characters in the string become unique.A string a of length n is lexicographically less than a string b of length m, if: there is an index i (1 \le i \le \min(n, m)) such that the first i-1 characters of the strings a and b are the same, and the i-th character of the string a is less than i-th character of string b; or the first \min(n, m) characters in the strings a and b are the same and n < m. For example, the string a="aezakmi" is lexicographically less than the string b="aezus".InputThe first line contains one integer t (1 \le t \le 10^4). Then t test cases follow.Each test case is characterized by a string s, consisting of lowercase Latin letters (1 \le |s| \le 2 \cdot 10^5).It is guaranteed that the sum of the lengths of the strings in all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the lexicographically maximum string that can be obtained after applying a certain sequence of operations after which all characters in the string become unique.ExampleInput 6 codeforces aezakmi abacaba convexhull swflldjgpaxs myneeocktxpqjpz Output odfrces ezakmi cba convexhul wfldjgpaxs myneocktxqjpz
6 codeforces aezakmi abacaba convexhull swflldjgpaxs myneeocktxpqjpz
odfrces ezakmi cba convexhul wfldjgpaxs myneocktxqjpz
2.5 seconds
256 megabytes
['brute force', 'data structures', 'dp', 'greedy', 'strings', '*2000']
F. Triangular Pathstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 \le c \le r), where r is the number of the layer, and c is the number of the point in the layer. From each point (r, c) there are two directed edges to the points (r+1, c) and (r+1, c+1), but only one of the edges is activated. If r + c is even, then the edge to the point (r+1, c) is activated, otherwise the edge to the point (r+1, c+1) is activated. Look at the picture for a better understanding. Activated edges are colored in black. Non-activated edges are colored in gray. From the point (r_1, c_1) it is possible to reach the point (r_2, c_2), if there is a path between them only from activated edges. For example, in the picture above, there is a path from (1, 1) to (3, 2), but there is no path from (2, 1) to (1, 1).Initially, you are at the point (1, 1). For each turn, you can: Replace activated edge for point (r, c). That is if the edge to the point (r+1, c) is activated, then instead of it, the edge to the point (r+1, c+1) becomes activated, otherwise if the edge to the point (r+1, c+1), then instead if it, the edge to the point (r+1, c) becomes activated. This action increases the cost of the path by 1; Move from the current point to another by following the activated edge. This action does not increase the cost of the path. You are given a sequence of n points of an infinite triangle (r_1, c_1), (r_2, c_2), \ldots, (r_n, c_n). Find the minimum cost path from (1, 1), passing through all n points in arbitrary order.InputThe first line contains one integer t (1 \le t \le 10^4) is the number of test cases. Then t test cases follow.Each test case begins with a line containing one integer n (1 \le n \le 2 \cdot 10^5) is the number of points to visit.The second line contains n numbers r_1, r_2, \ldots, r_n (1 \le r_i \le 10^9), where r_i is the number of the layer in which i-th point is located.The third line contains n numbers c_1, c_2, \ldots, c_n (1 \le c_i \le r_i), where c_i is the number of the i-th point in the r_i layer.It is guaranteed that all n points are distinct.It is guaranteed that there is always at least one way to traverse all n points.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the minimum cost of a path passing through all points in the corresponding test case.ExampleInput 4 3 1 4 2 1 3 1 2 2 4 2 3 2 1 1000000000 1 1000000000 4 3 10 5 8 2 5 2 4 Output 0 1 999999999 2
4 3 1 4 2 1 3 1 2 2 4 2 3 2 1 1000000000 1 1000000000 4 3 10 5 8 2 5 2 4
0 1 999999999 2
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'math', 'shortest paths', 'sortings', '*2000']
E. Restoring the Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation is a sequence of n integers from 1 to n, in which all numbers occur exactly once. For example, [1], [3, 5, 2, 1, 4], [1, 3, 2] are permutations, and [2, 3, 2], [4, 3, 1], [0] are not.Polycarp was presented with a permutation p of numbers from 1 to n. However, when Polycarp came home, he noticed that in his pocket, the permutation p had turned into an array q according to the following rule: q_i = \max(p_1, p_2, \ldots, p_i). Now Polycarp wondered what lexicographically minimal and lexicographically maximal permutations could be presented to him.An array a of length n is lexicographically smaller than an array b of length n if there is an index i (1 \le i \le n) such that the first i-1 elements of arrays a and b are the same, and the i-th element of the array a is less than the i-th element of the array b. For example, the array a=[1, 3, 2, 3] is lexicographically smaller than the array b=[1, 3, 4, 2].For example, if n=7 and p=[3, 2, 4, 1, 7, 5, 6], then q=[3, 3, 4, 4, 7, 7, 7] and the following permutations could have been as p initially: [3, 1, 4, 2, 7, 5, 6] (lexicographically minimal permutation); [3, 1, 4, 2, 7, 6, 5]; [3, 2, 4, 1, 7, 5, 6]; [3, 2, 4, 1, 7, 6, 5] (lexicographically maximum permutation). For a given array q, find the lexicographically minimal and lexicographically maximal permutations that could have been originally presented to Polycarp.InputThe first line contains one integer t (1 \le t \le 10^4). Then t test cases follow.The first line of each test case contains one integer n (1 \le n \le 2 \cdot 10^5).The second line of each test case contains n integers q_1, q_2, \ldots, q_n (1 \le q_i \le n).It is guaranteed that the array q was obtained by applying the rule from the statement to some permutation p.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output two lines: on the first line output n integers — lexicographically minimal permutation that could have been originally presented to Polycarp; on the second line print n integers — lexicographically maximal permutation that could have been originally presented to Polycarp; ExampleInput 4 7 3 3 4 4 7 7 7 4 1 2 3 4 7 3 4 5 5 5 7 7 1 1 Output 3 1 4 2 7 5 6 3 2 4 1 7 6 5 1 2 3 4 1 2 3 4 3 4 5 1 2 7 6 3 4 5 2 1 7 6 1 1
4 7 3 3 4 4 7 7 7 4 1 2 3 4 7 3 4 5 5 5 7 7 1 1
3 1 4 2 7 5 6 3 2 4 1 7 6 5 1 2 3 4 1 2 3 4 3 4 5 1 2 7 6 3 4 5 2 1 7 6 1 1
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1500']
D. Epic Transformationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n consisting of integers. You can apply the following operation, consisting of several steps, on the array a zero or more times: you select two different numbers in the array a_i and a_j; you remove i-th and j-th elements from the array. For example, if n=6 and a=[1, 6, 1, 1, 4, 4], then you can perform the following sequence of operations: select i=1, j=5. The array a becomes equal to [6, 1, 1, 4]; select i=1, j=2. The array a becomes equal to [1, 4]. What can be the minimum size of the array after applying some sequence of operations to it?InputThe first line contains a single integer t (1 \le t \le 10^4). Then t test cases follow.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) is length of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the minimum possible size of the array after applying some sequence of operations to it.ExampleInput 5 6 1 6 1 1 4 4 2 1 2 2 1 1 5 4 5 4 5 4 6 2 3 2 1 3 1 Output 0 0 2 1 0
5 6 1 6 1 1 4 4 2 1 2 2 1 1 5 4 5 4 5 4 6 2 3 2 1 3 1
0 0 2 1 0
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', '*1400']
C. Double-ended Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given the strings a and b, consisting of lowercase Latin letters. You can do any number of the following operations in any order: if |a| > 0 (the length of the string a is greater than zero), delete the first character of the string a, that is, replace a with a_2 a_3 \ldots a_n; if |a| > 0, delete the last character of the string a, that is, replace a with a_1 a_2 \ldots a_{n-1}; if |b| > 0 (the length of the string b is greater than zero), delete the first character of the string b, that is, replace b with b_2 b_3 \ldots b_n; if |b| > 0, delete the last character of the string b, that is, replace b with b_1 b_2 \ldots b_{n-1}. Note that after each of the operations, the string a or b may become empty.For example, if a="hello" and b="icpc", then you can apply the following sequence of operations: delete the first character of the string a \Rightarrow a="ello" and b="icpc"; delete the first character of the string b \Rightarrow a="ello" and b="cpc"; delete the first character of the string b \Rightarrow a="ello" and b="pc"; delete the last character of the string a \Rightarrow a="ell" and b="pc"; delete the last character of the string b \Rightarrow a="ell" and b="p". For the given strings a and b, find the minimum number of operations for which you can make the strings a and b equal. Note that empty strings are also equal.InputThe first line contains a single integer t (1 \le t \le 100). Then t test cases follow.The first line of each test case contains the string a (1 \le |a| \le 20), consisting of lowercase Latin letters.The second line of each test case contains the string b (1 \le |b| \le 20), consisting of lowercase Latin letters.OutputFor each test case, output the minimum number of operations that can make the strings a and b equal.ExampleInput 5 a a abcd bc hello codeforces hello helo dhjakjsnasjhfksafasd adjsnasjhfksvdafdser Output 0 2 13 3 20
5 a a abcd bc hello codeforces hello helo dhjakjsnasjhfksafasd adjsnasjhfksvdafdser
0 2 13 3 20
2 seconds
256 megabytes
['brute force', 'implementation', 'strings', '*1000']
B. Partial Replacementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a number k and a string s of length n, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met: The first character '*' in the original string should be replaced with 'x'; The last character '*' in the original string should be replaced with 'x'; The distance between two neighboring replaced characters 'x' must not exceed k (more formally, if you replaced characters at positions i and j (i < j) and at positions [i+1, j-1] there is no "x" symbol, then j-i must be no more than k). For example, if n=7, s=.**.*** and k=3, then the following strings will satisfy the conditions above: .xx.*xx; .x*.x*x; .xx.xxx. But, for example, the following strings will not meet the conditions: .**.*xx (the first character '*' should be replaced with 'x'); .x*.xx* (the last character '*' should be replaced with 'x'); .x*.*xx (the distance between characters at positions 2 and 6 is greater than k=3). Given n, k, and s, find the minimum number of '*' characters that must be replaced with 'x' in order to meet the above conditions.InputThe first line contains one integer t (1 \le t \le 500). Then t test cases follow.The first line of each test case contains two integers n and k (1 \le k \le n \le 50).The second line of each test case contains a string s of length n, consisting of the characters '.' and '*'.It is guaranteed that there is at least one '*' in the string s.It is guaranteed that the distance between any two neighboring '*' characters does not exceed k.OutputFor each test case output the minimum number of '*' characters that must be replaced with 'x' characters in order to satisfy the conditions above.ExampleInput 5 7 3 .**.*** 5 1 ..*.. 5 2 *.*.* 3 2 *.* 1 1 * Output 3 1 3 2 1
5 7 3 .**.*** 5 1 ..*.. 5 2 *.*.* 3 2 *.* 1 1 *
3 1 3 2 1
2 seconds
256 megabytes
['greedy', 'implementation', '*1100']
A. Strange Tabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp found a rectangular table consisting of n rows and m columns. He noticed that each cell of the table has its number, obtained by the following algorithm "by columns": cells are numbered starting from one; cells are numbered from left to right by columns, and inside each column from top to bottom; number of each cell is an integer one greater than in the previous cell. For example, if n = 3 and m = 5, the table will be numbered as follows: \begin{matrix} 1 & 4 & 7 & 10 & 13 \\ 2 & 5 & 8 & 11 & 14 \\ 3 & 6 & 9 & 12 & 15 \\ \end{matrix} However, Polycarp considers such numbering inconvenient. He likes the numbering "by rows": cells are numbered starting from one; cells are numbered from top to bottom by rows, and inside each row from left to right; number of each cell is an integer one greater than the number of the previous cell. For example, if n = 3 and m = 5, then Polycarp likes the following table numbering: \begin{matrix} 1 & 2 & 3 & 4 & 5 \\ 6 & 7 & 8 & 9 & 10 \\ 11 & 12 & 13 & 14 & 15 \\ \end{matrix} Polycarp doesn't have much time, so he asks you to find out what would be the cell number in the numbering "by rows", if in the numbering "by columns" the cell has the number x?InputThe first line contains a single integer t (1 \le t \le 10^4). Then t test cases follow.Each test case consists of a single line containing three integers n, m, x (1 \le n, m \le 10^6, 1 \le x \le n \cdot m), where n and m are the number of rows and columns in the table, and x is the cell number.Note that the numbers in some test cases do not fit into the 32-bit integer type, so you must use at least the 64-bit integer type of your programming language.OutputFor each test case, output the cell number in the numbering "by rows".ExampleInput 5 1 1 1 2 2 3 3 5 11 100 100 7312 1000000 1000000 1000000000000 Output 1 2 9 1174 1000000000000
5 1 1 1 2 2 3 3 5 11 100 100 7312 1000000 1000000 1000000000000
1 2 9 1174 1000000000000
2 seconds
256 megabytes
['math', '*800']
G. Encoded messagetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe first line of the input contains a single integer N (1 \le N \le 24). The next N lines contain 5 space-separated integers each. The first three integers will be between 0 and 2, inclusive. The last two integers will be between 0 and 3, inclusive. The sum of the first three integers will be equal to the sum of the last two integers.OutputOutput the result – a string of lowercase English letters.ExamplesInput 1 1 0 0 1 0 Output a Input 10 2 0 0 1 1 1 1 1 2 1 2 1 0 1 2 1 1 0 1 1 2 1 0 2 1 1 1 1 2 1 1 2 1 3 1 2 0 0 1 1 1 1 0 1 1 1 1 2 2 2 Output codeforcez
1 1 0 0 1 0
a
1 second
256 megabytes
['*special problem', 'implementation', '*2600']
F. Mathtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output *The two images are equivalent, feel free to use either one.InputThe input contains a single integer a (-100 \le a \le 100).OutputOutput the result – an integer number.ExampleInput 1 Output 1
1
1
1 second
256 megabytes
['*special problem', 'math', '*2200']
E. Cakewalktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA mouse encountered a nice big cake and decided to take a walk across it, eating the berries on top of the cake on its way. The cake is rectangular, neatly divided into squares; some of the squares have a berry in them, and some don't.The mouse is in a bit of a hurry, though, so once she enters the cake from its northwest corner (the top left cell in the input data), she will only go east (right) or south (down), until she reaches the southeast corner (the bottom right cell). She will eat every berry in the squares she passes through, but not in the other squares.The mouse tries to choose her path so as to maximize the number of berries consumed. However, her haste and hunger might be clouding her judgement, leading her to suboptimal decisions...InputThe first line of input contains two integers H and W (1 \le H, W \le 5), separated by a space, — the height and the width of the cake.The next H lines contain a string of W characters each, representing the squares of the cake in that row: '.' represents an empty square, and '*' represents a square with a berry.OutputOutput the number of berries the mouse will eat following her strategy.ExamplesInput 4 3 *.. .*. ..* ... Output 3 Input 4 4 .*.. *... ...* ..*. Output 2 Input 3 4 ..** *... .... Output 1 Input 5 5 ..*.. ..... **... **... **... Output 1
4 3 *.. .*. ..* ...
3
1 second
256 megabytes
['*special problem', 'greedy', 'implementation', 'shortest paths', '*1800']
D. Xenolith? Hippodrome?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe input contains two integers N, M (1 \le N \le 1024, 2 \le M \le 16), separated by a single space.OutputOutput "YES" or "NO".ExamplesInput 2 3 Output YES Input 3 2 Output NO Input 33 16 Output YES Input 26 5 Output NO
2 3
YES
1 second
256 megabytes
['*special problem', 'number theory', '*1800']
C. Fibonacci Wordstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe input consists of a single string of uppercase letters A-Z. The length of the string is between 1 and 10 characters, inclusive.OutputOutput "YES" or "NO".ExamplesInput HELP Output YES Input AID Output NO Input MARY Output NO Input ANNA Output YES Input MUG Output YES Input CUP Output NO Input SUM Output YES Input PRODUCT Output NO
HELP
YES
1 second
256 megabytes
['*special problem', 'implementation', '*1400']
B. DMCAtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMany people are aware of DMCA – Digital Millennium Copyright Act. But another recently proposed DMCA – Digital Millennium Calculation Act – is much less known.In this problem you need to find a root of a number according to this new DMCA law.InputThe input contains a single integer a (1 \le a \le 1000000).OutputOutput the result – an integer number.ExamplesInput 1 Output 1 Input 81 Output 9
1
1
1 second
256 megabytes
['*special problem', 'implementation', 'number theory', '*1600']
A. Is it rated - 2time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInteractionThis is an interactive problem. You need to read participants' queries from standard input and print your responses to standard output. You don't know the number of queries upfront, so you'll need to process them as you get them; you'll know you're done once you reach the end of the file.In each query, you will be asked the question, written in one line. You have to answer it correctly, patiently and without any display of emotions. Your response is case-insensitive.Please make sure to use the stream flushing operation after each response in order not to leave part of your output in some buffer.ExampleInput Is it rated? Is it rated? Is it rated? Output NO NO NO
Is it rated? Is it rated? Is it rated?
NO NO NO
1 second
256 megabytes
['*special problem', 'implementation', 'interactive', '*900']
B. Flip the Bitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a binary string a of length n. In one operation, you can select any prefix of a with an equal number of 0 and 1 symbols. Then all symbols in the prefix are inverted: each 0 becomes 1 and each 1 becomes 0.For example, suppose a=0111010000. In the first operation, we can select the prefix of length 8 since it has four 0's and four 1's: [01110100]00\to [10001011]00. In the second operation, we can select the prefix of length 2 since it has one 0 and one 1: [10]00101100\to [01]00101100. It is illegal to select the prefix of length 4 for the third operation, because it has three 0's and one 1. Can you transform the string a into the string b using some finite number of operations (possibly, none)?InputThe first line contains a single integer t (1\le t\le 10^4) — the number of test cases.The first line of each test case contains a single integer n (1\le n\le 3\cdot 10^5) — the length of the strings a and b.The following two lines contain strings a and b of length n, consisting of symbols 0 and 1.The sum of n across all test cases does not exceed 3\cdot 10^5.OutputFor each test case, output "YES" if it is possible to transform a into b, or "NO" if it is impossible. You can print each letter in any case (upper or lower).ExampleInput 5 10 0111010000 0100101100 4 0000 0000 3 001 000 12 010101010101 100110011010 6 000111 110100 Output YES YES NO YES NO NoteThe first test case is shown in the statement.In the second test case, we transform a into b by using zero operations.In the third test case, there is no legal operation, so it is impossible to transform a into b.In the fourth test case, here is one such transformation: Select the length 2 prefix to get 100101010101. Select the length 12 prefix to get 011010101010. Select the length 8 prefix to get 100101011010. Select the length 4 prefix to get 011001011010. Select the length 6 prefix to get 100110011010. In the fifth test case, the only legal operation is to transform a into 111000. From there, the only legal operation is to return to the string we started with, so we cannot transform a into b.
5 10 0111010000 0100101100 4 0000 0000 3 001 000 12 010101010101 100110011010 6 000111 110100
YES YES NO YES NO
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*1200']
A. Déjà Vutime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA palindrome is a string that reads the same backward as forward. For example, the strings "z", "aaa", "aba", and "abccba" are palindromes, but "codeforces" and "ab" are not. You hate palindromes because they give you déjà vu.There is a string s. You must insert exactly one character 'a' somewhere in s. If it is possible to create a string that is not a palindrome, you should find one example. Otherwise, you should report that it is impossible.For example, suppose s= "cbabc". By inserting an 'a', you can create "acbabc", "cababc", "cbaabc", "cbabac", or "cbabca". However "cbaabc" is a palindrome, so you must output one of the other options.InputThe first line contains a single integer t (1\le t\le 10^4) — the number of test cases.The only line of each test case contains a string s consisting of lowercase English letters.The total length of all strings does not exceed 3\cdot 10^5.OutputFor each test case, if there is no solution, output "NO".Otherwise, output "YES" followed by your constructed string of length |s|+1 on the next line. If there are multiple solutions, you may print any.You can print each letter of "YES" and "NO" in any case (upper or lower).ExampleInput 6 cbabc ab zza ba a nutforajaroftuna Output YES cbabac YES aab YES zaza YES baa NO YES nutforajarofatuna NoteThe first test case is described in the statement.In the second test case, we can make either "aab" or "aba". But "aba" is a palindrome, so "aab" is the only correct answer.In the third test case, "zaza" and "zzaa" are correct answers, but not "azza".In the fourth test case, "baa" is the only correct answer.In the fifth test case, we can only make "aa", which is a palindrome. So the answer is "NO".In the sixth test case, "anutforajaroftuna" is a palindrome, but inserting 'a' elsewhere is valid.
6 cbabc ab zza ba a nutforajaroftuna
YES cbabac YES aab YES zaza YES baa NO YES nutforajarofatuna
1 second
256 megabytes
['constructive algorithms', 'strings', '*800']
F. Balance the Cardstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA balanced bracket sequence is defined as an integer sequence that can be built with the following rules: The empty sequence is balanced. If [a_1,\ldots,a_n] and [b_1,\ldots, b_m] are balanced, then their concatenation [a_1,\ldots,a_n,b_1,\ldots,b_m] is balanced. If x is a positive integer and [a_1,\ldots,a_n] is balanced, then [x,a_1,\ldots,a_n,-x] is balanced. The positive numbers can be imagined as opening brackets and the negative numbers as closing brackets, where matching brackets must have the same type (absolute value). For example, [1, 2, -2, -1] and [1, 3, -3, 2, -2, -1] are balanced, but [1, 2, -1, -2] and [-1, 1] are not balanced.There are 2n cards. Each card has a number on the front and a number on the back. Each integer 1,-1,2,-2,\ldots,n,-n appears exactly once on the front of some card and exactly once on the back of some (not necessarily the same) card.You can reorder the cards however you like. You are not allowed to flip cards, so numbers cannot move between the front and back. Your task is to order the cards so that the sequences given by the front numbers and the back numbers are both balanced, or report that it is impossible.InputThe first line contains a single integer n (1\le n\le 2\cdot 10^5) — the number of bracket types, and half the number of cards.The next 2n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (-n\le a_i,b_i\le n, a_i\ne 0, b_i\ne 0) — the numbers on the front and back of the i-th card, respectively. Every integer 1,-1,2,-2,\ldots,n,-n appears exactly once as a_i and exactly once as b_i.OutputOn the first line, output "YES" if it's possible to reorder these cards to satisfy the condition. Otherwise, output "NO". You can print each letter in any case (upper or lower).If it is possible, on the next 2n lines output the cards in an order so that the front and back are both balanced. If there are multiple solutions, you may output any.ExamplesInput 5 1 3 -3 -5 4 -3 2 2 -1 -4 -2 5 3 -1 5 1 -4 4 -5 -2 Output YES 1 3 4 -3 -4 4 -1 -4 5 1 3 -1 2 2 -2 5 -3 -5 -5 -2 Input 2 1 1 -1 2 2 -1 -2 -2 Output NO NoteIn the first test case, the front numbers create the balanced sequence [1,4,-4,-1,5,3,2,-2,-3,-5] and the back numbers create the balanced sequence [3,-3,4,-4,1,-1,2,5,-5,-2].In the second test case, the cards are given in an order so that the front numbers are balanced, but the back numbers create the unbalanced sequence [1,2,-1,-2]. If we swapped the second and third cards, we would balance the back numbers and unbalance the front numbers. But there is no order that balances both.
5 1 3 -3 -5 4 -3 2 2 -1 -4 -2 5 3 -1 5 1 -4 4 -5 -2
YES 1 3 4 -3 -4 4 -1 -4 5 1 3 -1 2 2 -2 5 -3 -5 -5 -2
3 seconds
256 megabytes
['constructive algorithms', 'data structures', 'divide and conquer', 'geometry', 'graphs', 'implementation', '*3500']
E. 2-Coloringtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a grid with n rows and m columns. Every cell of the grid should be colored either blue or yellow.A coloring of the grid is called stupid if every row has exactly one segment of blue cells and every column has exactly one segment of yellow cells.In other words, every row must have at least one blue cell, and all blue cells in a row must be consecutive. Similarly, every column must have at least one yellow cell, and all yellow cells in a column must be consecutive. An example of a stupid coloring. Examples of clever colorings. The first coloring is missing a blue cell in the second row, and the second coloring has two yellow segments in the second column. How many stupid colorings of the grid are there? Two colorings are considered different if there is some cell that is colored differently.InputThe only line contains two integers n, m (1\le n, m\le 2021).OutputOutput a single integer — the number of stupid colorings modulo 998244353.ExamplesInput 2 2 Output 2 Input 4 3 Output 294 Input 2020 2021 Output 50657649 NoteIn the first test case, these are the only two stupid 2\times 2 colorings.
2 2
2
3 seconds
256 megabytes
['combinatorics', 'dp', 'math', '*3100']
D. Flip the Cardstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1\le i<n.To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?InputThe first line contains a single integer n (1\le n\le 2\cdot 10^5) — the number of cards.The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1\le a_i, b_i\le 2n). Every integer between 1 and 2n appears exactly once.OutputIf it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.ExamplesInput 5 3 10 6 4 1 9 5 8 2 7 Output 2 Input 2 1 2 3 4 Output -1 Input 3 1 2 3 6 4 5 Output -1 NoteIn the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1.In the second test case, it is impossible to sort the deck.
5 3 10 6 4 1 9 5 8 2 7
2
2 seconds
256 megabytes
['2-sat', 'constructive algorithms', 'data structures', 'greedy', 'sortings', 'two pointers', '*2600']
C. Travelling Salesman Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities numbered from 1 to n, and city i has beauty a_i.A salesman wants to start at city 1, visit every city exactly once, and return to city 1.For all i\ne j, a flight from city i to city j costs \max(c_i,a_j-a_i) dollars, where c_i is the price floor enforced by city i. Note that there is no absolute value. Find the minimum total cost for the salesman to complete his trip.InputThe first line contains a single integer n (2\le n\le 10^5) — the number of cities.The i-th of the next n lines contains two integers a_i, c_i (0\le a_i,c_i\le 10^9) — the beauty and price floor of the i-th city.OutputOutput a single integer — the minimum total cost.ExamplesInput 3 1 9 2 1 4 1 Output 11 Input 6 4 2 8 4 3 0 2 3 7 1 0 1 Output 13 NoteIn the first test case, we can travel in order 1\to 3\to 2\to 1. The flight 1\to 3 costs \max(c_1,a_3-a_1)=\max(9,4-1)=9. The flight 3\to 2 costs \max(c_3, a_2-a_3)=\max(1,2-4)=1. The flight 2\to 1 costs \max(c_2,a_1-a_2)=\max(1,1-2)=1. The total cost is 11, and we cannot do better.
3 1 9 2 1 4 1
11
2 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'greedy', 'shortest paths', 'sortings', 'two pointers', '*2200']
B. 3-Coloringtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Alice and Bob are playing a game. There is n\times n grid, initially empty. We refer to the cell in row i and column j by (i, j) for 1\le i, j\le n. There is an infinite supply of tokens that come in 3 colors labelled 1, 2, and 3.The game proceeds with turns as follows. Each turn begins with Alice naming one of the three colors, let's call it a. Then, Bob chooses a color b\ne a, chooses an empty cell, and places a token of color b on that cell.We say that there is a conflict if there exist two adjacent cells containing tokens of the same color. Two cells are considered adjacent if they share a common edge.If at any moment there is a conflict, Alice wins. Otherwise, if n^2 turns are completed (so that the grid becomes full) without any conflicts, Bob wins.We have a proof that Bob has a winning strategy. Play the game as Bob and win.The interactor is adaptive. That is, Alice's color choices can depend on Bob's previous moves.InteractionThe interaction begins by reading a single integer n (2\le n\le 100) — the size of the grid.The turns of the game follow. You should begin each turn by reading an integer a (1\le a\le 3) — Alice's chosen color.Then you must print three integers b,i,j (1\le b\le 3,b\ne a, 1\le i,j\le n) — denoting that Bob puts a token of color b in the cell (i, j). The cell (i, j) must not contain a token from a previous turn. If your move is invalid or loses the game, the interaction is terminated and you will receive a Wrong Answer verdict.After n^2 turns have been completed, make sure to exit immediately to avoid getting unexpected verdicts.After printing something do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack FormatTo hack, use the following format.The first line contains a single integer n (2\le n\le 100).The second line contains n^2 integers a_1,\ldots,a_{n^2} (1\le a_i\le 3), where a_i denotes Alice's color on the i-th turn.The interactor might deviate from the list of colors in your hack, but only if it forces Bob to lose.ExampleInput 2 1 2 1 3 Output 2 1 1 3 1 2 3 2 1 1 2 2 NoteThe final grid from the sample is pictured below. Bob wins because there are no two adjacent cells with tokens of the same color. \begin{matrix}2&3\\3&1\end{matrix}The sample is only given to demonstrate the input and output format. It is not guaranteed to represent an optimal strategy for Bob or the real behavior of the interactor.
2 1 2 1 3
2 1 1 3 1 2 3 2 1 1 2 2
3 seconds
256 megabytes
['constructive algorithms', 'games', 'interactive', '*1700']
A. Balance the Bitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not.You are given a binary string s of length n. Construct two balanced bracket sequences a and b of length n such that for all 1\le i\le n: if s_i=1, then a_i=b_i if s_i=0, then a_i\ne b_i If it is impossible, you should report about it.InputThe first line contains a single integer t (1\le t\le 10^4) — the number of test cases.The first line of each test case contains a single integer n (2\le n\le 2\cdot 10^5, n is even).The next line contains a string s of length n, consisting of characters 0 and 1.The sum of n across all test cases does not exceed 2\cdot 10^5.OutputIf such two balanced bracked sequences exist, output "YES" on the first line, otherwise output "NO". You can print each letter in any case (upper or lower).If the answer is "YES", output the balanced bracket sequences a and b satisfying the conditions on the next two lines.If there are multiple solutions, you may print any.ExampleInput 3 6 101101 10 1001101101 4 1100 Output YES ()()() ((())) YES ()()((())) (())()()() NO NoteIn the first test case, a="()()()" and b="((()))". The characters are equal in positions 1, 3, 4, and 6, which are the exact same positions where s_i=1.In the second test case, a="()()((()))" and b="(())()()()". The characters are equal in positions 1, 4, 5, 7, 8, 10, which are the exact same positions where s_i=1.In the third test case, there is no solution.
3 6 101101 10 1001101101 4 1100
YES ()()() ((())) YES ()()((())) (())()()() NO
1 second
256 megabytes
['constructive algorithms', 'greedy', '*1600']
B. Napoleon Caketime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis week Arkady wanted to cook some pancakes (to follow ancient traditions) and make a problem about that. But then he remembered that one can't make a problem about stacking pancakes without working at a specific IT company, so he decided to bake the Napoleon cake instead.To bake a Napoleon cake, one has to bake n dry layers first, and then put them on each other in one stack, adding some cream. Arkady started with an empty plate, and performed the following steps n times: place a new cake layer on the top of the stack; after the i-th layer is placed, pour a_i units of cream on top of the stack. When x units of cream are poured on the top of the stack, top x layers of the cake get drenched in the cream. If there are less than x layers, all layers get drenched and the rest of the cream is wasted. If x = 0, no layer gets drenched. The picture represents the first test case of the example. Help Arkady determine which layers of the cake eventually get drenched when the process is over, and which don't.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 20\,000). Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of layers in the cake.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le n) — the amount of cream poured on the cake after adding each layer.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single line with n integers. The i-th of the integers should be equal to 1 if the i-th layer from the bottom gets drenched, and 0 otherwise.ExampleInput 3 6 0 3 0 0 1 3 10 0 0 0 1 0 5 0 0 0 2 3 0 0 0 Output 1 1 0 1 1 1 0 1 1 1 1 1 0 0 1 1 0 0 0
3 6 0 3 0 0 1 3 10 0 0 0 1 0 5 0 0 0 2 3 0 0 0
1 1 0 1 1 1 0 1 1 1 1 1 0 0 1 1 0 0 0
1 second
256 megabytes
['dp', 'implementation', 'sortings', '*900']
A. Alexey and Traintime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should!Alexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment 0. Also, let's say that the train will visit n stations numbered from 1 to n along its way, and that Alexey destination is the station n.Alexey learned from the train schedule n integer pairs (a_i, b_i) where a_i is the expected time of train's arrival at the i-th station and b_i is the expected time of departure.Also, using all information he has, Alexey was able to calculate n integers tm_1, tm_2, \dots, tm_n where tm_i is the extra time the train need to travel from the station i - 1 to the station i. Formally, the train needs exactly a_i - b_{i-1} + tm_i time to travel from station i - 1 to station i (if i = 1 then b_0 is the moment the train leave the terminal, and it's equal to 0).The train leaves the station i, if both conditions are met: it's on the station for at least \left\lceil \frac{b_i - a_i}{2} \right\rceil units of time (division with ceiling); current time \ge b_i. Since Alexey spent all his energy on prediction of time delays, help him to calculate the time of arrival at the station n.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains the single integer n (1 \le n \le 100) — the number of stations.Next n lines contain two integers each: a_i and b_i (1 \le a_i < b_i \le 10^6). It's guaranteed that b_i < a_{i+1}. Next line contains n integers tm_1, tm_2, \dots, tm_n (0 \le tm_i \le 10^6).OutputFor each test case, print one integer — the time of Alexey's arrival at the last station.ExampleInput 2 2 2 4 10 12 0 2 5 1 4 7 8 9 10 13 15 19 20 1 2 3 4 5 Output 12 32 NoteIn the first test case, Alexey arrives at station 1 without any delay at the moment a_1 = 2 (since tm_1 = 0). After that, he departs at moment b_1 = 4. Finally, he arrives at station 2 with tm_2 = 2 extra time, or at the moment 12.In the second test case, Alexey arrives at the first station with tm_1 = 1 extra time, or at moment 2. The train, from one side, should stay at the station at least \left\lceil \frac{b_1 - a_1}{2} \right\rceil = 2 units of time and from the other side should depart not earlier than at moment b_1 = 4. As a result, the trains departs right at the moment 4.Using the same logic, we can figure out that the train arrives at the second station at the moment 9 and departs at the moment 10; at the third station: arrives at 14 and departs at 15; at the fourth: arrives at 22 and departs at 23. And, finally, arrives at the fifth station at 32.
2 2 2 4 10 12 0 2 5 1 4 7 8 9 10 13 15 19 20 1 2 3 4 5
12 32
1 second
256 megabytes
['implementation', '*800']
F. Cupboards Jumpstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn the house where Krosh used to live, he had n cupboards standing in a line, the i-th cupboard had the height of h_i. Krosh moved recently, but he wasn't able to move the cupboards with him. Now he wants to buy n new cupboards so that they look as similar to old ones as possible.Krosh does not remember the exact heights of the cupboards, but for every three consecutive cupboards he remembers the height difference between the tallest and the shortest of them. In other words, if the cupboards' heights were h_1, h_2, \ldots, h_n, then Krosh remembers the values w_i = \max(h_{i}, h_{i + 1}, h_{i + 2}) - \min(h_{i}, h_{i + 1}, h_{i + 2}) for all 1 \leq i \leq n - 2.Krosh wants to buy such n cupboards that all the values w_i remain the same. Help him determine the required cupboards' heights, or determine that he remembers something incorrectly and there is no suitable sequence of heights.InputThe first line contains two integers n and C (3 \leq n \leq 10^6, 0 \leq C \leq 10^{12}) — the number of cupboards and the limit on possible w_i.The second line contains n - 2 integers w_1, w_2, \ldots, w_{n - 2} (0 \leq w_i \leq C) — the values defined in the statement.OutputIf there is no suitable sequence of n cupboards, print "NO".Otherwise print "YES" in the first line, then in the second line print n integers h'_1, h'_2, \ldots, h'_n (0 \le h'_i \le 10^{18}) — the heights of the cupboards to buy, from left to right.We can show that if there is a solution, there is also a solution satisfying the constraints on heights.If there are multiple answers, print any.ExamplesInput 7 20 4 8 12 16 20 Output YES 4 8 8 16 20 4 0 Input 11 10 5 7 2 3 4 5 2 1 8 Output YES 1 1 6 8 6 5 2 0 0 1 8 Input 6 9 1 6 9 0 Output NO NoteConsider the first example: w_1 = \max(4, 8, 8) - \min(4, 8, 8) = 8 - 4 = 4 w_2 = \max(8, 8, 16) - \min(8, 8, 16) = 16 - 8 = 8 w_3 = \max(8, 16, 20) - \min(8, 16, 20) = 20 - 8 = 12 w_4 = \max(16, 20, 4) - \min(16, 20, 4) = 20 - 4 = 16 w_5 = \max(20, 4, 0) - \min(20, 4, 0) = 20 - 0 = 20 There are other possible solutions, for example, the following: 0, 1, 4, 9, 16, 25, 36.
7 20 4 8 12 16 20
YES 4 8 8 16 20 4 0
6 seconds
512 megabytes
['dp', '*3500']
E. Subset Tricktime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVanya invented an interesting trick with a set of integers.Let an illusionist have a set of positive integers S. He names a positive integer x. Then an audience volunteer must choose some subset (possibly, empty) of S without disclosing it to the illusionist. The volunteer tells the illusionist the size of the chosen subset. And here comes the trick: the illusionist guesses whether the sum of the subset elements does not exceed x. The sum of elements of an empty subset is considered to be 0.Vanya wants to prepare the trick for a public performance. He prepared some set of distinct positive integers S. Vasya wants the trick to be successful. He calls a positive number x unsuitable, if he can't be sure that the trick would be successful for every subset a viewer can choose.Vanya wants to count the number of unsuitable integers for the chosen set S.Vanya plans to try different sets S. He wants you to write a program that finds the number of unsuitable integers for the initial set S, and after each change to the set S. Vanya will make q changes to the set, and each change is one of the following two types: add a new integer a to the set S, or remove some integer a from the set S. InputThe first line contains two integers n, q (1 \leq n, q \leq 200\,000) — the size of the initial set S and the number of changes.The next line contains n distinct integers s_1, s_2, \ldots, s_n (1 \leq s_i \leq 10^{13}) — the initial elements of S.Each of the following q lines contain two integers t_i, a_i (1 \leq t_i \leq 2, 1 \leq a_i \leq 10^{13}), describing a change: If t_i = 1, then an integer a_i is added to the set S. It is guaranteed that this integer is not present in S before this operation. If t_i = 2, then an integer a_i is removed from the set S. In is guaranteed that this integer is present in S before this operation. OutputPrint q + 1 lines.In the first line print the number of unsuitable integers for the initial set S. In the next q lines print the number of unsuitable integers for S after each change.ExampleInput 3 11 1 2 3 2 1 1 5 1 6 1 7 2 6 2 2 2 3 1 10 2 5 2 7 2 10 Output 4 1 6 12 19 13 8 2 10 3 0 0 NoteIn the first example the initial set is S = \{1, 2, 3\}. For this set the trick can be unsuccessful for x \in \{1, 2, 3, 4\}. For example, if x = 4, the volunteer can choose the subset \{1, 2\} with sum 3 \leq x, and can choose the subset \{2, 3\} with sum 5 > x. However, in both cases the illusionist only know the same size of the subset (2), so he can't be sure answering making a guess. Since there is only one subset of size 3, and the sum of each subset of smaller size does not exceed 5, all x \ge 5 are suitable.
3 11 1 2 3 2 1 1 5 1 6 1 7 2 6 2 2 2 3 1 10 2 5 2 7 2 10
4 1 6 12 19 13 8 2 10 3 0 0
3 seconds
512 megabytes
['binary search', 'data structures', '*3300']
D. Tiles for Bathroomtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKostya is extremely busy: he is renovating his house! He needs to hand wallpaper, assemble furniture throw away trash.Kostya is buying tiles for bathroom today. He is standing in front of a large square stand with tiles in a shop. The stand is a square of n \times n cells, each cell of which contains a small tile with color c_{i,\,j}. The shop sells tiles in packs: more specifically, you can only buy a subsquare of the initial square.A subsquare is any square part of the stand, i. e. any set S(i_0, j_0, k) = \{c_{i,\,j}\ |\ i_0 \le i < i_0 + k, j_0 \le j < j_0 + k\} with 1 \le i_0, j_0 \le n - k + 1.Kostya still does not know how many tiles he needs, so he considers the subsquares of all possible sizes. He doesn't want his bathroom to be too colorful. Help Kostya to count for each k \le n the number of subsquares of size k \times k that have at most q different colors of tiles. Two subsquares are considered different if their location on the stand is different.InputThe first line contains two integers n and q (1 \le n \le 1500, 1 \le q \le 10) — the size of the stand and the limit on the number of distinct colors in a subsquare.Each of the next n lines contains n integers c_{i,\,j} (1 \le c_{i,\,j} \le n^2): the j-th integer in the i-th line is the color of the tile in the cell (i,\,j).OutputFor each k from 1 to n print a single integer — the number of subsquares of size k \times k with no more than q different colors.ExamplesInput 3 4 1 2 3 4 5 6 7 8 9 Output 9 4 0 Input 4 8 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 Output 16 9 4 0 NoteIn the first example all colors are distinct. Kostya doesn't want the subsquare have more than 4 colors, so he can buy any subsquare of size 1 \times 1 or 2 \times 2, but he can't buy a subsquare of size 3 \times 3.In the second example there are colors that appear multiple times. Because q = 8, Kostya can buy any subsquare of size 1 \times 1 and 2 \times 2, and any subsquare 3 \times 3, because of such subsquare has 7 different colors. He can't buy the whole stand 4 \times 4, because there are 9 colors.
3 4 1 2 3 4 5 6 7 8 9
9 4 0
5 seconds
512 megabytes
['data structures', 'sortings', 'two pointers', '*2900']
C. Matrix Sortingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two tables A and B of size n \times m. We define a sorting by column as the following: we choose a column and reorder the rows of the table by the value in this column, from the rows with the smallest value to the rows with the largest. In case there are two or more rows with equal value in this column, their relative order does not change (such sorting algorithms are called stable).You can find this behavior of sorting by column in many office software for managing spreadsheets. Petya works in one, and he has a table A opened right now. He wants to perform zero of more sortings by column to transform this table to table B.Determine if it is possible to do so, and if yes, find a sequence of columns to sort by. Note that you do not need to minimize the number of sortings.InputThe first line contains two integers n and m (1 \le n, m \le 1500) — the sizes of the tables.Each of the next n lines contains m integers a_{i,j} (1 \le a_{i, j} \le n), denoting the elements of the table A.Each of the next n lines contains m integers b_{i, j} (1 \le b_{i, j} \le n), denoting the elements of the table B.OutputIf it is not possible to transform A into B, print -1.Otherwise, first print an integer k (0 \le k \le 5000) — the number of sortings in your solution.Then print k integers c_1, \ldots, c_k (1 \le c_i \le m) — the columns, by which Petya needs to perform a sorting.We can show that if a solution exists, there is one in no more than 5000 sortings.ExamplesInput 2 2 2 2 1 2 1 2 2 2 Output 1 1Input 3 3 2 3 2 1 3 3 1 1 2 1 1 2 1 3 3 2 3 2 Output 2 1 2Input 2 2 1 1 2 1 2 1 1 1 Output -1Input 4 1 2 2 2 1 1 2 2 2 Output 1 1 NoteConsider the second example. After the sorting by the first column the table becomes\begin{matrix} 1&3&3\\ 1&1&2\\ 2&3&2. \end{matrix}After the sorting by the second column the table becomes\begin{matrix} 1&1&2\\ 1&3&3\\ 2&3&2, \end{matrix}and this is what we need.In the third test any sorting does not change anything, because the columns are already sorted.
2 2 2 2 1 2 1 2 2 2
1 1
2 seconds
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'greedy', 'two pointers', '*2600']
B. Two chandelierstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: red – brown – yellow – red – brown – yellow and so on. There are many chandeliers that differs in color set or order of colors. And the person responsible for the light made a critical mistake — they bought two different chandeliers.Since chandeliers are different, some days they will have the same color, but some days — different. Of course, it looks poor and only annoys Vasya. As a result, at the k-th time when chandeliers will light with different colors, Vasya will become very angry and, most probably, will fire the person who bought chandeliers.Your task is to calculate the day, when it happens (counting from the day chandeliers were installed). You can think that Vasya works every day without weekends and days off.InputThe first line contains three integers n, m and k (1 \le n, m \le 500\,000; 1 \le k \le 10^{12}) — the number of colors in the first and the second chandeliers and how many times colors should differ to anger Vasya.The second line contains n different integers a_i (1 \le a_i \le 2 \cdot \max(n, m)) that describe the first chandelier's sequence of colors.The third line contains m different integers b_j (1 \le b_i \le 2 \cdot \max(n, m)) that describe the second chandelier's sequence of colors.At the i-th day, the first chandelier has a color a_x, where x = ((i - 1) \mod n) + 1) and the second one has a color b_y, where y = ((i - 1) \mod m) + 1).It's guaranteed that sequence a differs from sequence b, so there are will be days when colors of chandeliers differs.OutputPrint the single integer — the index of day when Vasya will become angry.ExamplesInput 4 2 4 4 2 3 1 2 1 Output 5 Input 3 8 41 1 3 2 1 6 4 3 5 7 2 8 Output 47 Input 1 2 31 1 1 2 Output 62 NoteIn the first example, the chandeliers will have different colors at days 1, 2, 3 and 5. That's why the answer is 5.
4 2 4 4 2 3 1 2 1
5
2 seconds
256 megabytes
['binary search', 'brute force', 'chinese remainder theorem', 'math', 'number theory', '*2200']
A. Going Hometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w.Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery?InputThe first line contains the single integer n (4 \leq n \leq 200\,000) — the size of the array.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 2.5 \cdot 10^6).OutputPrint "YES" if there are such four indices, and "NO" otherwise.If such indices exist, print these indices x, y, z and w (1 \le x, y, z, w \le n).If there are multiple answers, print any of them.ExamplesInput 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NONoteIn the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6.In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3
6 2 1 5 2 7 4
YES 2 3 1 6
2 seconds
256 megabytes
['brute force', 'hashing', 'implementation', 'math', '*1800']
G. Graph Coloringtime limit per test7 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph consisting of n_1 vertices in the first part, n_2 vertices in the second part, and m edges, numbered from 1 to m. You have to color each edge into one of two colors, red and blue. You have to minimize the following value: \sum \limits_{v \in V} |r(v) - b(v)|, where V is the set of vertices of the graph, r(v) is the number of red edges incident to v, and b(v) is the number of blue edges incident to v.Sounds classical and easy, right? Well, you have to process q queries of the following format: 1 v_1 v_2 — add a new edge connecting the vertex v_1 of the first part with the vertex v_2 of the second part. This edge gets a new index as follows: the first added edge gets the index m + 1, the second — m + 2, and so on. After adding the edge, you have to print the hash of the current optimal coloring (if there are multiple optimal colorings, print the hash of any of them). Actually, this hash won't be verified, you may print any number as the answer to this query, but you may be asked to produce the coloring having this hash; 2 — print the optimal coloring of the graph with the same hash you printed while processing the previous query. The query of this type will only be asked after a query of type 1, and there will be at most 10 queries of this type. If there are multiple optimal colorings corresponding to this hash, print any of them. Note that if an edge was red or blue in some coloring, it may change its color in next colorings.The hash of the coloring is calculated as follows: let R be the set of indices of red edges, then the hash is (\sum \limits_{i \in R} 2^i) \bmod 998244353.Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.InputThe first line contains three integers n_1, n_2 and m (1 \le n_1, n_2, m \le 2 \cdot 10^5).Then m lines follow, the i-th of them contains two integers x_i and y_i (1 \le x_i \le n_1; 1 \le y_i \le n_2) meaning that the i-th edge connects the vertex x_i from the first part and the vertex y_i from the second part.The next line contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries you have to process.The next q lines contain the queries in the format introduced in the statement.Additional constraints on the input: at any moment, the graph won't contain any multiple edges; the queries of type 2 are only asked if the previous query had type 1; there are at most 10 queries of type 2. OutputTo answer a query of type 1, print one integer — the hash of the optimal coloring.To answer a query of type 2, print one line. It should begin with the integer k — the number of red edges. Then, k distinct integer should follow — the indices of red edges in your coloring, in any order. Each index should correspond to an existing edge, and the hash of the coloring you produce should be equal to the hash you printed as the answer to the previous query.If there are multiple answers to a query, you may print any of them.ExampleInput 3 4 2 1 2 3 4 10 1 1 3 1 2 3 2 1 3 3 2 1 2 4 2 1 2 1 1 1 1 2 Output 8 8 1 3 40 2 3 5 104 3 5 6 3 104 360 4 5 6 3 8
3 4 2 1 2 3 4 10 1 1 3 1 2 3 2 1 3 3 2 1 2 4 2 1 2 1 1 1 1 2
8 8 1 3 40 2 3 5 104 3 5 6 3 104 360 4 5 6 3 8
7 seconds
1024 megabytes
['data structures', 'graphs', 'interactive', '*3100']
F. Diameter Cutstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer k and an undirected tree, consisting of n vertices.The length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of this tree.You are about to remove a set of edges from the tree. The tree splits into multiple smaller trees when the edges are removed. The set of edges is valid if all the resulting trees have diameter less than or equal to k.Two sets of edges are different if there is an edge such that it appears in only one of the sets.Count the number of valid sets of edges modulo 998\,244\,353.InputThe first line contains two integers n and k (2 \le n \le 5000, 0 \le k \le n - 1) — the number of vertices of the tree and the maximum allowed diameter, respectively.Each of the next n-1 lines contains a description of an edge: two integers v and u (1 \le v, u \le n, v \neq u).The given edges form a tree.OutputPrint a single integer — the number of valid sets of edges modulo 998\,244\,353.ExamplesInput 4 3 1 2 1 3 1 4 Output 8 Input 2 0 1 2 Output 1 Input 6 2 1 6 2 4 2 6 3 6 5 6 Output 25 Input 6 3 1 2 1 5 2 3 3 4 5 6 Output 29 NoteIn the first example the diameter of the given tree is already less than or equal to k. Thus, you can choose any set of edges to remove and the resulting trees will have diameter less than or equal to k. There are 2^3 sets, including the empty one.In the second example you have to remove the only edge. Otherwise, the diameter will be 1, which is greater than 0.Here are the trees for the third and the fourth examples:
4 3 1 2 1 3 1 4
8
2 seconds
256 megabytes
['combinatorics', 'dfs and similar', 'dp', 'trees', '*2400']
E. Chaotic Mergetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s.Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order.A merge z is produced from a sequence a by the following rules: if a_i=0, then remove a letter from the beginning of x and append it to the end of z; if a_i=1, then remove a letter from the beginning of y and append it to the end of z. Two merging sequences a and b are different if there is some position i such that a_i \neq b_i.Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} \neq z_i.Let s[l,r] for some 1 \le l \le r \le |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive.Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered.Calculate \sum \limits_{1 \le l_1 \le r_1 \le |x| \\ 1 \le l_2 \le r_2 \le |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998\,244\,353.InputThe first line contains a string x (1 \le |x| \le 1000).The second line contains a string y (1 \le |y| \le 1000).Both strings consist only of lowercase Latin letters.OutputPrint a single integer — the sum of f(l_1, r_1, l_2, r_2) over 1 \le l_1 \le r_1 \le |x| and 1 \le l_2 \le r_2 \le |y| modulo 998\,244\,353.ExamplesInput aaa bb Output 24 Input code forces Output 1574 Input aaaaa aaa Output 0 Input justamassivetesttocheck howwellyouhandlemodulooperations Output 667387032 NoteIn the first example there are: 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10"; 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101"; 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010"; 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010"; 2 pairs of substrings "aaa" and "b", each with no valid merging sequences; 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010"; Thus, the answer is 6 \cdot 2 + 3 \cdot 1 + 4 \cdot 1 + 2 \cdot 2 + 2 \cdot 0 + 1 \cdot 1 = 24.
aaa bb
24
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'strings', '*2400']
D. The Number of Pairstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given three positive (greater than zero) integers c, d and x. You have to find the number of pairs of positive integers (a, b) such that equality c \cdot lcm(a, b) - d \cdot gcd(a, b) = x holds. Where lcm(a, b) is the least common multiple of a and b and gcd(a, b) is the greatest common divisor of a and b.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of one line containing three integer c, d and x (1 \le c, d, x \le 10^7).OutputFor each test case, print one integer — the number of pairs (a, b) such that the above equality holds.ExampleInput 4 1 1 3 4 2 6 3 3 7 2 7 25 Output 4 3 0 8 NoteIn the first example, the correct pairs are: (1, 4), (4,1), (3, 6), (6, 3).In the second example, the correct pairs are: (1, 2), (2, 1), (3, 3).
4 1 1 3 4 2 6 3 3 7 2 7 25
4 3 0 8
2 seconds
512 megabytes
['dp', 'math', 'number theory', '*2100']
C. Minimum Grid Pathtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's say you are standing on the XY-plane at point (0, 0) and you want to reach point (n, n).You can move only in two directions: to the right, i. e. horizontally and in the direction that increase your x coordinate, or up, i. e. vertically and in the direction that increase your y coordinate. In other words, your path will have the following structure: initially, you choose to go to the right or up; then you go some positive integer distance in the chosen direction (distances can be chosen independently); after that you change your direction (from right to up, or from up to right) and repeat the process. You don't like to change your direction too much, so you will make no more than n - 1 direction changes.As a result, your path will be a polygonal chain from (0, 0) to (n, n), consisting of at most n line segments where each segment has positive integer length and vertical and horizontal segments alternate.Not all paths are equal. You have n integers c_1, c_2, \dots, c_n where c_i is the cost of the i-th segment.Using these costs we can define the cost of the path as the sum of lengths of the segments of this path multiplied by their cost, i. e. if the path consists of k segments (k \le n), then the cost of the path is equal to \sum\limits_{i=1}^{k}{c_i \cdot length_i} (segments are numbered from 1 to k in the order they are in the path).Find the path of the minimum cost and print its cost.InputThe first line contains the single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains the single integer n (2 \le n \le 10^5).The second line of each test case contains n integers c_1, c_2, \dots, c_n (1 \le c_i \le 10^9) — the costs of each segment.It's guaranteed that the total sum of n doesn't exceed 10^5.OutputFor each test case, print the minimum possible cost of the path from (0, 0) to (n, n) consisting of at most n alternating segments.ExampleInput 3 2 13 88 3 2 3 1 5 4 3 2 1 4 Output 202 13 19 NoteIn the first test case, to reach (2, 2) you need to make at least one turn, so your path will consist of exactly 2 segments: one horizontal of length 2 and one vertical of length 2. The cost of the path will be equal to 2 \cdot c_1 + 2 \cdot c_2 = 26 + 176 = 202.In the second test case, one of the optimal paths consists of 3 segments: the first segment of length 1, the second segment of length 3 and the third segment of length 2.The cost of the path is 1 \cdot 2 + 3 \cdot 3 + 2 \cdot 1 = 13.In the third test case, one of the optimal paths consists of 4 segments: the first segment of length 1, the second one — 1, the third one — 4, the fourth one — 4. The cost of the path is 1 \cdot 4 + 1 \cdot 3 + 4 \cdot 2 + 4 \cdot 1 = 19.
3 2 13 88 3 2 3 1 5 4 3 2 1 4
202 13 19
2 seconds
256 megabytes
['brute force', 'data structures', 'greedy', 'math', '*1500']
B. Binary Removalstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.You are asked to choose some integer k (k > 0) and find a sequence a of length k such that: 1 \le a_1 < a_2 < \dots < a_k \le |s|; a_{i-1} + 1 < a_i for all i from 2 to k. The characters at positions a_1, a_2, \dots, a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} \le s'_i.Does there exist such a sequence a that the resulting string s' is sorted?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Then the descriptions of t testcases follow.The only line of each testcase contains a string s (2 \le |s| \le 100). Each character is either '0' or '1'.OutputFor each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, \dots, a_k and concatenating the parts without changing the order produces a sorted string.Otherwise, print "NO".You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).ExampleInput 5 10101011011 0000 11111 110 1100 Output YES YES YES YES NO NoteIn the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.In the second and the third testcases the sequences are already sorted.In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
5 10101011011 0000 11111 110 1100
YES YES YES YES NO
2 seconds
256 megabytes
['brute force', 'dp', 'greedy', 'implementation', '*1000']
A. Domino on Windowsilltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a board represented as a grid with 2 \times n cells.The first k_1 cells on the first row and first k_2 cells on the second row are colored in white. All other cells are colored in black.You have w white dominoes (2 \times 1 tiles, both cells are colored in white) and b black dominoes (2 \times 1 tiles, both cells are colored in black).You can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino.Can you place all w + b dominoes on the board if you can place dominoes both horizontally and vertically?InputThe first line contains a single integer t (1 \le t \le 3000) — the number of test cases.The first line of each test case contains three integers n, k_1 and k_2 (1 \le n \le 1000; 0 \le k_1, k_2 \le n).The second line of each test case contains two integers w and b (0 \le w, b \le n).OutputFor each test case, print YES if it's possible to place all w + b dominoes on the board and NO, otherwise.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).ExampleInput 5 1 0 1 1 0 1 1 1 0 0 3 0 0 1 3 4 3 1 2 2 5 4 3 3 1 Output NO YES NO YES YES NoteIn the first test case, n = 1, k_1 = 0 and k_2 = 1. It means that 2 \times 1 board has black cell (1, 1) and white cell (2, 1). So, you can't place any white domino, since there is only one white cell.In the second test case, the board of the same size 2 \times 1, but both cell are white. Since w = 0 and b = 0, so you can place 0 + 0 = 0 dominoes on the board.In the third test case, board 2 \times 3, but fully colored in black (since k_1 = k_2 = 0), so you can't place any white domino.In the fourth test case, cells (1, 1), (1, 2), (1, 3), and (2, 1) are white and other cells are black. You can place 2 white dominoes at positions ((1, 1), (2, 1)) and ((1, 2), (1, 3)) and 2 black dominoes at positions ((1, 4), (2, 4)) ((2, 2), (2, 3)).
5 1 0 1 1 0 1 1 1 0 0 3 0 0 1 3 4 3 1 2 2 5 4 3 3 1
NO YES NO YES YES
1 second
256 megabytes
['combinatorics', 'constructive algorithms', 'math', '*800']
F. Christmas Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are going to celebrate Christmas by playing a game with a tree of presents. The tree has n nodes (numbered 1 to n, with some node r as its root). There are a_i presents are hanging from the i-th node.Before beginning the game, a special integer k is chosen. The game proceeds as follows: Alice begins the game, with moves alternating each turn; in any move, the current player may choose some node (for example, i) which has depth at least k. Then, the player picks some positive number of presents hanging from that node, let's call it m (1 \le m \le a_i); the player then places these m presents on the k-th ancestor (let's call it j) of the i-th node (the k-th ancestor of vertex i is a vertex j such that i is a descendant of j, and the difference between the depth of j and the depth of i is exactly k). Now, the number of presents of the i-th node (a_i) is decreased by m, and, correspondingly, a_j is increased by m; Alice and Bob both play optimally. The player unable to make a move loses the game.For each possible root of the tree, find who among Alice or Bob wins the game.Note: The depth of a node i in a tree with root r is defined as the number of edges on the simple path from node r to node i. The depth of root r itself is zero.InputThe first line contains two space-separated integers n and k (3 \le n \le 10^5, 1 \le k \le 20).The next n-1 lines each contain two integers x and y (1 \le x, y \le n, x \neq y), denoting an undirected edge between the two nodes x and y. These edges form a tree of n nodes.The next line contains n space-separated integers denoting the array a (0 \le a_i \le 10^9).OutputOutput n integers, where the i-th integer is 1 if Alice wins the game when the tree is rooted at node i, or 0 otherwise.ExampleInput 5 1 1 2 1 3 5 2 4 3 0 3 2 4 4 Output 1 0 0 1 1 NoteLet us calculate the answer for sample input with root node as 1 and as 2.Root node 1Alice always wins in this case. One possible gameplay between Alice and Bob is: Alice moves one present from node 4 to node 3. Bob moves four presents from node 5 to node 2. Alice moves four presents from node 2 to node 1. Bob moves three presents from node 2 to node 1. Alice moves three presents from node 3 to node 1. Bob moves three presents from node 4 to node 3. Alice moves three presents from node 3 to node 1. Bob is now unable to make a move and hence loses.Root node 2Bob always wins in this case. One such gameplay is: Alice moves four presents from node 4 to node 3. Bob moves four presents from node 5 to node 2. Alice moves six presents from node 3 to node 1. Bob moves six presents from node 1 to node 2. Alice is now unable to make a move and hence loses.
5 1 1 2 1 3 5 2 4 3 0 3 2 4 4
1 0 0 1 1
2 seconds
256 megabytes
['bitmasks', 'data structures', 'dfs and similar', 'dp', 'games', 'math', 'trees', '*2500']
E. Two Housestime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i.Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B.Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable.Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist?In the problem input, you are not given the direction of each road. You are given — for each house — only the number of incoming roads to that house (k_i).You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice.Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit.See the Interaction section below for more details.InputThe first line contains a single integer n (3 \le n \le 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, \dots, k_n (0 \le k_i \le n - 1), the i-th of them represents the number of incoming roads to the i-th house.InteractionTo ask a query, print "? A B" (1 \leq A,B \leq N, A\neq B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise.To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0".After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict.You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate.If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict.After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. 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.ExamplesInput 3 1 1 1 YesOutput ? 1 2 ! 1 2Input 4 1 2 0 3 No No No No No NoOutput ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0NoteIn the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits.In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city.
3 1 1 1 Yes
? 1 2 ! 1 2
3.5 seconds
256 megabytes
['brute force', 'graphs', 'greedy', 'interactive', 'sortings', '*2200']
D. Bananas in a Microwavetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a malfunctioning microwave in which you want to put some bananas. You have n time-steps before the microwave stops working completely. At each time-step, it displays a new operation.Let k be the number of bananas in the microwave currently. Initially, k = 0. In the i-th operation, you are given three parameters t_i, x_i, y_i in the input. Based on the value of t_i, you must do one of the following:Type 1: (t_i=1, x_i, y_i) — pick an a_i, such that 0 \le a_i \le y_i, and perform the following update a_i times: k:=\lceil (k + x_i) \rceil.Type 2: (t_i=2, x_i, y_i) — pick an a_i, such that 0 \le a_i \le y_i, and perform the following update a_i times: k:=\lceil (k \cdot x_i) \rceil.Note that x_i can be a fractional value. See input format for more details. Also, \lceil x \rceil is the smallest integer \ge x.At the i-th time-step, you must apply the i-th operation exactly once.For each j such that 1 \le j \le m, output the earliest time-step at which you can create exactly j bananas. If you cannot create exactly j bananas, output -1.InputThe first line contains two space-separated integers n (1 \le n \le 200) and m (2 \le m \le 10^5).Then, n lines follow, where the i-th line denotes the operation for the i-th timestep. Each such line contains three space-separated integers t_i, x'_i and y_i (1 \le t_i \le 2, 1\le y_i\le m).Note that you are given x'_i, which is 10^5 \cdot x_i. Thus, to obtain x_i, use the formula x_i= \dfrac{x'_i} {10^5}.For type 1 operations, 1 \le x'_i \le 10^5 \cdot m, and for type 2 operations, 10^5 < x'_i \le 10^5 \cdot m.OutputPrint m integers, where the i-th integer is the earliest time-step when you can obtain exactly i bananas (or -1 if it is impossible).ExamplesInput 3 20 1 300000 2 2 400000 2 1 1000000 3 Output -1 -1 1 -1 -1 1 -1 -1 -1 3 -1 2 3 -1 -1 3 -1 -1 -1 3 Input 3 20 1 399999 2 2 412345 2 1 1000001 3 Output -1 -1 -1 1 -1 -1 -1 1 -1 -1 3 -1 -1 -1 3 -1 2 -1 3 -1 NoteIn the first sample input, let us see how to create 16 number of bananas in three timesteps. Initially, k=0. In timestep 1, we choose a_1=2, so we apply the type 1 update — k := \lceil(k+3)\rceil — two times. Hence, k is now 6. In timestep 2, we choose a_2=0, hence value of k remains unchanged. In timestep 3, we choose a_3=1, so we are applying the type 1 update k:= \lceil(k+10)\rceil once. Hence, k is now 16. It can be shown that k=16 cannot be reached in fewer than three timesteps with the given operations.In the second sample input, let us see how to create 17 number of bananas in two timesteps. Initially, k=0. In timestep 1, we choose a_1=1, so we apply the type 1 update — k := \lceil(k+3.99999)\rceil — once. Hence, k is now 4. In timestep 2, we choose a_2=1, so we apply the type 2 update — k := \lceil(k\cdot 4.12345)\rceil — once. Hence, k is now 17. It can be shown that k=17 cannot be reached in fewer than two timesteps with the given operations.
3 20 1 300000 2 2 400000 2 1 1000000 3
-1 -1 1 -1 -1 1 -1 -1 -1 3 -1 2 3 -1 -1 3 -1 -1 -1 3
3 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'implementation', '*2200']
C. Planar Reflectionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGaurang has grown up in a mystical universe. He is faced by n consecutive 2D planes. He shoots a particle of decay age k at the planes.A particle can pass through a plane directly, however, every plane produces an identical copy of the particle going in the opposite direction with a decay age k-1. If a particle has decay age equal to 1, it will NOT produce a copy.For example, if there are two planes and a particle is shot with decay age 3 (towards the right), the process is as follows: (here, D(x) refers to a single particle with decay age x) the first plane produces a D(2) to the left and lets D(3) continue on to the right; the second plane produces a D(2) to the left and lets D(3) continue on to the right; the first plane lets D(2) continue on to the left and produces a D(1) to the right; the second plane lets D(1) continue on to the right (D(1) cannot produce any copies). In total, the final multiset S of particles is \{D(3), D(2), D(2), D(1)\}. (See notes for visual explanation of this test case.)Gaurang is unable to cope up with the complexity of this situation when the number of planes is too large. Help Gaurang find the size of the multiset S, given n and k.Since the size of the multiset can be very large, you have to output it modulo 10^9+7.Note: Particles can go back and forth between the planes without colliding with each other.InputThe first line of the input contains the number of test cases t (1 \le t \le 100). Then, t lines follow, each containing two integers n and k (1 \le n, k \le 1000). Additionally, the sum of n over all test cases will not exceed 1000, and the sum of k over all test cases will not exceed 1000. All test cases in one test are different.OutputOutput t integers. The i-th of them should be equal to the answer to the i-th test case.ExamplesInput 4 2 3 2 2 3 1 1 3 Output 4 3 1 2 Input 3 1 1 1 500 500 250 Output 1 2 257950823 NoteLet us explain the first example with four test cases. Test case 1: (n = 2, k = 3) is already explained in the problem statement.See the below figure of this simulation. Each straight line with a different color represents the path of a different particle. As you can see, there are four distinct particles in the multiset. Note that the vertical spacing between reflected particles is for visual clarity only (as mentioned before, no two distinct particles collide with each other) Test case 2: (n = 2, k = 2) is explained as follows: the first plane produces a D(1) to the left and lets D(2) continue on to the right; the second plane produces a D(1) to the left and lets D(2) continue on to the right; the first plane lets D(1) continue on to the left (D(1) cannot produce any copies).Total size of multiset obtained \{D(1), D(1), D(2)\} is equal to three.Test case 3: (n = 3, k = 1), there are three planes, but decay age is only one. So no new copies are produced while the one particle passes through the planes. Hence, the answer is one.Test case 4: (n = 1, k = 3) there is only one plane. The particle produces a new copy to the left. The multiset \{D(2), D(3)\} is of size two.
4 2 3 2 2 3 1 1 3
4 3 1 2
1 second
256 megabytes
['brute force', 'data structures', 'dp', '*1600']
B. Box Fittingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n rectangles, each of height 1. Each rectangle's width is a power of 2 (i. e. it can be represented as 2^x for some non-negative integer x). You are also given a two-dimensional box of width W. Note that W may or may not be a power of 2. Moreover, W is at least as large as the width of the largest rectangle.You have to find the smallest height of this box, such that it is able to fit all the given rectangles. It is allowed to have some empty space left in this box after fitting all the rectangles.You cannot rotate the given rectangles to make them fit into the box. Moreover, any two distinct rectangles must not overlap, i. e., any two distinct rectangles must have zero intersection area.See notes for visual explanation of sample input.InputThe first line of input contains one integer t (1 \le t \le 5 \cdot 10^3) — the number of test cases. Each test case consists of two lines.For each test case: the first line contains two integers n (1 \le n \le 10^5) and W (1 \le W \le 10^9); the second line contains n integers w_1, w_2, \dots, w_n (1 \le w_i \le 10^6), where w_i is the width of the i-th rectangle. Each w_i is a power of 2; additionally, \max\limits_{i=1}^{n} w_i \le W. The sum of n over all test cases does not exceed 10^5.OutputOutput t integers. The i-th integer should be equal to the answer to the i-th test case — the smallest height of the box.ExampleInput 2 5 16 1 2 8 4 8 6 10 2 8 8 2 2 8 Output 2 3 NoteFor the first test case in the sample input, the following figure shows one way to fit the given five rectangles into the 2D box with minimum height: In the figure above, the number inside each rectangle is its width. The width of the 2D box is 16 (indicated with arrow below). The minimum height required for the 2D box in this case is 2 (indicated on the left).In the second test case, you can have a minimum height of three by keeping two blocks (one each of widths eight and two) on each of the three levels.
2 5 16 1 2 8 4 8 6 10 2 8 8 2 2 8
2 3
1 second
256 megabytes
['binary search', 'bitmasks', 'data structures', 'greedy', '*1300']
A. GCD Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe \text{gcdSum} of a positive integer is the gcd of that integer with its sum of digits. Formally, \text{gcdSum}(x) = gcd(x, \text{ sum of digits of } x) for a positive integer x. gcd(a, b) denotes the greatest common divisor of a and b — the largest integer d such that both integers a and b are divisible by d.For example: \text{gcdSum}(762) = gcd(762, 7 + 6 + 2)=gcd(762,15) = 3.Given an integer n, find the smallest integer x \ge n such that \text{gcdSum}(x) > 1.InputThe first line of input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t lines follow, each containing a single integer n (1 \le n \le 10^{18}).All test cases in one test are different.OutputOutput t lines, where the i-th line is a single integer containing the answer to the i-th test case.ExampleInput 3 11 31 75 Output 12 33 75 NoteLet us explain the three test cases in the sample.Test case 1: n = 11: \text{gcdSum}(11) = gcd(11, 1 + 1) = gcd(11,\ 2) = 1.\text{gcdSum}(12) = gcd(12, 1 + 2) = gcd(12,\ 3) = 3.So the smallest number \ge 11 whose gcdSum > 1 is 12.Test case 2: n = 31: \text{gcdSum}(31) = gcd(31, 3 + 1) = gcd(31,\ 4) = 1.\text{gcdSum}(32) = gcd(32, 3 + 2) = gcd(32,\ 5) = 1.\text{gcdSum}(33) = gcd(33, 3 + 3) = gcd(33,\ 6) = 3.So the smallest number \ge 31 whose gcdSum > 1 is 33.Test case 3: \ n = 75: \text{gcdSum}(75) = gcd(75, 7 + 5) = gcd(75,\ 12) = 3.The \text{gcdSum} of 75 is already > 1. Hence, it is the answer.
3 11 31 75
12 33 75
1 second
256 megabytes
['brute force', 'math', '*800']
E2. Square-Free Division (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference is that in this version 0 \leq k \leq 20.There is an array a_1, a_2, \ldots, a_n of n positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square.Moreover, it is allowed to do at most k such operations before the division: choose a number in the array and change its value to any positive integer.What is the minimum number of continuous segments you should use if you will make changes optimally?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 two integers n, k (1 \le n \le 2 \cdot 10^5, 0 \leq k \leq 20).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^7).It's guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print a single integer  — the answer to the problem.ExampleInput 35 218 6 2 4 111 46 2 2 8 9 1 3 6 3 9 71 01Output 1 2 1 NoteIn the first test case it is possible to change the array this way: [\underline{3}, 6, 2, 4, \underline{5}] (changed elements are underlined). After that the array does not need to be divided, so the answer is 1.In the second test case it is possible to change the array this way: [6, 2, \underline{3}, 8, 9, \underline{5}, 3, 6, \underline{10}, \underline{11}, 7]. After that such division is optimal: [6, 2, 3] [8, 9, 5, 3, 6, 10, 11, 7]
35 218 6 2 4 111 46 2 2 8 9 1 3 6 3 9 71 01
1 2 1
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', 'math', 'number theory', 'two pointers', '*2500']
E1. Square-Free Division (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference is that in this version k = 0.There is an array a_1, a_2, \ldots, a_n of n positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square.Moreover, it is allowed to do at most k such operations before the division: choose a number in the array and change its value to any positive integer. But in this version k = 0, so it is not important.What is the minimum number of continuous segments you should use if you will make changes optimally?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 two integers n, k (1 \le n \le 2 \cdot 10^5, k = 0).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^7).It's guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print a single integer  — the answer to the problem.ExampleInput 35 018 6 2 4 15 06 8 1 24 81 01Output 3 2 1 NoteIn the first test case the division may be as follows: [18, 6] [2, 4] [1]
35 018 6 2 4 15 06 8 1 24 81 01
3 2 1
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', 'math', 'number theory', 'two pointers', '*1700']
D. Geniustime limit per test2 secondsmemory limit per test32 megabytesinputstandard inputoutputstandard outputPlease note the non-standard memory limit.There are n problems numbered with integers from 1 to n. i-th problem has the complexity c_i = 2^i, tag tag_i and score s_i.After solving the problem i it's allowed to solve problem j if and only if \text{IQ} < |c_i - c_j| and tag_i \neq tag_j. After solving it your \text{IQ} changes and becomes \text{IQ} = |c_i - c_j| and you gain |s_i - s_j| points.Any problem can be the first. You can solve problems in any order and as many times as you want.Initially your \text{IQ} = 0. Find the maximum number of points that can be earned.InputThe first line contains a single integer t (1 \le t \le 100)  — the number of test cases. The first line of each test case contains an integer n (1 \le n \le 5000)  — the number of problems.The second line of each test case contains n integers tag_1, tag_2, \ldots, tag_n (1 \le tag_i \le n)  — tags of the problems.The third line of each test case contains n integers s_1, s_2, \ldots, s_n (1 \le s_i \le 10^9)  — scores of the problems.It's guaranteed that sum of n over all test cases does not exceed 5000.OutputFor each test case print a single integer  — the maximum number of points that can be earned.ExampleInput 5 4 1 2 3 4 5 10 15 20 4 1 2 1 2 5 10 15 20 4 2 2 4 1 2 8 19 1 2 1 1 6 9 1 1 666 Output 35 30 42 0 0 NoteIn the first test case optimal sequence of solving problems is as follows: 1 \rightarrow 2, after that total score is 5 and \text{IQ} = 2 2 \rightarrow 3, after that total score is 10 and \text{IQ} = 4 3 \rightarrow 1, after that total score is 20 and \text{IQ} = 6 1 \rightarrow 4, after that total score is 35 and \text{IQ} = 14 In the second test case optimal sequence of solving problems is as follows: 1 \rightarrow 2, after that total score is 5 and \text{IQ} = 2 2 \rightarrow 3, after that total score is 10 and \text{IQ} = 4 3 \rightarrow 4, after that total score is 15 and \text{IQ} = 8 4 \rightarrow 1, after that total score is 35 and \text{IQ} = 14 In the third test case optimal sequence of solving problems is as follows: 1 \rightarrow 3, after that total score is 17 and \text{IQ} = 6 3 \rightarrow 4, after that total score is 35 and \text{IQ} = 8 4 \rightarrow 2, after that total score is 42 and \text{IQ} = 12
5 4 1 2 3 4 5 10 15 20 4 1 2 1 2 5 10 15 20 4 2 2 4 1 2 8 19 1 2 1 1 6 9 1 1 666
35 30 42 0 0
2 seconds
32 megabytes
['bitmasks', 'dp', 'graphs', 'number theory', '*2500']
C2. k-LCM (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is the hard version of the problem. The only difference is that in this version 3 \le k \le n.You are given a positive integer n. Find k positive integers a_1, a_2, \ldots, a_k, such that: a_1 + a_2 + \ldots + a_k = n LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2} Here LCM is the least common multiple of numbers a_1, a_2, \ldots, a_k.We can show that for given constraints the answer always exists.InputThe first line contains a single integer t (1 \le t \le 10^4)  — the number of test cases.The only line of each test case contains two integers n, k (3 \le n \le 10^9, 3 \le k \le n).It is guaranteed that the sum of k over all test cases does not exceed 10^5.OutputFor each test case print k positive integers a_1, a_2, \ldots, a_k, for which all conditions are satisfied.ExampleInput 2 6 4 9 5 Output 1 2 2 1 1 3 3 1 1
2 6 4 9 5
1 2 2 1 1 3 3 1 1
1 second
256 megabytes
['constructive algorithms', 'math', '*1600']
C1. k-LCM (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is the easy version of the problem. The only difference is that in this version k = 3.You are given a positive integer n. Find k positive integers a_1, a_2, \ldots, a_k, such that: a_1 + a_2 + \ldots + a_k = n LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2} Here LCM is the least common multiple of numbers a_1, a_2, \ldots, a_k.We can show that for given constraints the answer always exists.InputThe first line contains a single integer t (1 \le t \le 10^4)  — the number of test cases.The only line of each test case contains two integers n, k (3 \le n \le 10^9, k = 3).OutputFor each test case print k positive integers a_1, a_2, \ldots, a_k, for which all conditions are satisfied.ExampleInput 3 3 3 8 3 14 3 Output 1 1 1 4 2 2 2 6 6
3 3 3 8 3 14 3
1 1 1 4 2 2 2 6 6
1 second
256 megabytes
['constructive algorithms', 'math', '*1200']
B. M-arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \ldots, a_n consisting of n positive integers and a positive integer m.You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.Let's call an array m-divisible if for each two adjacent numbers in the array (two numbers on the positions i and i+1 are called adjacent for each i) their sum is divisible by m. An array of one element is m-divisible.Find the smallest number of m-divisible arrays that a_1, a_2, \ldots, a_n is possible to divide into.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 two integers n, m (1 \le n \le 10^5, 1 \le m \le 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).It is guaranteed that the sum of n and the sum of m over all test cases do not exceed 10^5.OutputFor each test case print the answer to the problem.ExampleInput 4 6 4 2 2 8 6 9 4 10 8 1 1 1 5 2 4 4 8 6 7 1 1 666 2 2 2 4 Output 3 6 1 1 NoteIn the first test case we can divide the elements as follows: [4, 8]. It is a 4-divisible array because 4+8 is divisible by 4. [2, 6, 2]. It is a 4-divisible array because 2+6 and 6+2 are divisible by 4. [9]. It is a 4-divisible array because it consists of one element.
4 6 4 2 2 8 6 9 4 10 8 1 1 1 5 2 4 4 8 6 7 1 1 666 2 2 2 4
3 6 1 1
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*1200']
A. Meximizationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n and an array a_1, a_2, \ldots, a_n. You should reorder the elements of the array a in such way that the sum of \textbf{MEX} on prefixes (i-th prefix is a_1, a_2, \ldots, a_i) is maximized.Formally, you should find an array b_1, b_2, \ldots, b_n, such that the sets of elements of arrays a and b are equal (it is equivalent to array b can be found as an array a with some reordering of its elements) and \sum\limits_{i=1}^{n} \textbf{MEX}(b_1, b_2, \ldots, b_i) is maximized.\textbf{MEX} of a set of nonnegative integers is the minimal nonnegative integer such that it is not in the set.For example, \textbf{MEX}(\{1, 2, 3\}) = 0, \textbf{MEX}(\{0, 1, 2, 4, 5\}) = 3.InputThe first line contains a single integer t (1 \le t \le 100)  — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 100).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 100).OutputFor each test case print an array b_1, b_2, \ldots, b_n  — the optimal reordering of a_1, a_2, \ldots, a_n, so the sum of \textbf{MEX} on its prefixes is maximized.If there exist multiple optimal answers you can find any.ExampleInput 3 7 4 2 0 1 3 3 7 5 2 2 8 6 9 1 0 Output 0 1 2 3 4 7 3 2 6 8 9 2 0 NoteIn the first test case in the answer \textbf{MEX} for prefixes will be: \textbf{MEX}(\{0\}) = 1 \textbf{MEX}(\{0, 1\}) = 2 \textbf{MEX}(\{0, 1, 2\}) = 3 \textbf{MEX}(\{0, 1, 2, 3\}) = 4 \textbf{MEX}(\{0, 1, 2, 3, 4\}) = 5 \textbf{MEX}(\{0, 1, 2, 3, 4, 7\}) = 5 \textbf{MEX}(\{0, 1, 2, 3, 4, 7, 3\}) = 5 The sum of \textbf{MEX} = 1 + 2 + 3 + 4 + 5 + 5 + 5 = 25. It can be proven, that it is a maximum possible sum of \textbf{MEX} on prefixes.
3 7 4 2 0 1 3 3 7 5 2 2 8 6 9 1 0
0 1 2 3 4 7 3 2 6 8 9 2 0
1 second
256 megabytes
['brute force', 'data structures', 'greedy', 'sortings', '*800']
B. Max and Mextime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a multiset S initially consisting of n distinct non-negative integers. A multiset is a set, that can contain some elements multiple times.You will perform the following operation k times: Add the element \lceil\frac{a+b}{2}\rceil (rounded up) into S, where a = \operatorname{mex}(S) and b = \max(S). If this number is already in the set, it is added again. Here \operatorname{max} of a multiset denotes the maximum integer in the multiset, and \operatorname{mex} of a multiset denotes the smallest non-negative integer that is not present in the multiset. For example: \operatorname{mex}(\{1,4,0,2\})=3; \operatorname{mex}(\{2,5,1\})=0. Your task is to calculate the number of distinct elements in S after k operations will be done.InputThe input consists of multiple test cases. The first line contains a single integer t (1\le t\le 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n, k (1\le n\le 10^5, 0\le k\le 10^9) — the initial size of the multiset S and how many operations you need to perform.The second line of each test case contains n distinct integers a_1,a_2,\dots,a_n (0\le a_i\le 10^9) — the numbers in the initial multiset.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print the number of distinct elements in S after k operations will be done.ExampleInput 5 4 1 0 1 3 4 3 1 0 1 4 3 0 0 1 4 3 2 0 1 2 3 2 1 2 3 Output 4 4 3 5 3 NoteIn the first test case, S=\{0,1,3,4\}, a=\operatorname{mex}(S)=2, b=\max(S)=4, \lceil\frac{a+b}{2}\rceil=3. So 3 is added into S, and S becomes \{0,1,3,3,4\}. The answer is 4.In the second test case, S=\{0,1,4\}, a=\operatorname{mex}(S)=2, b=\max(S)=4, \lceil\frac{a+b}{2}\rceil=3. So 3 is added into S, and S becomes \{0,1,3,4\}. The answer is 4.
5 4 1 0 1 3 4 3 1 0 1 4 3 0 0 1 4 3 2 0 1 2 3 2 1 2 3
4 4 3 5 3
1 second
256 megabytes
['math', '*1100']
A. Split it!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKawashiro Nitori is a girl who loves competitive programming.One day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem.Given a string s and a parameter k, you need to check if there exist k+1 non-empty strings a_1,a_2...,a_{k+1}, such that s=a_1+a_2+\ldots +a_k+a_{k+1}+R(a_k)+R(a_{k-1})+\ldots+R(a_{1}). Here + represents concatenation. We define R(x) as a reversed string x. For example R(abcd) = dcba. Note that in the formula above the part R(a_{k+1}) is intentionally skipped.InputThe input consists of multiple test cases. The first line contains a single integer t (1\le t\le 100)  — the number of test cases. The description of the test cases follows.The first line of each test case description contains two integers n, k (1\le n\le 100, 0\le k\le \lfloor \frac{n}{2} \rfloor)  — the length of the string s and the parameter k.The second line of each test case description contains a single string s of length n, consisting of lowercase English letters.OutputFor each test case, print "YES" (without quotes), if it is possible to find a_1,a_2,\ldots,a_{k+1}, and "NO" (without quotes) otherwise.You can print letters in any case (upper or lower).ExampleInput 7 5 1 qwqwq 2 1 ab 3 1 ioi 4 2 icpc 22 0 dokidokiliteratureclub 19 8 imteamshanghaialice 6 3 aaaaaa Output YES NO YES NO YES NO NO NoteIn the first test case, one possible solution is a_1=qw and a_2=q.In the third test case, one possible solution is a_1=i and a_2=o.In the fifth test case, one possible solution is a_1=dokidokiliteratureclub.
7 5 1 qwqwq 2 1 ab 3 1 ioi 4 2 icpc 22 0 dokidokiliteratureclub 19 8 imteamshanghaialice 6 3 aaaaaa
YES NO YES NO YES NO NO
1 second
256 megabytes
['brute force', 'constructive algorithms', 'greedy', 'strings', '*900']