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
|
---|---|---|---|---|---|
D. Zero Remainder Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n positive integers.Initially, you have an integer x = 0. During one move, you can do one of the following two operations: Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1). Just increase x by 1 (x := x + 1). The first operation can be applied no more than once to each i from 1 to n.Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by k (the value k is given).You have to answer t independent test cases. InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains two integers n and k (1 \le n \le 2 \cdot 10^5; 1 \le k \le 10^9) — the length of a and the required divisior. The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the i-th element of a.It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by k.ExampleInput
5
4 3
1 2 1 3
10 6
8 7 1 8 3 7 5 10 8 9
5 10
20 100 50 20 100500
10 25
24 24 24 24 24 24 24 24 24 24
8 8
1 2 3 4 5 6 7 8
Output
6
18
0
227
8
NoteConsider the first test case of the example: x=0, a = [1, 2, 1, 3]. Just increase x; x=1, a = [1, 2, 1, 3]. Add x to the second element and increase x; x=2, a = [1, 3, 1, 3]. Add x to the third element and increase x; x=3, a = [1, 3, 3, 3]. Add x to the fourth element and increase x; x=4, a = [1, 3, 3, 6]. Just increase x; x=5, a = [1, 3, 3, 6]. Add x to the first element and increase x; x=6, a = [6, 3, 3, 6]. We obtained the required array. Note that you can't add x to the same element more than once. | 5
4 3
1 2 1 3
10 6
8 7 1 8 3 7 5 10 8 9
5 10
20 100 50 20 100500
10 25
24 24 24 24 24 24 24 24 24 24
8 8
1 2 3 4 5 6 7 8
| 6 18 0 227 8 | 2 seconds | 256 megabytes | ['math', 'sortings', 'two pointers', '*1400'] |
C. Move Bracketstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of \frac{n}{2} opening brackets '(' and \frac{n}{2} closing brackets ')'.In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remove the i-th character of s and insert it before or after all remaining characters of s).Your task is to find the minimum number of moves required to obtain regular bracket sequence from s. It can be proved that the answer always exists under the given constraints.Recall what the regular bracket sequence is: "()" is regular bracket sequence; if s is regular bracket sequence then "(" + s + ")" is regular bracket sequence; if s and t are regular bracket sequences then s + t is regular bracket sequence. For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2000) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (2 \le n \le 50) — the length of s. It is guaranteed that n is even. The second line of the test case containg the string s consisting of \frac{n}{2} opening and \frac{n}{2} closing brackets.OutputFor each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from s. It can be proved that the answer always exists under the given constraints.ExampleInput
4
2
)(
4
()()
8
())()()(
10
)))((((())
Output
1
0
1
3
NoteIn the first test case of the example, it is sufficient to move the first bracket to the end of the string.In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain "((()))(())". | 4
2
)(
4
()()
8
())()()(
10
)))((((())
| 1 0 1 3 | 1 second | 256 megabytes | ['greedy', 'strings', '*1000'] |
B. Multiply by 2, divide by 6time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder).Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow. The only line of the test case contains one integer n (1 \le n \le 10^9).OutputFor each test case, print the answer — the minimum number of moves needed to obtain 1 from n if it's possible to do that or -1 if it's impossible to obtain 1 from n.ExampleInput
7
1
2
3
12
12345
15116544
387420489
Output
0
-1
2
-1
-1
12
36
NoteConsider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer 15116544: Divide by 6 and get 2519424; divide by 6 and get 419904; divide by 6 and get 69984; divide by 6 and get 11664; multiply by 2 and get 23328; divide by 6 and get 3888; divide by 6 and get 648; divide by 6 and get 108; multiply by 2 and get 216; divide by 6 and get 36; divide by 6 and get 6; divide by 6 and get 1. | 7
1
2
3
12
12345
15116544
387420489
| 0 -1 2 -1 -1 12 36 | 1 second | 256 megabytes | ['math', '*900'] |
A. Required Remaindertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers x, y and n. Your task is to find the maximum integer k such that 0 \le k \le n that k \bmod x = y, where \bmod is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.You have to answer t independent test cases. It is guaranteed that such k exists for each test case.InputThe first line of the input contains one integer t (1 \le t \le 5 \cdot 10^4) — the number of test cases. The next t lines contain test cases.The only line of the test case contains three integers x, y and n (2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9).It can be shown that such k always exists under the given constraints.OutputFor each test case, print the answer — maximum non-negative integer k such that 0 \le k \le n and k \bmod x = y. It is guaranteed that the answer always exists.ExampleInput
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
NoteIn the first test case of the example, the answer is 12339 = 7 \cdot 1762 + 5 (thus, 12339 \bmod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7. | 7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
| 12339 0 15 54306 999999995 185 999999998 | 1 second | 256 megabytes | ['math', '*800'] |
G. Pawnstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a chessboard consisting of n rows and n columns. Rows are numbered from bottom to top from 1 to n. Columns are numbered from left to right from 1 to n. The cell at the intersection of the x-th column and the y-th row is denoted as (x, y). Furthermore, the k-th column is a special column. Initially, the board is empty. There are m changes to the board. During the i-th change one pawn is added or removed from the board. The current board is good if we can move all pawns to the special column by the followings rules: Pawn in the cell (x, y) can be moved to the cell (x, y + 1), (x - 1, y + 1) or (x + 1, y + 1); You can make as many such moves as you like; Pawns can not be moved outside the chessboard; Each cell can not contain more than one pawn. The current board may not always be good. To fix it, you can add new rows to the board. New rows are added at the top, i. e. they will have numbers n+1, n+2, n+3, \dots.After each of m changes, print one integer — the minimum number of rows which you have to add to make the board good.InputThe first line contains three integers n, k and m (1 \le n, m \le 2 \cdot 10^5; 1 \le k \le n) — the size of the board, the index of the special column and the number of changes respectively.Then m lines follow. The i-th line contains two integers x and y (1 \le x, y \le n) — the index of the column and the index of the row respectively. If there is no pawn in the cell (x, y), then you add a pawn to this cell, otherwise — you remove the pawn from this cell.OutputAfter each change print one integer — the minimum number of rows which you have to add to make the board good.ExampleInput
5 3 5
4 4
3 5
2 4
3 4
3 5
Output
0
1
2
2
1
| 5 3 5
4 4
3 5
2 4
3 4
3 5
| 0 1 2 2 1 | 3 seconds | 256 megabytes | ['data structures', 'divide and conquer', 'greedy', '*2600'] |
F. Network Coveragetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).All network stations have capacities: the i-th station can provide the connection to at most b_i households.Now the government asks you to check can the designed stations meet the needs of all cities or not — that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains the single integer n (2 \le n \le 10^6) — the number of cities and stations.The second line of each test case contains n integers (1 \le a_i \le 10^9) — the number of households in the i-th city.The third line of each test case contains n integers (1 \le b_i \le 10^9) — the capacities of the designed stations.It's guaranteed that the sum of n over test cases doesn't exceed 10^6.OutputFor each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).ExampleInput
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
NoteIn the first test case: the first network station can provide 2 connections to the first city and 1 connection to the second city; the second station can provide 2 connections to the second city and 1 connection to the third city; the third station can provide 3 connections to the third city. In the second test case: the 1-st station can provide 2 connections to the 1-st city; the 2-nd station can provide 3 connections to the 2-nd city; the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station. In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total. | 5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
| YES YES NO YES YES | 2 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'data structures', 'greedy', '*2400'] |
E. Sum of Digitstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet f(x) be the sum of digits of a decimal number x.Find the smallest non-negative integer x such that f(x) + f(x + 1) + \dots + f(x + k) = n.InputThe first line contains one integer t (1 \le t \le 150) — the number of test cases.Each test case consists of one line containing two integers n and k (1 \le n \le 150, 0 \le k \le 9). OutputFor each test case, print one integer without leading zeroes. If there is no such x that f(x) + f(x + 1) + \dots + f(x + k) = n, print -1; otherwise, print the minimum x meeting that constraint.ExampleInput
7
1 0
1 1
42 7
13 7
99 1
99 0
99 2
Output
1
0
4
-1
599998
99999999999
7997
| 7
1 0
1 1
42 7
13 7
99 1
99 0
99 2
| 1 0 4 -1 599998 99999999999 7997 | 2 seconds | 512 megabytes | ['brute force', 'constructive algorithms', 'dp', 'greedy', '*2200'] |
D. Maximum Sum on Even Positionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. Indices of the array start from zero (i. e. the first element is a_0, the second one is a_1, and so on).You can reverse at most one subarray (continuous subsegment) of this array. Recall that the subarray of a with borders l and r is a[l; r] = a_l, a_{l + 1}, \dots, a_{r}.Your task is to reverse such a subarray that the sum of elements on even positions of the resulting array is maximized (i. e. the sum of elements a_0, a_2, \dots, a_{2k} for integer k = \lfloor\frac{n-1}{2}\rfloor should be maximum possible).You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the length of a. The second line of the test case contains n integers a_0, a_1, \dots, a_{n-1} (1 \le a_i \le 10^9), where a_i is the i-th element of a.It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer on the separate line — the maximum possible sum of elements on even positions after reversing at most one subarray (continuous subsegment) of a.ExampleInput
4
8
1 7 3 4 7 6 2 9
5
1 2 1 2 1
10
7 8 4 5 7 6 8 9 7 3
4
3 1 2 1
Output
26
5
37
5
| 4
8
1 7 3 4 7 6 2 9
5
1 2 1 2 1
10
7 8 4 5 7 6 8 9 7 3
4
3 1 2 1
| 26 5 37 5 | 2 seconds | 256 megabytes | ['divide and conquer', 'dp', 'greedy', 'implementation', '*1600'] |
C. Pluses and Minusestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: res = 0for init = 0 to inf cur = init ok = true for i = 1 to |s| res = res + 1 if s[i] == '+' cur = cur + 1 else cur = cur - 1 if cur < 0 ok = false break if ok breakNote that the inf denotes infinity, and the characters of the string are numbered from 1 to |s|.You have to calculate the value of the res after the process ends.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.The only lines of each test case contains string s (1 \le |s| \le 10^6) consisting only of characters + and -.It's guaranteed that sum of |s| over all test cases doesn't exceed 10^6.OutputFor each test case print one integer — the value of the res after the process ends.ExampleInput
3
--+-
---
++--+-
Output
7
9
6
| 3
--+-
---
++--+-
| 7 9 6 | 2 seconds | 256 megabytes | ['math', '*1300'] |
B. 01 Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlica and Bob are playing a game.Initially they have a binary string s consisting of only characters 0 and 1.Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string s and delete them. For example, if s = 1011001 then the following moves are possible: delete s_1 and s_2: \textbf{10}11001 \rightarrow 11001; delete s_2 and s_3: 1\textbf{01}1001 \rightarrow 11001; delete s_4 and s_5: 101\textbf{10}01 \rightarrow 10101; delete s_6 and s_7: 10110\textbf{01} \rightarrow 10110. If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.InputFirst line contains one integer t (1 \le t \le 1000) — the number of test cases.Only line of each test case contains one string s (1 \le |s| \le 100), consisting of only characters 0 and 1.OutputFor each test case print answer in the single line.If Alice can win print DA (YES in Russian) in any register. Otherwise print NET (NO in Russian) in any register.ExampleInput
3
01
1111
0011
Output
DA
NET
NET
NoteIn the first test case after Alice's move string s become empty and Bob can not make any move.In the second test case Alice can not make any move initially.In the third test case after Alice's move string s turn into 01. Then, after Bob's move string s become empty and Alice can not make any move. | 3
01
1111
0011
| DA NET NET | 1 second | 256 megabytes | ['games', '*900'] |
A. Donut Shopstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are two rival donut shops.The first shop sells donuts at retail: each donut costs a dollars.The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them is greater or equal to x.You want to determine two positive integer values: how many donuts can you buy so that they are strictly cheaper in the first shop than in the second shop? how many donuts can you buy so that they are strictly cheaper in the second shop than in the first shop? If any of these values doesn't exist then that value should be equal to -1. If there are multiple possible answers, then print any of them.The printed values should be less or equal to 10^9. It can be shown that under the given constraints such values always exist if any values exist at all.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Each of the next t lines contains three integers a, b and c (1 \le a \le 10^9, 2 \le b \le 10^9, 1 \le c \le 10^9).OutputFor each testcase print two positive integers. For both shops print such x that buying x donuts in this shop is strictly cheaper than buying x donuts in the other shop. x should be greater than 0 and less or equal to 10^9.If there is no such x, then print -1. If there are multiple answers, then print any of them.ExampleInput
4
5 10 4
4 5 20
2 2 3
1000000000 1000000000 1000000000
Output
-1 20
8 -1
1 2
-1 1000000000
NoteIn the first testcase buying any number of donuts will be cheaper in the second shop. For example, for 3 or 5 donuts you'll have to buy a box of 10 donuts for 4 dollars. 3 or 5 donuts in the first shop would cost you 15 or 25 dollars, respectively, however. For 20 donuts you'll have to buy two boxes for 8 dollars total. Note that 3 and 5 are also valid answers for the second shop, along with many other answers.In the second testcase buying any number of donuts will be either cheaper in the first shop or the same price. 8 donuts cost 32 dollars in the first shop and 40 dollars in the second shop (because you have to buy two boxes). 10 donuts will cost 40 dollars in both shops, so 10 is not a valid answer for any of the shops.In the third testcase 1 donut costs 2 and 3 dollars, respectively. 2 donuts cost 4 and 3 dollars. Thus, 1 is a valid answer for the first shop and 2 is a valid answer for the second shop.In the fourth testcase 10^9 donuts cost 10^{18} dollars in the first shop and 10^9 dollars in the second shop. | 4
5 10 4
4 5 20
2 2 3
1000000000 1000000000 1000000000
| -1 20 8 -1 1 2 -1 1000000000 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', '*1000'] |
F. Omkar and Modestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRay lost his array and needs to find it by asking Omkar. Omkar is willing to disclose that the array has the following qualities: The array has n (1 \le n \le 2 \cdot 10^5) elements. Every element in the array a_i is an integer in the range 1 \le a_i \le 10^9. The array is sorted in nondecreasing order. Ray is allowed to send Omkar a series of queries. A query consists of two integers, l and r such that 1 \le l \le r \le n. Omkar will respond with two integers, x and f. x is the mode of the subarray from index l to index r inclusive. The mode of an array is defined by the number that appears the most frequently. If there are multiple numbers that appear the most number of times, the smallest such number is considered to be the mode. f is the amount of times that x appears in the queried subarray.The array has k (1 \le k \le \min(25000,n)) distinct elements. However, due to Ray's sins, Omkar will not tell Ray what k is. Ray is allowed to send at most 4k queries.Help Ray find his lost array.InputThe only line of the input contains a single integer n (1 \le n \le 2 \cdot 10^5), which equals to the length of the array that you are trying to find.InteractionThe interaction starts with reading n.Then you can make one type of query: "? \enspace l \enspace r" (1 \le l \le r \le n) where l and r are the bounds of the subarray that you wish to query. The answer to each query will be in the form "x \enspace f" where x is the mode of the subarray and f is the number of times x appears in the subarray. x satisfies (1 \leq x \leq 10^9). f satisfies (1 \leq f \leq r-l+1). If you make more than 4k queries or violate the number range in the query, you will get an output "-1." If you terminate after receiving the response "-1", you will get the "Wrong answer" verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream. To output your answer, print: "! \enspace a_1 \enspace a_2 \enspace \ldots \enspace a_{n-1} \enspace a_n" which is an exclamation point followed by the array with a space between every element. And quit after that. This query is not counted towards the 4k queries limit.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 documentation for other languages.Hack FormatTo hack, output 1 integer on the first line, n (1 \le n \le 2 \cdot 10^5). On the second line output n integers a_1, a_2, \ldots, a_{n-1}, a_n separated by a space such that there are at most 25000 distinct numbers and a_j \le a_{j+1} for all j from 1 to n-1.ExampleInput
6
2 2
2 2
3 2
2 1
Output
? 1 6
? 1 3
? 4 6
? 3 4
! 1 2 2 3 3 4NoteThe first query is l=1 and r=6. The mode is 2, and 2 appears 2 times, so x=2 and f=2. Note that 3 also appears two times, but 2 is outputted because 2 is smaller.The second query is l=1 and r=3. The mode is 2 and 2 appears twice in the subarray with indices [1,3].The third query is l=4 and r=6. The mode is 3 and 3 appears twice in the subarray with indices [4,6].The fourth query is l=3 and r=4. The mode is 2, which appears once in the subarray with indices [3,4]. Note that 3 also appears once in that range, but 2 is smaller than 3. | 6
2 2
2 2
3 2
2 1
| ? 1 6 ? 1 3 ? 4 6 ? 3 4 ! 1 2 2 3 3 4 | 3 seconds | 256 megabytes | ['binary search', 'divide and conquer', 'interactive', '*2700'] |
E. Omkar and Last Floortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOmkar is building a house. He wants to decide how to make the floor plan for the last floor.Omkar's floor starts out as n rows of m zeros (1 \le n,m \le 100). Every row is divided into intervals such that every 0 in the row is in exactly 1 interval. For every interval for every row, Omkar can change exactly one of the 0s contained in that interval to a 1. Omkar defines the quality of a floor as the sum of the squares of the sums of the values in each column, i. e. if the sum of the values in the i-th column is q_i, then the quality of the floor is \sum_{i = 1}^m q_i^2.Help Omkar find the maximum quality that the floor can have.InputThe first line contains two integers, n and m (1 \le n,m \le 100), which are the number of rows and number of columns, respectively.You will then receive a description of the intervals in each row. For every row i from 1 to n: The first row contains a single integer k_i (1 \le k_i \le m), which is the number of intervals on row i. The j-th of the next k_i lines contains two integers l_{i,j} and r_{i,j}, which are the left and right bound (both inclusive), respectively, of the j-th interval of the i-th row. It is guaranteed that all intervals other than the first interval will be directly after the interval before it. Formally, l_{i,1} = 1, l_{i,j} \leq r_{i,j} for all 1 \le j \le k_i, r_{i,j-1} + 1 = l_{i,j} for all 2 \le j \le k_i, and r_{i,k_i} = m.OutputOutput one integer, which is the maximum possible quality of an eligible floor plan.ExampleInput
4 5
2
1 2
3 5
2
1 3
4 5
3
1 1
2 4
5 5
3
1 1
2 2
3 5
Output
36
NoteThe given test case corresponds to the following diagram. Cells in the same row and have the same number are a part of the same interval. The most optimal assignment is: The sum of the 1st column is 4, the sum of the 2nd column is 2, the sum of the 3rd and 4th columns are 0, and the sum of the 5th column is 4.The quality of this floor plan is 4^2 + 2^2 + 0^2 + 0^2 + 4^2 = 36. You can show that there is no floor plan with a higher quality. | 4 5
2
1 2
3 5
2
1 3
4 5
3
1 1
2 4
5 5
3
1 1
2 2
3 5
| 36 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'two pointers', '*2900'] |
D. Omkar and Circletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDanny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem!You are given n nonnegative integers a_1, a_2, \dots, a_n arranged in a circle, where n must be odd (ie. n-1 is divisible by 2). Formally, for all i such that 2 \leq i \leq n, the elements a_{i - 1} and a_i are considered to be adjacent, and a_n and a_1 are also considered to be adjacent. In one operation, you pick a number on the circle, replace it with the sum of the two elements adjacent to it, and then delete the two adjacent elements from the circle. This is repeated until only one number remains in the circle, which we call the circular value.Help Danny find the maximum possible circular value after some sequences of operations. InputThe first line contains one odd integer n (1 \leq n < 2 \cdot 10^5, n is odd) — the initial size of the circle.The second line contains n integers a_{1},a_{2},\dots,a_{n} (0 \leq a_{i} \leq 10^9) — the initial numbers in the circle.OutputOutput the maximum possible circular value after applying some sequence of operations to the given circle.ExamplesInput
3
7 10 2
Output
17
Input
1
4
Output
4
NoteFor the first test case, here's how a circular value of 17 is obtained:Pick the number at index 3. The sum of adjacent elements equals 17. Delete 7 and 10 from the circle and replace 2 with 17.Note that the answer may not fit in a 32-bit integer. | 3
7 10 2
| 17 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'games', 'greedy', '*2100'] |
C. Omkar and Baseballtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPatrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across n sessions follow the identity permutation (ie. in the first game he scores 1 point, in the second game he scores 2 points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up! Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on [1,2,3] can yield [3,1,2] but it cannot yield [3,2,1] since the 2 is in the same position. Given a permutation of n integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed 10^{18}.An array a is a subarray of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line of each test case contains integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the given permutation.The second line of each test case contains n integers a_{1},a_{2},...,a_{n} (1 \leq a_{i} \leq n) — the initial permutation.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.ExampleInput
251 2 3 4 573 2 4 5 1 6 7Output
0
2
NoteIn the first permutation, it is already sorted so no exchanges are needed.It can be shown that you need at least 2 exchanges to sort the second permutation.[3, 2, 4, 5, 1, 6, 7]Perform special exchange on range (1, 5)[4, 1, 2, 3, 5, 6, 7]Perform special exchange on range (1, 4)[1, 2, 3, 4, 5, 6, 7] | 251 2 3 4 573 2 4 5 1 6 7 | 0 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', '*1500'] |
B. Omkar and Last Class of Mathtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b.Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b such that a + b = n and LCM(a, b) is the minimum value possible.Can you help Omkar solve his ludicrously challenging math problem?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10). Description of the test cases follows.Each test case consists of a single integer n (2 \leq n \leq 10^{9}).OutputFor each test case, output two positive integers a and b, such that a + b = n and LCM(a, b) is the minimum possible.ExampleInput
3
4
6
9
Output
2 2
3 3
3 6
NoteFor the first test case, the numbers we can choose are 1, 3 or 2, 2. LCM(1, 3) = 3 and LCM(2, 2) = 2, so we output 2 \ 2.For the second test case, the numbers we can choose are 1, 5, 2, 4, or 3, 3. LCM(1, 5) = 5, LCM(2, 4) = 4, and LCM(3, 3) = 3, so we output 3 \ 3.For the third test case, LCM(3, 6) = 6. It can be shown that there are no other pairs of numbers which sum to 9 that have a lower LCM. | 3
4
6
9
| 2 2 3 3 3 6 | 1 second | 256 megabytes | ['greedy', 'math', 'number theory', '*1300'] |
A. Omkar and Completiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 \leq x,y,z \leq n), a_{x}+a_{y} \neq a_{z} (not necessarily distinct).You are given one integer n. Please find any complete array of length n. It is guaranteed that under given constraints such array exists.InputEach test contains multiple test cases. The first line contains t (1 \le t \le 1000) — the number of test cases. Description of the test cases follows.The only line of each test case contains one integer n (1 \leq n \leq 1000).It is guaranteed that the sum of n over all test cases does not exceed 1000.OutputFor each test case, print a complete array on a single line. All elements have to be integers between 1 and 1000 and for all indices x,y,z (1 \leq x,y,z \leq n) (not necessarily distinct), a_{x}+a_{y} \neq a_{z} must hold.If multiple solutions exist, you may print any.ExampleInput
2
5
4
Output
1 5 3 77 12
384 384 44 44
NoteIt can be shown that the outputs above are valid for each test case. For example, 44+44 \neq 384.Below are some examples of arrays that are NOT complete for the 1st test case:[1,2,3,4,5] Notice that a_{1}+a_{2} = a_{3}.[1,3000,1,300,1] Notice that a_{2} = 3000 > 1000. | 2
5
4
| 1 5 3 77 12 384 384 44 44 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*800'] |
F. Raging Thundertime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are a warrior fighting against the machine god Thor.Thor challenge you to solve the following problem:There are n conveyors arranged in a line numbered with integers from 1 to n from left to right. Each conveyor has a symbol "<" or ">". The initial state of the conveyor i is equal to the i-th character of the string s. There are n+1 holes numbered with integers from 0 to n. The hole 0 is on the left side of the conveyor 1, and for all i \geq 1 the hole i is on the right side of the conveyor i.When a ball is on the conveyor i, the ball moves by the next rules:If the symbol "<" is on the conveyor i, then: If i=1, the ball falls into the hole 0. If the symbol "<" is on the conveyor i-1, the ball moves to the conveyor i-1. If the symbol ">" is on the conveyor i-1, the ball falls into the hole i-1. If the symbol ">" is on the conveyor i, then: If i=n, the ball falls into the hole n. If the symbol ">" is on the conveyor i+1, the ball moves to the conveyor i+1. If the symbol "<" is on the conveyor i+1, the ball falls into the hole i. You should answer next q queries, each query is defined by the pair of integers l, r (1 \leq l \leq r \leq n): First, for all conveyors l,l+1,...,r, the symbol "<" changes to ">" and vice versa. These changes remain for the next queries. After that, put one ball on each conveyor l,l+1,...,r. Then, each ball falls into some hole. Find the maximum number of balls in one hole. After the query all balls disappear and don't considered in the next queries. InputThe first line contains two integers n, q (1 \le n \le 5 \times 10^5 , 1 \le q \le 10^5).The second line contains a string s of length n. It consists of characters "<" and ">". Next q lines contain the descriptions of the queries, i-th of them contains two integers l, r (1 \le l \le r \le n), describing the i-th query.OutputPrint q lines, in the i-th of them print the answer to the i-th query.ExampleInput
5 6
><>><
2 4
3 5
1 5
1 3
2 4
1 5
Output
3
3
5
3
2
3
Note In the first query, the conveyors change to ">><<<". After that, put a ball on each conveyor \{2,3,4\}. All three balls fall into the hole 2. So the answer is 3. In the second query, the conveyors change to ">>>>>". After that, put a ball on each conveyor \{3,4,5\}. All three balls fall into the hole 5. So the answer is 3. In the third query, the conveyors change to "<<<<<". After that, put a ball on each conveyor \{1,2,3,4,5\}. All five balls fall into the hole 0. So the answer is 5. In the fourth query, the conveyors change to ">>><<". After that, put a ball on each conveyor \{1,2,3\}. All three balls fall into the hole 3. So the answer is 3. In the fifth query, the conveyors change to "><<><". After that, put a ball on each conveyor \{2,3,4\}. Two balls fall into the hole 1, and one ball falls into the hole 4. So, the answer is 2. In the sixth query, the conveyors change to "<>><>". After that, put a ball on each conveyor \{1,2,3,4,5\}. Three balls fall into the hole 3, one ball falls into the hole 0 and one ball falls into the hole 5. So, the answer is 3. | 5 6
><>><
2 4
3 5
1 5
1 3
2 4
1 5
| 3 3 5 3 2 3 | 3 seconds | 512 megabytes | ['data structures', 'divide and conquer', 'implementation', '*2800'] |
E2. Asterism (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved.First, Aoi came up with the following idea for the competitive programming problem:Yuzu is a girl who collecting candies. Originally, she has x candies. There are also n enemies numbered with integers from 1 to n. Enemy i has a_i candies.Yuzu is going to determine a permutation P. A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, \{2,3,1,5,4\} is a permutation, but \{1,2,2\} is not a permutation (2 appears twice in the array) and \{1,3,4\} is also not a permutation (because n=3 but there is the number 4 in the array).After that, she will do n duels with the enemies with the following rules: If Yuzu has equal or more number of candies than enemy P_i, she wins the duel and gets 1 candy. Otherwise, she loses the duel and gets nothing. The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations P exist?This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea:Let's define f(x) as the number of valid permutations for the integer x.You are given n, a and a prime number p \le n. Let's call a positive integer x good, if the value f(x) is not divisible by p. Find all good integers x.Your task is to solve this problem made by Akari.InputThe first line contains two integers n, p (2 \le p \le n \le 10^5). It is guaranteed, that the number p is prime (it has exactly two divisors 1 and p).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).OutputIn the first line, print the number of good integers x.In the second line, output all good integers x in the ascending order.It is guaranteed that the number of good integers x does not exceed 10^5.ExamplesInput
3 2
3 4 5
Output
1
3
Input
4 3
2 3 5 6
Output
2
3 4
Input
4 3
9 1 1 1
Output
0
Input
3 2
1000000000 1 999999999
Output
1
999999998
NoteIn the first test, p=2. If x \le 2, there are no valid permutations for Yuzu. So f(x)=0 for all x \le 2. The number 0 is divisible by 2, so all integers x \leq 2 are not good. If x = 3, \{1,2,3\} is the only valid permutation for Yuzu. So f(3)=1, so the number 3 is good. If x = 4, \{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\} are all valid permutations for Yuzu. So f(4)=4, so the number 4 is not good. If x \ge 5, all 6 permutations are valid for Yuzu. So f(x)=6 for all x \ge 5, so all integers x \ge 5 are not good. So, the only good number is 3.In the third test, for all positive integers x the value f(x) is divisible by p = 3. | 3 2
3 4 5
| 1 3 | 1 second | 256 megabytes | ['binary search', 'combinatorics', 'dp', 'math', 'number theory', 'sortings', '*2300'] |
E1. Asterism (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved.First, Aoi came up with the following idea for the competitive programming problem:Yuzu is a girl who collecting candies. Originally, she has x candies. There are also n enemies numbered with integers from 1 to n. Enemy i has a_i candies.Yuzu is going to determine a permutation P. A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, \{2,3,1,5,4\} is a permutation, but \{1,2,2\} is not a permutation (2 appears twice in the array) and \{1,3,4\} is also not a permutation (because n=3 but there is the number 4 in the array).After that, she will do n duels with the enemies with the following rules: If Yuzu has equal or more number of candies than enemy P_i, she wins the duel and gets 1 candy. Otherwise, she loses the duel and gets nothing. The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations P exist?This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea:Let's define f(x) as the number of valid permutations for the integer x.You are given n, a and a prime number p \le n. Let's call a positive integer x good, if the value f(x) is not divisible by p. Find all good integers x.Your task is to solve this problem made by Akari.InputThe first line contains two integers n, p (2 \le p \le n \le 2000). It is guaranteed, that the number p is prime (it has exactly two divisors 1 and p).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 2000).OutputIn the first line, print the number of good integers x.In the second line, output all good integers x in the ascending order.It is guaranteed that the number of good integers x does not exceed 10^5.ExamplesInput
3 2
3 4 5
Output
1
3
Input
4 3
2 3 5 6
Output
2
3 4
Input
4 3
9 1 1 1
Output
0
NoteIn the first test, p=2. If x \le 2, there are no valid permutations for Yuzu. So f(x)=0 for all x \le 2. The number 0 is divisible by 2, so all integers x \leq 2 are not good. If x = 3, \{1,2,3\} is the only valid permutation for Yuzu. So f(3)=1, so the number 3 is good. If x = 4, \{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\} are all valid permutations for Yuzu. So f(4)=4, so the number 4 is not good. If x \ge 5, all 6 permutations are valid for Yuzu. So f(x)=6 for all x \ge 5, so all integers x \ge 5 are not good. So, the only good number is 3.In the third test, for all positive integers x the value f(x) is divisible by p = 3. | 3 2
3 4 5
| 1 3 | 1 second | 256 megabytes | ['binary search', 'brute force', 'combinatorics', 'math', 'number theory', 'sortings', '*1900'] |
D. Grid-00100time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers n,k. Construct a grid A with size n \times n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k.Let's define: A_{i,j} as the integer in the i-th row and the j-th column. R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 \le i \le n). C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 \le j \le n). In other words, R_i are row sums and C_j are column sums of the grid A. For the grid A let's define the value f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2 (here for an integer sequence X we define \max(X) as the maximum value in X and \min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any.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. Next t lines contain descriptions of test cases.For each test case the only line contains two integers n, k (1 \le n \le 300, 0 \le k \le n^2).It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5.OutputFor each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied.After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}.If there are multiple answers you can print any.ExampleInput
4
2 2
3 8
1 0
4 16
Output
0
10
01
2
111
111
101
0
0
0
1111
1111
1111
1111
NoteIn the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A).In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). | 4
2 2
3 8
1 0
4 16
| 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', '*1600'] |
C. A Cookie for Youtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has a vanilla cookies and b chocolate cookies for the party.She invited n guests of the first type and m guests of the second type to the party. They will come to the party in some order. After coming to the party, each guest will choose the type of cookie (vanilla or chocolate) to eat. There is a difference in the way how they choose that type:If there are v vanilla cookies and c chocolate cookies at the moment, when the guest comes, then if the guest of the first type: if v>c the guest selects a vanilla cookie. Otherwise, the guest selects a chocolate cookie. if the guest of the second type: if v>c the guest selects a chocolate cookie. Otherwise, the guest selects a vanilla cookie. After that: If there is at least one cookie of the selected type, the guest eats one. Otherwise (there are no cookies of the selected type), the guest gets angry and returns to home. Anna wants to know if there exists some order of guests, such that no one guest gets angry. Your task is to answer her question.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Next t lines contain descriptions of test cases.For each test case, the only line contains four integers a, b, n, m (0 \le a,b,n,m \le 10^{18}, n+m \neq 0).OutputFor each test case, print the answer in one line. If there exists at least one valid order, print "Yes". Otherwise, print "No".You can print each letter in any case (upper or lower).ExampleInput
6
2 2 1 2
0 100 0 1
12 13 25 1
27 83 14 25
0 0 1 0
1000000000000000000 1000000000000000000 1000000000000000000 1000000000000000000
Output
Yes
No
No
Yes
No
Yes
NoteIn the first test case, let's consider the order \{1, 2, 2\} of types of guests. Then: The first guest eats a chocolate cookie. After that, there are 2 vanilla cookies and 1 chocolate cookie. The second guest eats a chocolate cookie. After that, there are 2 vanilla cookies and 0 chocolate cookies. The last guest selects a chocolate cookie, but there are no chocolate cookies. So, the guest gets angry. So, this order can't be chosen by Anna.Let's consider the order \{2, 2, 1\} of types of guests. Then: The first guest eats a vanilla cookie. After that, there is 1 vanilla cookie and 2 chocolate cookies. The second guest eats a vanilla cookie. After that, there are 0 vanilla cookies and 2 chocolate cookies. The last guest eats a chocolate cookie. After that, there are 0 vanilla cookies and 1 chocolate cookie. So, the answer to this test case is "Yes".In the fifth test case, it is illustrated, that the number of cookies (a + b) can be equal to zero, but the number of guests (n + m) can't be equal to zero.In the sixth test case, be careful about the overflow of 32-bit integer type. | 6
2 2 1 2
0 100 0 1
12 13 25 1
27 83 14 25
0 0 1 0
1000000000000000000 1000000000000000000 1000000000000000000 1000000000000000000
| Yes No No Yes No Yes | 1 second | 256 megabytes | ['greedy', 'implementation', 'math', '*1300'] |
B. Magical Calendartime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!In detail, she can choose any integer k which satisfies 1 \leq k \leq r, and set k days as the number of days in a week.Alice is going to paint some n consecutive days on this calendar. On this calendar, dates are written from the left cell to the right cell in a week. If a date reaches the last day of a week, the next day's cell is the leftmost cell in the next (under) row.She wants to make all of the painted cells to be connected by side. It means, that for any two painted cells there should exist at least one sequence of painted cells, started in one of these cells, and ended in another, such that any two consecutive cells in this sequence are connected by side.Alice is considering the shape of the painted cells. Two shapes are the same if there exists a way to make them exactly overlapped using only parallel moves, parallel to the calendar's sides.For example, in the picture, a week has 4 days and Alice paints 5 consecutive days. [1] and [2] are different shapes, but [1] and [3] are equal shapes. Alice wants to know how many possible shapes exists if she set how many days a week has and choose consecutive n days and paints them in calendar started in one of the days of the week. As was said before, she considers only shapes, there all cells are connected by side.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Next t lines contain descriptions of test cases.For each test case, the only line contains two integers n, r (1 \le n \le 10^9, 1 \le r \le 10^9).OutputFor each test case, print a single integer — the answer to the problem.Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language.ExampleInput
5
3 4
3 2
3 1
13 7
1010000 9999999
Output
4
3
1
28
510049495001
NoteIn the first test case, Alice can set 1,2,3 or 4 days as the number of days in a week.There are 6 possible paintings shown in the picture, but there are only 4 different shapes. So, the answer is 4. Notice that the last example in the picture is an invalid painting because all cells are not connected by sides. In the last test case, be careful with the overflow issue, described in the output format. | 5
3 4
3 2
3 1
13 7
1010000 9999999
| 4 3 1 28 510049495001 | 1 second | 256 megabytes | ['math', '*1200'] |
A. Magical Stickstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA penguin Rocher has n sticks. He has exactly one stick with length i for all 1 \le i \le n.He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his set and can be used for the next connections.He wants to create the maximum number of sticks that have the same length. It is not necessary to make all sticks have the same length, some sticks can have the other length. How many sticks with the equal length he can create?InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Next t lines contain descriptions of test cases.For each test case, the only line contains a single integer n (1 \le n \le 10^{9}).OutputFor each test case, print a single integer — the answer to the problem.ExampleInput
4
1
2
3
4
Output
1
1
2
2
NoteIn the third case, he can connect two sticks with lengths 1 and 2 and he will get one stick with length 3. So, he will have two sticks with lengths 3.In the fourth case, he can connect two sticks with lengths 1 and 3 and he will get one stick with length 4. After that, he will have three sticks with lengths \{2, 4, 4\}, so two sticks have the same length, and one stick has the other length. | 4
1
2
3
4
| 1 1 2 2 | 1 second | 256 megabytes | ['math', '*800'] |
F2. The Hidden Pair (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNote that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.This is an interactive problem.You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them.More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \{a_1, a_2, \ldots, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal.You can ask no more than 11 queries.InputThe first line contains a single integer t (1 \leq t \leq 10) — the number of test cases. Please note, how the interaction process is organized.The first line of each test case consists of a single integer n (2 \le n \le 1000) — the number of nodes in the tree.The next n - 1 lines consist of two integers u, v (1 \le u, v \le n, u \ne v) — the edges of the tree.InteractionTo ask a query print a single line: In the beginning print "? c " (without quotes) where c (1 \leq c \leq n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] — the indices of nodes from the list. For each query, you will receive two integers x, d — the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately.When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] — the hidden nodes. You can output the hidden nodes in any order.After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately.Guessing the hidden nodes does not count towards the number of queries asked.The interactor is not adaptive. The hidden nodes do not change with queries.Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes.You need to solve each test case before receiving the input for the next test case.The limit of 11 queries applies to each test case and not to the entire input.After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack the solution, use the following test format:The first line should contain a single integer t (1 \leq t \leq 10) — the number of test cases. The description of the test cases follows.The first line of each test case should contain a single integer n (2 \le n \le 1000) — the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] — the hidden nodes. The next n - 1 lines should contain two integers u, v (1 \le u, v \le n, u \ne v) — the edges of the tree.ExampleInput
1
3
1 2
1 3
1 1
2 3
3 1
3 1
CorrectOutput
? 1 1
? 1 2
? 1 3
? 2 2 3
! 1 3NoteThe tree from the first test is shown below, and the hidden nodes are 1 and 3. | 1
3
1 2
1 3
1 1
2 3
3 1
3 1
Correct | ? 1 1 ? 1 2 ? 1 3 ? 2 2 3 ! 1 3 | 2 seconds | 256 megabytes | ['binary search', 'dfs and similar', 'graphs', 'interactive', 'shortest paths', 'trees', '*2700'] |
F1. The Hidden Pair (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNote that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.This is an interactive problem.You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them.More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \{a_1, a_2, \ldots, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal.You can ask no more than 14 queries.InputThe first line contains a single integer t (1 \leq t \leq 10) — the number of test cases. Please note, how the interaction process is organized.The first line of each test case consists of a single integer n (2 \le n \le 1000) — the number of nodes in the tree.The next n - 1 lines consist of two integers u, v (1 \le u, v \le n, u \ne v) — the edges of the tree.InteractionTo ask a query print a single line: In the beginning print "? c " (without quotes) where c (1 \leq c \leq n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] — the indices of nodes from the list. For each query, you will receive two integers x, d — the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately.When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] — the hidden nodes. You can output the hidden nodes in any order.After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately.Guessing the hidden nodes does not count towards the number of queries asked.The interactor is not adaptive. The hidden nodes do not change with queries.Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes.You need to solve each test case before receiving the input for the next test case.The limit of 14 queries applies to each test case and not to the entire input.After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack the solution, use the following test format:The first line should contain a single integer t (1 \leq t \leq 10) — the number of test cases. The description of the test cases follows.The first line of each test case should contain a single integer n (2 \le n \le 1000) — the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] — the hidden nodes. The next n - 1 lines should contain two integers u, v (1 \le u, v \le n, u \ne v) — the edges of the tree.ExampleInput
1
3
1 2
1 3
1 1
2 3
3 1
3 1
CorrectOutput
? 1 1
? 1 2
? 1 3
? 2 2 3
! 1 3NoteThe tree from the first test is shown below, and the hidden nodes are 1 and 3. | 1
3
1 2
1 3
1 1
2 3
3 1
3 1
Correct | ? 1 1 ? 1 2 ? 1 3 ? 2 2 3 ! 1 3 | 2 seconds | 256 megabytes | ['binary search', 'dfs and similar', 'graphs', 'interactive', 'shortest paths', 'trees', '*2400'] |
E. Binary Subsequence Rotationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNaman has two binary strings s and t of length n (a binary string is a string which only consists of the characters "0" and "1"). He wants to convert s into t using the following operation as few times as possible.In one operation, he can choose any subsequence of s and rotate it clockwise once.For example, if s = 1\textbf{1}101\textbf{00}, he can choose a subsequence corresponding to indices (1-based) \{2, 6, 7 \} and rotate them clockwise. The resulting string would then be s = 1\textbf{0}101\textbf{10}.A string a is said to be a subsequence of string b if a can be obtained from b by deleting some characters without changing the ordering of the remaining characters.To perform a clockwise rotation on a sequence c of size k is to perform an operation which sets c_1:=c_k, c_2:=c_1, c_3:=c_2, \ldots, c_k:=c_{k-1} simultaneously.Determine the minimum number of operations Naman has to perform to convert s into t or say that it is impossible. InputThe first line contains a single integer n (1 \le n \le 10^6) — the length of the strings.The second line contains the binary string s of length n.The third line contains the binary string t of length n.OutputIf it is impossible to convert s to t after any number of operations, print -1.Otherwise, print the minimum number of operations required.ExamplesInput
6
010000
000001
Output
1Input
10
1111100000
0000011111
Output
5Input
8
10101010
01010101
Output
1Input
10
1111100000
1111100001
Output
-1NoteIn the first test, Naman can choose the subsequence corresponding to indices \{2, 6\} and rotate it once to convert s into t.In the second test, he can rotate the subsequence corresponding to all indices 5 times. It can be proved, that it is the minimum required number of operations.In the last test, it is impossible to convert s into t. | 6
010000
000001
| 1 | 2 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'data structures', 'greedy', '*2100'] |
D. Odd-Even Subsequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAshish has an array a of size n.A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.Consider a subsequence s of a. He defines the cost of s as the minimum between: The maximum among all elements at odd indices of s. The maximum among all elements at even indices of s. Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, \ldots), max(s_2, s_4, s_6, \ldots)).For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.Help him find the minimum cost of a subsequence of size k.InputThe first line contains two integers n and k (2 \leq k \leq n \leq 2 \cdot 10^5) — the size of the array a and the size of the subsequence.The next line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the elements of the array a.OutputOutput a single integer — the minimum cost of a subsequence of size k.ExamplesInput
4 2
1 2 3 4
Output
1Input
4 3
1 2 3 4
Output
2Input
5 3
5 3 4 2 6
Output
2Input
6 4
5 3 50 2 4 5
Output
3NoteIn the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3. | 4 2
1 2 3 4
| 1 | 2 seconds | 256 megabytes | ['binary search', 'dp', 'dsu', 'greedy', 'implementation', '*2000'] |
C. Number Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAshishgup and FastestFinger play a game. They start with a number n and play in turns. In each turn, a player can make any one of the following moves: Divide n by any of its odd divisors greater than 1. Subtract 1 from n if n is greater than 1. Divisors of a number include the number itself.The player who is unable to make a move loses the game.Ashishgup moves first. Determine the winner of the game if both of them play optimally.InputThe first line contains a single integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The only line of each test case contains a single integer — n (1 \leq n \leq 10^9).OutputFor each test case, print "Ashishgup" if he wins, and "FastestFinger" otherwise (without quotes).ExampleInput
7
1
2
3
4
5
6
12
Output
FastestFinger
Ashishgup
Ashishgup
FastestFinger
Ashishgup
FastestFinger
Ashishgup
NoteIn the first test case, n = 1, Ashishgup cannot make a move. He loses.In the second test case, n = 2, Ashishgup subtracts 1 on the first move. Now n = 1, FastestFinger cannot make a move, so he loses.In the third test case, n = 3, Ashishgup divides by 3 on the first move. Now n = 1, FastestFinger cannot make a move, so he loses.In the last test case, n = 12, Ashishgup divides it by 3. Now n = 4, FastestFinger is forced to subtract 1, and Ashishgup gets 3, so he wins by dividing it by 3. | 7
1
2
3
4
5
6
12
| FastestFinger Ashishgup Ashishgup FastestFinger Ashishgup FastestFinger Ashishgup | 2 seconds | 256 megabytes | ['games', 'math', 'number theory', '*1400'] |
B. GCD Compressiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAshish has an array a of consisting of 2n positive integers. He wants to compress a into an array b of size n-1. To do this, he first discards exactly 2 (any two) elements from a. He then performs the following operation until there are no elements left in a: Remove any two elements from a and append their sum to b. The compressed array b has to have a special property. The greatest common divisor (\mathrm{gcd}) of all its elements should be greater than 1.Recall that the \mathrm{gcd} of an array of positive integers is the biggest integer that is a divisor of all integers in the array.It can be proven that it is always possible to compress array a into an array b of size n-1 such that gcd(b_1, b_2..., b_{n-1}) > 1. Help Ashish find a way to do so.InputThe first line contains a single integer t (1 \leq t \leq 10) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2 \leq n \leq 1000).The second line of each test case contains 2n integers a_1, a_2, \ldots, a_{2n} (1 \leq a_i \leq 1000) — the elements of the array a.OutputFor each test case, output n-1 lines — the operations performed to compress the array a to the array b. The initial discard of the two elements is not an operation, you don't need to output anything about it.The i-th line should contain two integers, the indices (1 —based) of the two elements from the array a that are used in the i-th operation. All 2n-2 indices should be distinct integers from 1 to 2n.You don't need to output two initially discarded elements from a.If there are multiple answers, you can find any.ExampleInput
3
3
1 2 3 4 5 6
2
5 7 9 10
5
1 3 3 4 5 90 100 101 2 3
Output
3 6
4 5
3 4
1 9
2 3
4 5
6 10
NoteIn the first test case, b = \{3+6, 4+5\} = \{9, 9\} and \mathrm{gcd}(9, 9) = 9.In the second test case, b = \{9+10\} = \{19\} and \mathrm{gcd}(19) = 19.In the third test case, b = \{1+2, 3+3, 4+5, 90+3\} = \{3, 6, 9, 93\} and \mathrm{gcd}(3, 6, 9, 93) = 3. | 3
3
1 2 3 4 5 6
2
5 7 9 10
5
1 3 3 4 5 90 100 101 2 3
| 3 6 4 5 3 4 1 9 2 3 4 5 6 10 | 1 second | 256 megabytes | ['constructive algorithms', 'math', 'number theory', '*1100'] |
A. Maximum GCDtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's consider all integers in the range from 1 to n (inclusive).Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of \mathrm{gcd}(a, b), where 1 \leq a < b \leq n.The greatest common divisor, \mathrm{gcd}(a, b), of two positive integers a and b is the biggest integer that is a divisor of both a and b.InputThe first line contains a single integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The only line of each test case contains a single integer n (2 \leq n \leq 10^6).OutputFor each test case, output the maximum value of \mathrm{gcd}(a, b) among all 1 \leq a < b \leq n.ExampleInput
2
3
5
Output
1
2
NoteIn the first test case, \mathrm{gcd}(1, 2) = \mathrm{gcd}(2, 3) = \mathrm{gcd}(1, 3) = 1.In the second test case, 2 is the maximum possible value, corresponding to \mathrm{gcd}(2, 4). | 2
3
5
| 1 2 | 1 second | 256 megabytes | ['greedy', 'implementation', 'math', 'number theory', '*800'] |
F. BareLeetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determined and are known before the game begins, s_i and e_i may differ from round to round). The integer s_i is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was a) and will choose to write either 2 \cdot a or a + 1 instead. Whoever writes a number strictly greater than e_i loses that round and the other one wins that round.Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's s_i and e_i in advance. Lee will start the first round, the loser of each round will start the next round.The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.InputThe first line contains the integer t (1 \le t \le 10^5) — the number of rounds the game has. Then t lines follow, each contains two integers s_i and e_i (1 \le s_i \le e_i \le 10^{18}) — the i-th round's information.The rounds are played in the same order as given in input, s_i and e_i for all rounds are known to everyone before the game starts.OutputPrint two integers.The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise.The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise.ExamplesInput
3
5 8
1 4
3 10
Output
1 1
Input
4
1 2
2 3
3 4
4 5
Output
0 0
Input
1
1 1
Output
0 1
Input
2
1 9
4 5
Output
0 0
Input
2
1 2
2 8
Output
1 0
Input
6
216986951114298167 235031205335543871
148302405431848579 455670351549314242
506251128322958430 575521452907339082
1 768614336404564650
189336074809158272 622104412002885672
588320087414024192 662540324268197150
Output
1 0
NoteRemember, whoever writes an integer greater than e_i loses. | 3
5 8
1 4
3 10
| 1 1 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'games', '*2700'] |
E. DeadLeetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLee bought some food for dinner time, but Lee's friends eat dinner in a deadly way. Lee is so scared, he doesn't want to die, at least not before seeing Online IOI 2020...There are n different types of food and m Lee's best friends. Lee has w_i plates of the i-th type of food and each friend has two different favorite types of food: the i-th friend's favorite types of food are x_i and y_i (x_i \ne y_i).Lee will start calling his friends one by one. Whoever is called will go to the kitchen and will try to eat one plate of each of his favorite food types. Each of the friends will go to the kitchen exactly once.The only problem is the following: if a friend will eat at least one plate of food (in total) then he will be harmless. But if there is nothing left for him to eat (neither x_i nor y_i), he will eat Lee instead \times\_\times.Lee can choose the order of friends to call, so he'd like to determine if he can survive dinner or not. Also, he'd like to know the order itself.InputThe first line contains two integers n and m (2 \le n \le 10^5; 1 \le m \le 2 \cdot 10^5) — the number of different food types and the number of Lee's friends. The second line contains n integers w_1, w_2, \ldots, w_n (0 \le w_i \le 10^6) — the number of plates of each food type.The i-th line of the next m lines contains two integers x_i and y_i (1 \le x_i, y_i \le n; x_i \ne y_i) — the favorite types of food of the i-th friend. OutputIf Lee can survive the dinner then print ALIVE (case insensitive), otherwise print DEAD (case insensitive).Also, if he can survive the dinner, print the order Lee should call friends. If there are multiple valid orders, print any of them.ExamplesInput
3 3
1 2 1
1 2
2 3
1 3
Output
ALIVE
3 2 1
Input
3 2
1 1 0
1 2
1 3
Output
ALIVE
2 1
Input
4 4
1 2 0 1
1 3
1 2
2 3
2 4
Output
ALIVE
1 3 2 4
Input
5 5
1 1 1 2 1
3 4
1 2
2 3
4 5
4 5
Output
ALIVE
5 4 1 3 2
Input
4 10
2 4 1 4
3 2
4 2
4 1
3 1
4 1
1 3
3 2
2 1
3 1
2 4
Output
DEAD
NoteIn the first example, any of the following orders of friends are correct : [1, 3, 2], [3, 1, 2], [2, 3, 1], [3, 2, 1].In the second example, Lee should call the second friend first (the friend will eat a plate of food 1) and then call the first friend (the friend will eat a plate of food 2). If he calls the first friend sooner than the second one, then the first friend will eat one plate of food 1 and food 2 and there will be no food left for the second friend to eat. | 3 3
1 2 1
1 2
2 3
1 3
| ALIVE 3 2 1 | 2 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'greedy', 'implementation', 'sortings', '*2400'] |
D. TediousLeetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...Let's define a Rooted Dead Bush (RDB) of level n as a rooted tree constructed as described below.A rooted dead bush of level 1 is a single vertex. To construct an RDB of level i we, at first, construct an RDB of level i-1, then for each vertex u: if u has no children then we will add a single child to it; if u has one child then we will add two children to it; if u has more than one child, then we will skip it. Rooted Dead Bushes of level 1, 2 and 3. Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw: The center of the claw is the vertex with label 1. Lee has a Rooted Dead Bush of level n. Initially, all vertices of his RDB are green.In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo 10^9+7.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Next t lines contain test cases — one per line.The first line of each test case contains one integer n (1 \le n \le 2 \cdot 10^6) — the level of Lee's RDB.OutputFor each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo 10^9 + 7.ExampleInput
7
1
2
3
4
5
100
2000000
Output
0
0
4
4
12
990998587
804665184
NoteIt's easy to see that the answer for RDB of level 1 or 2 is 0.The answer for RDB of level 3 is 4 since there is only one claw we can choose: \{1, 2, 3, 4\}.The answer for RDB of level 4 is 4 since we can choose either single claw \{1, 3, 2, 4\} or single claw \{2, 7, 5, 6\}. There are no other claws in the RDB of level 4 (for example, we can't choose \{2, 1, 7, 6\}, since 1 is not a child of center vertex 2). Rooted Dead Bush of level 4. | 7
1
2
3
4
5
100
2000000
| 0 0 4 4 12 990998587 804665184 | 2 seconds | 256 megabytes | ['dp', 'graphs', 'greedy', 'math', 'trees', '*1900'] |
C. RationalLeetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought n integers, now it's time to distribute them between his friends rationally...Lee has n integers a_1, a_2, \ldots, a_n in his backpack and he has k friends. Lee would like to distribute all integers in his backpack between his friends, such that the i-th friend will get exactly w_i integers and each integer will be handed over to exactly one friend.Let's define the happiness of a friend as the sum of the maximum and the minimum integer he'll get.Lee would like to make his friends as happy as possible, in other words, he'd like to maximize the sum of friends' happiness. Now he asks you to calculate the maximum sum of friends' happiness.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Next 3t lines contain test cases — one per three lines.The first line of each test case contains two integers n and k (1 \le n \le 2 \cdot 10^5; 1 \le k \le n) — the number of integers Lee has and the number of Lee's friends.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (-10^9 \le a_i \le 10^9) — the integers Lee has.The third line contains k integers w_1, w_2, \ldots, w_k (1 \le w_i \le n; w_1 + w_2 + \ldots + w_k = n) — the number of integers Lee wants to give to each friend. It's guaranteed that the sum of n over test cases is less than or equal to 2 \cdot 10^5.OutputFor each test case, print a single integer — the maximum sum of happiness Lee can achieve.ExampleInput
3
4 2
1 13 7 17
1 3
6 2
10 10 10 10 11 11
3 3
4 4
1000000000 1000000000 1000000000 1000000000
1 1 1 1
Output
48
42
8000000000
NoteIn the first test case, Lee should give the greatest integer to the first friend (his happiness will be 17 + 17) and remaining integers to the second friend (his happiness will be 13 + 1).In the second test case, Lee should give \{10, 10, 11\} to the first friend and to the second friend, so the total happiness will be equal to (11 + 10) + (11 + 10)In the third test case, Lee has four friends and four integers, it doesn't matter how he distributes the integers between his friends. | 3
4 2
1 13 7 17
1 3
6 2
10 10 10 10 11 11
3 3
4 4
1000000000 1000000000 1000000000 1000000000
1 1 1 1
| 48 42 8000000000 | 2 seconds | 256 megabytes | ['greedy', 'math', 'sortings', 'two pointers', '*1400'] |
B. AccurateLeetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s).In one move he can choose two consecutive characters s_i and s_{i+1}, and if s_i is 1 and s_{i + 1} is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing.Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string s as clean as possible. He thinks for two different strings x and y, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner.Now you should answer t test cases: for the i-th test case, print the cleanest possible string that Lee can get by doing some number of moves.Small reminder: if we have two strings x and y of the same length then x is lexicographically smaller than y if there is a position i such that x_1 = y_1, x_2 = y_2,..., x_{i - 1} = y_{i - 1} and x_i < y_i.InputThe first line contains the integer t (1 \le t \le 10^4) — the number of test cases. Next 2t lines contain test cases — one per two lines.The first line of each test case contains the integer n (1 \le n \le 10^5) — the length of the string s.The second line contains the binary string s. The string s is a string of length n which consists only of zeroes and ones.It's guaranteed that sum of n over test cases doesn't exceed 10^5.OutputPrint t answers — one per test case.The answer to the i-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero).ExampleInput
5
10
0001111111
4
0101
8
11001101
10
1110000000
1
1
Output
0001111111
001
01
0
1
NoteIn the first test case, Lee can't perform any moves.In the second test case, Lee should erase s_2.In the third test case, Lee can make moves, for example, in the following order: 11001101 \rightarrow 1100101 \rightarrow 110101 \rightarrow 10101 \rightarrow 1101 \rightarrow 101 \rightarrow 01. | 5
10
0001111111
4
0101
8
11001101
10
1110000000
1
1
| 0001111111 001 01 0 1 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'strings', '*1200'] |
A. FashionabLeetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLee is going to fashionably decorate his house for a party, using some regular convex polygons...Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis at the same time.Recall that a regular n-sided polygon is a convex polygon with n vertices such that all the edges and angles are equal.Now he is shopping: the market has t regular polygons. For each of them print YES if it is beautiful and NO otherwise.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of polygons in the market. Each of the next t lines contains a single integer n_i (3 \le n_i \le 10^9): it means that the i-th polygon is a regular n_i-sided polygon. OutputFor each polygon, print YES if it's beautiful or NO otherwise (case insensitive).ExampleInput
4
3
4
12
1000000000
Output
NO
YES
YES
YES
NoteIn the example, there are 4 polygons in the market. It's easy to see that an equilateral triangle (a regular 3-sided polygon) is not beautiful, a square (a regular 4-sided polygon) is beautiful and a regular 12-sided polygon (is shown below) is beautiful as well. | 4
3
4
12
1000000000
| NO YES YES YES | 2 seconds | 256 megabytes | ['geometry', 'math', '*800'] |
H2. Breadboard Capacity (hard version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem H with modification queries.Lester and Delbert work at an electronics company. They are currently working on a microchip component serving to connect two independent parts of a large supercomputer.The component is built on top of a breadboard — a grid-like base for a microchip. The breadboard has n rows and m columns, and each row-column intersection contains a node. Also, on each side of the breadboard there are ports that can be attached to adjacent nodes. Left and right side have n ports each, and top and bottom side have m ports each. Each of the ports is connected on the outside to one of the parts bridged by the breadboard, and is colored red or blue respectively. Ports can be connected by wires going inside the breadboard. However, there are a few rules to follow: Each wire should connect a red port with a blue port, and each port should be connected to at most one wire. Each part of the wire should be horizontal or vertical, and turns are only possible at one of the nodes. To avoid interference, wires can not have common parts of non-zero length (but may have common nodes). Also, a wire can not cover the same segment of non-zero length twice.The capacity of the breadboard is the largest number of red-blue wire connections that can be made subject to the rules above. For example, the breadboard above has capacity 7, and one way to make seven connections is pictured below. Up to this point statements of both versions are identical. Differences follow below.As is common, specifications of the project change a lot during development, so coloring of the ports is not yet fixed. There are q modifications to process, each of them has the form of "colors of all ports in a contiguous range along one of the sides are switched (red become blue, and blue become red)". All modifications are persistent, that is, the previous modifications are not undone before the next one is made.To estimate how bad the changes are, Lester and Delbert need to find the breadboard capacity after each change. Help them do this efficiently.InputThe first line contains three integers n, m, q (1 \leq n, m \leq 10^5, 0 \leq q \leq 10^5) — the number of rows and columns of the breadboard, and the number of modifications respectively.The next four lines describe initial coloring of the ports. Each character in these lines is either R or B, depending on the coloring of the respective port. The first two of these lines contain n characters each, and describe ports on the left and right sides respectively from top to bottom. The last two lines contain m characters each, and describe ports on the top and bottom sides respectively from left to right.The next q lines describe modifications. Each of these lines contains a character s, followed by two integers l and r. If s is L or R, the modification is concerned with ports on the left/right side respectively, l and r satisfy 1 \leq l \leq r \leq n, and ports in rows between l and r (inclusive) on the side switch colors. Similarly, if s is U or D, then 1 \leq l \leq r \leq m, and ports in columns between l and r (inclusive) on the top/bottom side respectively switch colors.OutputPrint q + 1 integers, one per line — the breadboard capacity after 0, \ldots, q modifications have been made to the initial coloring.ExampleInput
4 5 4
BBRR
RBBR
BBBBB
RRRRR
L 2 3
R 3 4
U 1 5
D 1 5
Output
7
7
9
4
9
| 4 5 4
BBRR
RBBR
BBBBB
RRRRR
L 2 3
R 3 4
U 1 5
D 1 5
| 7 7 9 4 9 | 2 seconds | 512 megabytes | ['*3500'] |
H1. Breadboard Capacity (easy version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem H without modification queries.Lester and Delbert work at an electronics company. They are currently working on a microchip component serving to connect two independent parts of a large supercomputer.The component is built on top of a breadboard — a grid-like base for a microchip. The breadboard has n rows and m columns, and each row-column intersection contains a node. Also, on each side of the breadboard there are ports that can be attached to adjacent nodes. Left and right side have n ports each, and top and bottom side have m ports each. Each of the ports is connected on the outside to one of the parts bridged by the breadboard, and is colored red or blue respectively. Ports can be connected by wires going inside the breadboard. However, there are a few rules to follow: Each wire should connect a red port with a blue port, and each port should be connected to at most one wire. Each part of the wire should be horizontal or vertical, and turns are only possible at one of the nodes. To avoid interference, wires can not have common parts of non-zero length (but may have common nodes). Also, a wire can not cover the same segment of non-zero length twice.The capacity of the breadboard is the largest number of red-blue wire connections that can be made subject to the rules above. For example, the breadboard above has capacity 7, and one way to make seven connections is pictured below. Up to this point statements of both versions are identical. Differences follow below.Given the current breadboard configuration, help Lester and Delbert find its capacity efficiently.InputThe first line contains three integers n, m, q (1 \leq n, m \leq 10^5, \pmb{q = 0}). n and m are the number of rows and columns of the breadboard respectively. In this version q is always zero, and is only present for consistency with the harder version.The next four lines describe initial coloring of the ports. Each character in these lines is either R or B, depending on the coloring of the respective port. The first two of these lines contain n characters each, and describe ports on the left and right sides respectively from top to bottom. The last two lines contain m characters each, and describe ports on the top and bottom sides respectively from left to right.OutputPrint a single integer — the given breadboard capacity.ExampleInput
4 5 0
BBRR
RBBR
BBBBB
RRRRR
Output
7
| 4 5 0
BBRR
RBBR
BBBBB
RRRRR
| 7 | 2 seconds | 512 megabytes | ['dp', 'flows', 'greedy', '*3300'] |
G. Shifting Dominoestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBill likes to play with dominoes. He took an n \times m board divided into equal square cells, and covered it with dominoes. Each domino covers two adjacent cells of the board either horizontally or vertically, and each cell is covered exactly once with a half of one domino (that is, there are no uncovered cells, and no two dominoes cover the same cell twice).After that Bill decided to play with the covered board and share some photos of it on social media. First, he removes exactly one domino from the board, freeing two of the cells. Next, he moves dominoes around. A domino can only be moved along the line parallel to its longer side. A move in the chosen direction is possible if the next cell in this direction is currently free. Bill doesn't want to lose track of what the original tiling looks like, so he makes sure that at any point each domino shares at least one cell with its original position.After removing a domino and making several (possibly, zero) moves Bill takes a photo of the board and posts it. However, with the amount of filters Bill is using, domino borders are not visible, so only the two free cells of the board can be identified. When the photo is posted, Bill reverts the board to its original state and starts the process again.Bill wants to post as many photos as possible, but he will not post any photo twice. How many distinct photos can he take? Recall that photos are different if the pairs of free cells in the photos are different.InputThe first line contains two positive integers n and m (nm \leq 2 \cdot 10^5) — height and width of the board respectively.The next n lines describe the tiling of the board, row by row from top to bottom. Each of these lines contains m characters, describing the cells in the corresponding row left to right. Each character is one of U, D, L, or R, meaning that the cell is covered with a top, bottom, left, or right half of a domino respectively.It is guaranteed that the described tiling is valid, that is, each half-domino has a counterpart in the relevant location. In particular, since tiling is possible, the number of cells in the board is even.OutputPrint a single integer — the number of distinct photos Bill can take.ExamplesInput
2 4
UUUU
DDDD
Output
4
Input
2 3
ULR
DLR
Output
6
Input
6 6
ULRUUU
DUUDDD
UDDLRU
DLRLRD
ULRULR
DLRDLR
Output
133
NoteIn the first sample case, no moves are possible after removing any domino, thus there are four distinct photos.In the second sample case, four photos are possible after removing the leftmost domino by independently moving/not moving the remaining two dominoes. Two more different photos are obtained by removing one of the dominoes on the right. | 2 4
UUUU
DDDD
| 4 | 2 seconds | 512 megabytes | ['data structures', 'geometry', 'graphs', 'trees', '*3200'] |
F. Lamps on a Circletime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.John and his imaginary friend play a game. There are n lamps arranged in a circle. Lamps are numbered 1 through n in clockwise order, that is, lamps i and i + 1 are adjacent for any i = 1, \ldots, n - 1, and also lamps n and 1 are adjacent. Initially all lamps are turned off.John and his friend take turns, with John moving first. On his turn John can choose to terminate the game, or to make a move. To make a move, John can choose any positive number k and turn any k lamps of his choosing on. In response to this move, John's friend will choose k consecutive lamps and turn all of them off (the lamps in the range that were off before this move stay off). Note that the value of k is the same as John's number on his last move. For example, if n = 5 and John have just turned three lamps on, John's friend may choose to turn off lamps 1, 2, 3, or 2, 3, 4, or 3, 4, 5, or 4, 5, 1, or 5, 1, 2.After this, John may choose to terminate or move again, and so on. However, John can not make more than 10^4 moves.John wants to maximize the number of lamps turned on at the end of the game, while his friend wants to minimize this number. Your task is to provide a strategy for John to achieve optimal result. Your program will play interactively for John against the jury's interactor program playing for John's friend.Suppose there are n lamps in the game. Let R(n) be the number of turned on lamps at the end of the game if both players act optimally. Your program has to terminate the game with at least R(n) turned on lamps within 10^4 moves. Refer to Interaction section below for interaction details.For technical reasons hacks for this problem are disabled.InteractionInitially your program will be fed a single integer n (1 \leq n \leq 1000) — the number of lamps in the game. Then the interactor will wait for your actions.To make a move, print a line starting with an integer k (1 \leq k \leq n), followed by k distinct integers l_1, \ldots, l_k (1 \leq l_i \leq n) — indices of lamps you want to turn on. The indices may be printed in any order. It is allowed to try to turn on a lamp that is already on (although this will have no effect).If your move was invalid for any reason, or if you have made more than 10^4 moves, the interactor will reply with a line containing a single integer -1. Otherwise, the reply will be a line containing a single integer x (1 \leq x \leq n), meaning that the response was to turn off k consecutive lamps starting from x in clockwise order.To terminate the game instead of making a move, print a line containing a single integer 0. The test will be passed if at this point there are at least R(n) lamps turned on (note that neither R(n), nor the verdict received are not communicated to your program in any way). This action does not count towards the number of moves (that is, it is legal to terminate the game after exactly 10^4 moves).To receive the correct verdict, your program should terminate immediately after printing 0, or after receiving -1 as a response.Don't forget to flush your output after every action.ExamplesInput
3
Output
0
Input
4
1Output
2 1 3
0
NoteWhen n = 3, any John's move can be reversed, thus R(3) = 0, and terminating the game immediately is correct.R(4) = 1, and one strategy to achieve this result is shown in the second sample case.Blank lines in sample interactions are for clarity and should not be printed. | 3
| 0 | 2 seconds | 512 megabytes | ['games', 'implementation', 'interactive', 'math', '*2600'] |
E. Ski Accidentstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputArthur owns a ski resort on a mountain. There are n landing spots on the mountain numbered from 1 to n from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are no directed cycles formed by the tracks. There are at most two tracks leaving each spot, but many tracks may enter the same spot.A skier can start skiing from one spot and stop in another spot if there is a sequence of tracks that lead from the starting spot and end in the ending spot. Unfortunately, recently there were many accidents, because the structure of the resort allows a skier to go through dangerous paths, by reaching high speed and endangering himself and the other customers. Here, a path is called dangerous, if it consists of at least two tracks.Arthur wants to secure his customers by closing some of the spots in a way that there are no dangerous paths in the resort. When a spot is closed, all tracks entering and leaving that spot become unusable. Formally, after closing some of the spots, there should not be a path that consists of two or more tracks.Arthur doesn't want to close too many spots. He will be happy to find any way to close at most \frac{4}{7}n spots so that the remaining part is safe. Help him find any suitable way to do so.InputThe first line contains a single positive integer T — the number of test cases. T test case description follows.The first line of each description contains two integers n and m (1 \leq n \leq 2 \cdot 10^5) — the number of landing spots and tracks respectively.The following m lines describe the tracks. Each of these lines contains two integers x and y (1 \leq x < y \leq n) — indices of the starting and finishing spots for the respective track. It is guaranteed that at most two tracks start at each spot. There may be tracks in which starting and finishing spots both coincide.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single integer k (0 \leq k \leq \frac{4}{7}n) — the number of spots to be closed. In the next line, print k distinct integers — indices of all spots to be closed, in any order.If there are several answers, you may output any of them. Note that you don't have to minimize k. It can be shown that a suitable answer always exists.ExampleInput
2
4 6
1 2
1 3
2 3
2 4
3 4
3 4
7 6
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
3 4
4
4 5 6 7
NoteIn the first sample case, closing any two spots is suitable.In the second sample case, closing only the spot 1 is also suitable. | 2
4 6
1 2
1 3
2 3
2 4
3 4
3 4
7 6
1 2
1 3
2 4
2 5
3 6
3 7
| 2 3 4 4 4 5 6 7 | 2 seconds | 512 megabytes | ['constructive algorithms', 'graphs', 'greedy', '*2500'] |
D. AND, OR and square sumtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGottfried learned about binary number representation. He then came up with this task and presented it to you.You are given a collection of n non-negative integers a_1, \ldots, a_n. You are allowed to perform the following operation: choose two distinct indices 1 \leq i, j \leq n. If before the operation a_i = x, a_j = y, then after the operation a_i = x~\mathsf{AND}~y, a_j = x~\mathsf{OR}~y, where \mathsf{AND} and \mathsf{OR} are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).After all operations are done, compute \sum_{i=1}^n a_i^2 — the sum of squares of all a_i. What is the largest sum of squares you can achieve?InputThe first line contains a single integer n (1 \leq n \leq 2 \cdot 10^5).The second line contains n integers a_1, \ldots, a_n (0 \leq a_i < 2^{20}).OutputPrint a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.ExamplesInput
1
123
Output
15129
Input
3
1 3 5
Output
51
Input
2
349525 699050
Output
1099509530625
NoteIn the first sample no operation can be made, thus the answer is 123^2.In the second sample we can obtain the collection 1, 1, 7, and 1^2 + 1^2 + 7^2 = 51.If x and y are represented in binary with equal number of bits (possibly with leading zeros), then each bit of x~\mathsf{AND}~y is set to 1 if and only if both corresponding bits of x and y are set to 1. Similarly, each bit of x~\mathsf{OR}~y is set to 1 if and only if at least one of the corresponding bits of x and y are set to 1. For example, x = 3 and y = 5 are represented as 011_2 and 101_2 (highest bit first). Then, x~\mathsf{AND}~y = 001_2 = 1, and x~\mathsf{OR}~y = 111_2 = 7. | 1
123
| 15129 | 2 seconds | 512 megabytes | ['bitmasks', 'greedy', 'math', '*1700'] |
C. Even Picturetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLeo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the following conditions are satisfied: The picture is connected, that is, it is possible to get from any gray cell to any other by following a chain of gray cells, with each pair of adjacent cells in the path being neighbours (that is, sharing a side). Each gray cell has an even number of gray neighbours. There are exactly n gray cells with all gray neighbours. The number of other gray cells can be arbitrary (but reasonable, so that they can all be listed).Leo Jr. is now struggling to draw a beautiful picture with a particular choice of n. Help him, and provide any example of a beautiful picture.To output cell coordinates in your answer, assume that the sheet is provided with a Cartesian coordinate system such that one of the cells is chosen to be the origin (0, 0), axes 0x and 0y are orthogonal and parallel to grid lines, and a unit step along any axis in any direction takes you to a neighbouring cell.InputThe only line contains a single integer n (1 \leq n \leq 500) — the number of gray cells with all gray neighbours in a beautiful picture.OutputIn the first line, print a single integer k — the number of gray cells in your picture. For technical reasons, k should not exceed 5 \cdot 10^5.Each of the following k lines should contain two integers — coordinates of a gray cell in your picture. All listed cells should be distinct, and the picture should satisdfy all the properties listed above. All coordinates should not exceed 10^9 by absolute value.One can show that there exists an answer satisfying all requirements with a small enough k.ExampleInput
4
Output
12
1 0
2 0
0 1
1 1
2 1
3 1
0 2
1 2
2 2
3 2
1 3
2 3
NoteThe answer for the sample is pictured below: | 4
| 12 1 0 2 0 0 1 1 1 2 1 3 1 0 2 1 2 2 2 3 2 1 3 2 3 | 2 seconds | 512 megabytes | ['constructive algorithms', '*1500'] |
B. Codeforces Subsequencestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKarl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one.Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from left to right. For example, codeforces contains codeforces a single time, while codeforcesisawesome contains codeforces four times: codeforcesisawesome, codeforcesisawesome, codeforcesisawesome, codeforcesisawesome.Help Karl find any shortest string that contains at least k codeforces subsequences.InputThe only line contains a single integer k (1 \leq k \leq 10^{16}).OutputPrint a shortest string of lowercase English letters that contains at least k codeforces subsequences. If there are several such strings, print any of them.ExamplesInput
1
Output
codeforces
Input
3
Output
codeforcesss | 1
| codeforces | 2 seconds | 512 megabytes | ['brute force', 'constructive algorithms', 'greedy', 'math', 'strings', '*1500'] |
A. C+=time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLeo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change).In a prototype program Leo has two integer variables a and b, initialized with some positive values. He can perform any number of operations "a += b" or "b += a". Leo wants to test handling large integers, so he wants to make the value of either a or b strictly greater than a given value n. What is the smallest number of operations he has to perform?InputThe first line contains a single integer T (1 \leq T \leq 100) — the number of test cases.Each of the following T lines describes a single test case, and contains three integers a, b, n (1 \leq a, b \leq n \leq 10^9) — initial values of a and b, and the value one of the variables has to exceed, respectively.OutputFor each test case print a single integer — the smallest number of operations needed. Separate answers with line breaks.ExampleInput
2
1 2 3
5 4 100
Output
2
7
NoteIn the first case we cannot make a variable exceed 3 in one operation. One way of achieving this in two operations is to perform "b += a" twice. | 2
1 2 3
5 4 100
| 2 7 | 2 seconds | 512 megabytes | ['brute force', 'greedy', 'implementation', 'math', '*800'] |
F2. Flying Sort (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.You are given an array a of n integers (the given array can contain equal elements). You can perform the following operations on array elements: choose any index i (1 \le i \le n) and move the element a[i] to the begin of the array; choose any index i (1 \le i \le n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 2, 9], then the following sequence of operations can be performed: after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 2, 9]; after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 9, 4]. You can perform operations of any type any number of times in any order.Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations must be performed so the array satisfies the inequalities a[1] \le a[2] \le \ldots \le a[n].InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases in the test. Then t test cases follow.Each test case starts with a line containing an integer n (1 \le n \le 2 \cdot 10^5) — the size of the array a.Then follow n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — an array that needs to be sorted by the given operations. The given array can contain equal elements.The sum of n for all test cases in one test does not exceed 2 \cdot 10^5.OutputFor each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.ExampleInput
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
NoteIn the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] \rightarrow [2, 4, 7, 2, 9] \rightarrow [2, 2, 4, 7, 9].In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] \rightarrow [1, 3, 5, 8, 7] \rightarrow [1, 3, 5, 7, 8].In the third test case, the array is already sorted. | 9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
| 2 2 0 0 1 1 1 1 16 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dp', 'greedy', 'sortings', 'two pointers', '*2400'] |
F1. Flying Sort (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: choose any index i (1 \le i \le n) and move the element a[i] to the begin of the array; choose any index i (1 \le i \le n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order.Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] \le a[2] \le \ldots \le a[n].InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases in the test. Then t test cases follow.Each test case starts with a line containing an integer n (1 \le n \le 3000) — length of the array a.Then follow n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.The sum of n for all test cases in one test does not exceed 3000.OutputFor each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.ExampleInput
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
NoteIn the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] \rightarrow [3, 4, 7, 2, 9] \rightarrow [2, 3, 4, 7, 9].In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] \rightarrow [1, 3, 5, 8, 7] \rightarrow [1, 3, 5, 7, 8].In the third test case, the array is already sorted. | 4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
| 2 2 0 2 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'two pointers', '*2100'] |
E. Necklace Assemblytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe store sells n beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them.A necklace is a set of beads connected in a circle.For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can assemble the following necklaces (these are not all possible options): And the following necklaces cannot be assembled from beads sold in the store: The first necklace cannot be assembled because it has three beads "a" (of the two available). The second necklace cannot be assembled because it contains a bead "d", which is not sold in the store. We call a necklace k-beautiful if, when it is turned clockwise by k beads, the necklace remains unchanged. For example, here is a sequence of three turns of a necklace. As you can see, this necklace is, for example, 3-beautiful, 6-beautiful, 9-beautiful, and so on, but it is not 1-beautiful or 2-beautiful.In particular, a necklace of length 1 is k-beautiful for any integer k. A necklace that consists of beads of the same color is also beautiful for any k.You are given the integers n and k, and also the string s containing n lowercase letters of the English alphabet — each letter defines a bead in the store. You can buy any subset of beads and connect them in any order. Find the maximum length of a k-beautiful necklace you can assemble.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases in the test. Then t test cases follow.The first line of each test case contains two integers n and k (1 \le n, k \le 2000).The second line of each test case contains the string s containing n lowercase English letters — the beads in the store.It is guaranteed that the sum of n for all test cases does not exceed 2000.OutputOutput t answers to the test cases. Each answer is a positive integer — the maximum length of the k-beautiful necklace you can assemble.ExampleInput
6
6 3
abcbac
3 6
aaa
7 1000
abczgyo
5 4
ababa
20 10
aaebdbabdbbddaadaadc
20 5
ecbedececacbcbccbdec
Output
6
3
5
4
15
10
NoteThe first test case is explained in the statement.In the second test case, a 6-beautiful necklace can be assembled from all the letters.In the third test case, a 1000-beautiful necklace can be assembled, for example, from beads "abzyo". | 6
6 3
abcbac
3 6
aaa
7 1000
abczgyo
5 4
ababa
20 10
aaebdbabdbbddaadaadc
20 5
ecbedececacbcbccbdec
| 6 3 5 4 15 10 | 2 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'dp', 'graphs', 'greedy', 'number theory', '*1900'] |
D. Task On The Boardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wrote on the board a string s containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.After that, he erased some letters from the string s, and he rewrote the remaining letters in any order. As a result, he got some new string t. You have to find it with some additional information.Suppose that the string t has length m and the characters are numbered from left to right from 1 to m. You are given a sequence of m integers: b_1, b_2, \ldots, b_m, where b_i is the sum of the distances |i-j| from the index i to all such indices j that t_j > t_i (consider that 'a'<'b'<...<'z'). In other words, to calculate b_i, Polycarp finds all such indices j that the index j contains a letter that is later in the alphabet than t_i and sums all the values |i-j|.For example, if t = "abzb", then: since t_1='a', all other indices contain letters which are later in the alphabet, that is: b_1=|1-2|+|1-3|+|1-4|=1+2+3=6; since t_2='b', only the index j=3 contains the letter, which is later in the alphabet, that is: b_2=|2-3|=1; since t_3='z', then there are no indexes j such that t_j>t_i, thus b_3=0; since t_4='b', only the index j=3 contains the letter, which is later in the alphabet, that is: b_4=|4-3|=1. Thus, if t = "abzb", then b=[6,1,0,1].Given the string s and the array b, find any possible string t for which the following two requirements are fulfilled simultaneously: t is obtained from s by erasing some letters (possibly zero) and then writing the rest in any order; the array, constructed from the string t according to the rules above, equals to the array b specified in the input data. InputThe first line contains an integer q (1 \le q \le 100) — the number of test cases in the test. Then q test cases follow.Each test case consists of three lines: the first line contains string s, which has a length from 1 to 50 and consists of lowercase English letters; the second line contains positive integer m (1 \le m \le |s|), where |s| is the length of the string s, and m is the length of the array b; the third line contains the integers b_1, b_2, \dots, b_m (0 \le b_i \le 1225). It is guaranteed that in each test case an answer exists.OutputOutput q lines: the k-th of them should contain the answer (string t) to the k-th test case. It is guaranteed that an answer to each test case exists. If there are several answers, output any.ExampleInput
4
abac
3
2 1 0
abc
1
0
abba
3
1 0 1
ecoosdcefr
10
38 13 24 14 11 5 3 24 17 0
Output
aac
b
aba
codeforces
NoteIn the first test case, such strings t are suitable: "aac', "aab".In the second test case, such trings t are suitable: "a", "b", "c".In the third test case, only the string t equals to "aba" is suitable, but the character 'b' can be from the second or third position. | 4
abac
3
2 1 0
abc
1
0
abba
3
1 0 1
ecoosdcefr
10
38 13 24 14 11 5 3 24 17 0
| aac b aba codeforces | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', 'sortings', '*1800'] |
C. Social Distancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters "1" (the table is occupied) and "0" (the table is empty).Restaurant rules prohibit people to sit at a distance of k or less from each other. That is, if a person sits at the table number i, then all tables with numbers from i-k to i+k (except for the i-th) should be free. In other words, the absolute difference of the numbers of any two occupied tables must be strictly greater than k.For example, if n=8 and k=2, then: strings "10010001", "10000010", "00000000", "00100000" satisfy the rules of the restaurant; strings "10100100", "10011001", "11111111" do not satisfy to the rules of the restaurant, since each of them has a pair of "1" with a distance less than or equal to k=2. In particular, if the state of the restaurant is described by a string without "1" or a string with one "1", then the requirement of the restaurant is satisfied.You are given a binary string s that describes the current state of the restaurant. It is guaranteed that the rules of the restaurant are satisfied for the string s.Find the maximum number of free tables that you can occupy so as not to violate the rules of the restaurant. Formally, what is the maximum number of "0" that can be replaced by "1" such that the requirement will still be satisfied?For example, if n=6, k=1, s= "100010", then the answer to the problem will be 1, since only the table at position 3 can be occupied such that the rules are still satisfied.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases in the test. Then t test cases follow.Each test case starts with a line containing two integers n and k (1 \le k \le n \le 2\cdot 10^5) — the number of tables in the restaurant and the minimum allowed distance between two people.The second line of each test case contains a binary string s of length n consisting of "0" and "1" — a description of the free and occupied tables in the restaurant. The given string satisfy to the rules of the restaurant — the difference between indices of any two "1" is more than k.The sum of n for all test cases in one test does not exceed 2\cdot 10^5.OutputFor each test case output one integer — the number of tables that you can occupy so as not to violate the rules of the restaurant. If additional tables cannot be taken, then, obviously, you need to output 0.ExampleInput
6
6 1
100010
6 2
000000
5 1
10101
3 1
001
2 2
00
1 1
0
Output
1
2
0
1
1
1
NoteThe first test case is explained in the statement.In the second test case, the answer is 2, since you can choose the first and the sixth table.In the third test case, you cannot take any free table without violating the rules of the restaurant. | 6
6 1
100010
6 2
000000
5 1
10101
3 1
001
2 2
00
1 1
0
| 1 2 0 1 1 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*1300'] |
B. Even Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a[0 \ldots n-1] of length n which consists of non-negative integers. Note that array indices start from zero.An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 \le i \le n - 1) the equality i \bmod 2 = a[i] \bmod 2 holds, where x \bmod 2 is the remainder of dividing x by 2.For example, the arrays [0, 5, 2, 1] and [0, 17, 0, 3] are good, and the array [2, 4, 6, 7] is bad, because for i=1, the parities of i and a[i] are different: i \bmod 2 = 1 \bmod 2 = 1, but a[i] \bmod 2 = 4 \bmod 2 = 0.In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent).Find the minimum number of moves in which you can make the array a good, or say that this is not possible.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases in the test. Then t test cases follow.Each test case starts with a line containing an integer n (1 \le n \le 40) — the length of the array a.The next line contains n integers a_0, a_1, \ldots, a_{n-1} (0 \le a_i \le 1000) — the initial array.OutputFor each test case, output a single integer — the minimum number of moves to make the given array a good, or -1 if this is not possible.ExampleInput
4
4
3 2 7 6
3
3 2 6
1
7
7
4 9 2 1 18 3 0
Output
2
1
-1
0
NoteIn the first test case, in the first move, you can swap the elements with indices 0 and 1, and in the second move, you can swap the elements with indices 2 and 3.In the second test case, in the first move, you need to swap the elements with indices 0 and 1.In the third test case, you cannot make the array good. | 4
4
3 2 7 6
3
3 2 6
1
7
7
4 9 2 1 18 3 0
| 2 1 -1 0 | 2 seconds | 256 megabytes | ['greedy', 'math', '*800'] |
A. Short Substringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice guesses the strings that Bob made for her.At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.Bob builds b from a as follows: he writes all the substrings of length 2 of the string a in the order from left to right, and then joins them in the same order into the string b.For example, if Bob came up with the string a="abac", then all the substrings of length 2 of the string a are: "ab", "ba", "ac". Therefore, the string b="abbaac".You are given the string b. Help Alice to guess the string a that Bob came up with. It is guaranteed that b was built according to the algorithm given above. It can be proved that the answer to the problem is unique.InputThe first line contains a single positive integer t (1 \le t \le 1000) — the number of test cases in the test. Then t test cases follow.Each test case consists of one line in which the string b is written, consisting of lowercase English letters (2 \le |b| \le 100) — the string Bob came up with, where |b| is the length of the string b. It is guaranteed that b was built according to the algorithm given above.OutputOutput t answers to test cases. Each answer is the secret string a, consisting of lowercase English letters, that Bob came up with.ExampleInput
4
abbaac
ac
bccddaaf
zzzzzzzzzz
Output
abac
ac
bcdaf
zzzzzz
NoteThe first test case is explained in the statement.In the second test case, Bob came up with the string a="ac", the string a has a length 2, so the string b is equal to the string a.In the third test case, Bob came up with the string a="bcdaf", substrings of length 2 of string a are: "bc", "cd", "da", "af", so the string b="bccddaaf". | 4
abbaac
ac
bccddaaf
zzzzzzzzzz
| abac ac bcdaf zzzzzz | 2 seconds | 256 megabytes | ['implementation', 'strings', '*800'] |
G. Construct the Stringtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's denote the function f(s) that takes a string s consisting of lowercase Latin letters and dots, and returns a string consisting of lowercase Latin letters as follows: let r be an empty string; process the characters of s from left to right. For each character c, do the following: if c is a lowercase Latin letter, append c at the end of the string r; otherwise, delete the last character from r (if r is empty before deleting the last character — the function crashes); return r as the result of the function. You are given two strings s and t. You have to delete the minimum possible number of characters from s so that f(s) = t (and the function does not crash). Note that you aren't allowed to insert new characters into s or reorder the existing ones.InputThe input consists of two lines: the first one contains s — a string consisting of lowercase Latin letters and dots, the second one contains t — a string consisting of lowercase Latin letters (1 \le |t| \le |s| \le 10000).Additional constraint on the input: it is possible to remove some number of characters from s so that f(s) = t.OutputPrint one integer — the minimum possible number of characters you have to delete from s so f(s) does not crash and returns t as the result of the function.ExamplesInput
a.ba.b.
abb
Output
2
Input
.bbac..a.c.cd
bacd
Output
3
Input
c..code..c...o.d.de
code
Output
3
| a.ba.b.
abb
| 2 | 4 seconds | 512 megabytes | ['data structures', 'dp', 'strings', '*2700'] |
F. Jog Around The Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a simple weighted connected undirected graph, consisting of n vertices and m edges.A path in the graph of length k is a sequence of k+1 vertices v_1, v_2, \dots, v_{k+1} such that for each i (1 \le i \le k) the edge (v_i, v_{i+1}) is present in the graph. A path from some vertex v also has vertex v_1=v. Note that edges and vertices are allowed to be included in the path multiple times.The weight of the path is the total weight of edges in it.For each i from 1 to q consider a path from vertex 1 of length i of the maximum weight. What is the sum of weights of these q paths?Answer can be quite large, so print it modulo 10^9+7.InputThe first line contains a three integers n, m, q (2 \le n \le 2000; n - 1 \le m \le 2000; m \le q \le 10^9) — the number of vertices in the graph, the number of edges in the graph and the number of lengths that should be included in the answer.Each of the next m lines contains a description of an edge: three integers v, u, w (1 \le v, u \le n; 1 \le w \le 10^6) — two vertices v and u are connected by an undirected edge with weight w. The graph contains no loops and no multiple edges. It is guaranteed that the given edges form a connected graph.OutputPrint a single integer — the sum of the weights of the paths from vertex 1 of maximum weights of lengths 1, 2, \dots, q modulo 10^9+7.ExamplesInput
7 8 25
1 2 1
2 3 10
3 4 2
1 5 2
5 6 7
6 4 15
5 3 1
1 7 3
Output
4361
Input
2 1 5
1 2 4
Output
60
Input
15 15 23
13 10 12
11 14 12
2 15 5
4 10 8
10 2 4
10 7 5
3 10 1
5 6 11
1 13 8
9 15 4
4 2 9
11 15 1
11 12 14
10 8 12
3 6 11
Output
3250
Input
5 10 10000000
2 4 798
1 5 824
5 2 558
4 1 288
3 4 1890
3 1 134
2 3 1485
4 5 284
3 5 1025
1 2 649
Output
768500592
NoteHere is the graph for the first example: Some maximum weight paths are: length 1: edges (1, 7) — weight 3; length 2: edges (1, 2), (2, 3) — weight 1+10=11; length 3: edges (1, 5), (5, 6), (6, 4) — weight 2+7+15=24; length 4: edges (1, 5), (5, 6), (6, 4), (6, 4) — weight 2+7+15+15=39; \dots So the answer is the sum of 25 terms: 3+11+24+39+\dotsIn the second example the maximum weight paths have weights 4, 8, 12, 16 and 20. | 7 8 25
1 2 1
2 3 10
3 4 2
1 5 2
5 6 7
6 4 15
5 3 1
1 7 3
| 4361 | 2 seconds | 256 megabytes | ['binary search', 'dp', 'geometry', 'graphs', '*2700'] |
E. Two Arraystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a_1, a_2, \dots , a_n and b_1, b_2, \dots , b_m. Array b is sorted in ascending order (b_i < b_{i + 1} for each i from 1 to m - 1).You have to divide the array a into m consecutive subarrays so that, for each i from 1 to m, the minimum on the i-th subarray is equal to b_i. Note that each element belongs to exactly one subarray, and they are formed in such a way: the first several elements of a compose the first subarray, the next several elements of a compose the second subarray, and so on.For example, if a = [12, 10, 20, 20, 25, 30] and b = [10, 20, 30] then there are two good partitions of array a: [12, 10, 20], [20, 25], [30]; [12, 10], [20, 20, 25], [30]. You have to calculate the number of ways to divide the array a. Since the number can be pretty large print it modulo 998244353.InputThe first line contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the length of arrays a and b respectively.The second line contains n integers a_1, a_2, \dots , a_n (1 \le a_i \le 10^9) — the array a.The third line contains m integers b_1, b_2, \dots , b_m (1 \le b_i \le 10^9; b_i < b_{i+1}) — the array b.OutputIn only line print one integer — the number of ways to divide the array a modulo 998244353.ExamplesInput
6 3
12 10 20 20 25 30
10 20 30
Output
2
Input
4 2
1 3 3 7
3 7
Output
0
Input
8 2
1 2 2 2 2 2 2 2
1 2
Output
7
| 6 3
12 10 20 20 25 30
10 20 30
| 2 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'combinatorics', 'constructive algorithms', 'dp', 'two pointers', '*2100'] |
D. Two Divisorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers a_1, a_2, \dots, a_n.For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair.InputThe first line contains single integer n (1 \le n \le 5 \cdot 10^5) — the size of the array a.The second line contains n integers a_1, a_2, \dots, a_n (2 \le a_i \le 10^7) — the array a.OutputTo speed up the output, print two lines with n integers in each line.The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them.ExampleInput
10
2 3 4 5 6 7 8 9 10 24
Output
-1 -1 -1 -1 3 -1 -1 -1 2 2
-1 -1 -1 -1 2 -1 -1 -1 5 3
NoteLet's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7.There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. | 10
2 3 4 5 6 7 8 9 10 24
| -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', 'number theory', '*2000'] |
C. Palindromic Pathstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.InputThe first line contains one integer t (1 \le t \le 200) — the number of test cases.The first line of each test case contains two integers n and m (2 \le n, m \le 30) — the dimensions of the matrix.Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 \le a_{i, j} \le 1).OutputFor each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.ExampleInput
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
NoteThe resulting matrices in the first three test cases: \begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix} | 4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
| 0 3 4 4 | 1.5 seconds | 256 megabytes | ['greedy', 'math', '*1500'] |
B. Shuffletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0.You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i \le c, d \le r_i, and swap a_c and a_d.Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases. Then the description of t testcases follow.The first line of each test case contains three integers n, x and m (1 \le n \le 10^9; 1 \le m \le 100; 1 \le x \le n).Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 \le l_i \le r_i \le n).OutputFor each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end.ExampleInput
3
6 4 3
1 6
2 3
5 5
4 1 2
2 4
1 2
3 3 2
2 3
1 2
Output
6
2
3
NoteIn the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: swap a_k and a_4; swap a_2 and a_2; swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. | 3
6 4 3
1 6
2 3
5 5
4 1 2
2 4
1 2
3 3 2
2 3
1 2
| 6 2 3 | 1 second | 256 megabytes | ['math', 'two pointers', '*1300'] |
A. Shovels and Swordstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.Each tool can be sold for exactly one emerald. How many emeralds can Polycarp earn, if he has a sticks and b diamonds?InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.The only line of each test case contains two integers a and b (0 \le a, b \le 10^9) — the number of sticks and the number of diamonds, respectively.OutputFor each test case print one integer — the maximum number of emeralds Polycarp can earn.ExampleInput
4
4 4
1000000000 0
7 15
8 7
Output
2
0
7
5
NoteIn the first test case Polycarp can earn two emeralds as follows: craft one sword and one shovel.In the second test case Polycarp does not have any diamonds, so he cannot craft anything. | 4
4 4
1000000000 0
7 15
8 7
| 2 0 7 5 | 1 second | 256 megabytes | ['binary search', 'greedy', 'math', '*1100'] |
G. Secure Passwordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Ayush devised yet another scheme to set the password of his lock. The lock has n slots where each slot can hold any non-negative integer. The password P is a sequence of n integers, i-th element of which goes into the i-th slot of the lock.To set the password, Ayush comes up with an array A of n integers each in the range [0, 2^{63}-1]. He then sets the i-th element of P as the bitwise OR of all integers in the array except A_i.You need to guess the password. To make a query, you can choose a non-empty subset of indices of the array and ask the bitwise OR all elements of the array with index in this subset. You can ask no more than 13 queries.InputThe first line of input contains one integer n (2 \le n \le 1000) — the number of slots in the lock.InteractionTo ask a query print a single line: In the beginning print "? c " (without quotes) where c (1 \leq c \leq n) denotes the size of the subset of indices being queried, followed by c distinct space-separated integers in the range [1, n]. For each query, you will receive an integer x — the bitwise OR of values in the array among all the indices queried. If the subset of indices queried is invalid or you exceeded the number of queries then you will get x = -1. In this case, you should terminate the program immediately.When you have guessed the password, print a single line "! " (without quotes), followed by n space-separated integers — the password sequence.Guessing the password does not count towards the number of queries asked.The interactor is not adaptive. The array A does not change with queries.After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack the solution, use the following test format:On the first line print a single integer n (2 \le n \le 1000) — the number of slots in the lock. The next line should contain n space-separated integers in the range [0, 2^{63} - 1] — the array A.ExampleInput
3
1
2
4
Output
? 1 1
? 1 2
? 1 3
! 6 5 3
NoteThe array A in the example is \{{1, 2, 4\}}. The first element of the password is bitwise OR of A_2 and A_3, the second element is bitwise OR of A_1 and A_3 and the third element is bitwise OR of A_1 and A_2. Hence the password sequence is \{{6, 5, 3\}}. | 3
1
2
4
| ? 1 1 ? 1 2 ? 1 3 ! 6 5 3 | 2 seconds | 256 megabytes | ['bitmasks', 'combinatorics', 'constructive algorithms', 'interactive', 'math', '*2800'] |
F. Swaps Againtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid.Each test case consists of an integer n and two arrays a and b, of size n. If after some (possibly zero) operations described below, array a can be transformed into array b, the input is said to be valid. Otherwise, it is invalid.An operation on array a is: select an integer k (1 \le k \le \lfloor\frac{n}{2}\rfloor) swap the prefix of length k with the suffix of length k For example, if array a initially is \{1, 2, 3, 4, 5, 6\}, after performing an operation with k = 2, it is transformed into \{5, 6, 3, 4, 1, 2\}.Given the set of test cases, help them determine if each one is valid or invalid.InputThe first line contains one integer t (1 \le t \le 500) — the number of test cases. The description of each test case is as follows.The first line of each test case contains a single integer n (1 \le n \le 500) — the size of the arrays.The second line of each test case contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^9) — elements of array a.The third line of each test case contains n integers b_1, b_2, ..., b_n (1 \le b_i \le 10^9) — elements of array b.OutputFor each test case, print "Yes" if the given input is valid. Otherwise print "No".You may print the answer in any case.ExampleInput
5
2
1 2
2 1
3
1 2 3
1 2 3
3
1 2 4
1 3 4
4
1 2 3 2
3 1 2 2
3
1 2 3
1 3 2
Output
yes
yes
No
yes
No
NoteFor the first test case, we can swap prefix a[1:1] with suffix a[2:2] to get a=[2, 1].For the second test case, a is already equal to b.For the third test case, it is impossible since we cannot obtain 3 in a.For the fourth test case, we can first swap prefix a[1:1] with suffix a[4:4] to obtain a=[2, 2, 3, 1]. Now we can swap prefix a[1:2] with suffix a[3:4] to obtain a=[3, 1, 2, 2].For the fifth test case, it is impossible to convert a to b. | 5
2
1 2
2 1
3
1 2 3
1 2 3
3
1 2 4
1 3 4
4
1 2 3 2
3 1 2 2
3
1 2 3
1 3 2
| yes yes No yes No | 2 seconds | 256 megabytes | ['constructive algorithms', 'implementation', 'sortings', '*2100'] |
E. Maximum Subsequence Valuetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRidhiman challenged Ashish to find the maximum valued subsequence of an array a of size n consisting of positive integers. The value of a non-empty subsequence of k elements of a is defined as \sum 2^i over all integers i \ge 0 such that at least \max(1, k - 2) elements of the subsequence have the i-th bit set in their binary representation (value x has the i-th bit set in its binary representation if \lfloor \frac{x}{2^i} \rfloor \mod 2 is equal to 1). Recall that b is a subsequence of a, if b can be obtained by deleting some(possibly zero) elements from a.Help Ashish find the maximum value he can get by choosing some subsequence of a.InputThe first line of the input consists of a single integer n (1 \le n \le 500) — the size of a.The next line consists of n space-separated integers — the elements of the array (1 \le a_i \le 10^{18}).OutputPrint a single integer — the maximum value Ashish can get by choosing some subsequence of a.ExamplesInput
3
2 1 3
Output
3Input
3
3 1 4
Output
7Input
1
1
Output
1Input
4
7 7 1 1
Output
7NoteFor the first test case, Ashish can pick the subsequence \{{2, 3}\} of size 2. The binary representation of 2 is 10 and that of 3 is 11. Since \max(k - 2, 1) is equal to 1, the value of the subsequence is 2^0 + 2^1 (both 2 and 3 have 1-st bit set in their binary representation and 3 has 0-th bit set in its binary representation). Note that he could also pick the subsequence \{{3\}} or \{{2, 1, 3\}}.For the second test case, Ashish can pick the subsequence \{{3, 4\}} with value 7.For the third test case, Ashish can pick the subsequence \{{1\}} with value 1.For the fourth test case, Ashish can pick the subsequence \{{7, 7\}} with value 7. | 3
2 1 3
| 3 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', '*1900'] |
D. Solve The Mazetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVivek has encountered a problem. He has a maze that can be represented as an n \times m grid. Each of the grid cells may represent the following: Empty — '.' Wall — '#' Good person — 'G' Bad person — 'B' The only escape from the maze is at cell (n, m).A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.InputThe first line contains one 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, m (1 \le n, m \le 50) — the number of rows and columns in the maze.Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.OutputFor each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"You may print every letter in any case (upper or lower).ExampleInput
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
NoteFor the first and second test cases, all conditions are already satisfied.For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.For the fourth test case, the good person at (1,1) cannot escape.For the fifth test case, Vivek can block the cells (2,3) and (2,2).For the last test case, Vivek can block the destination cell (2, 2). | 6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
| Yes Yes No No Yes Yes | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'implementation', 'shortest paths', '*1700'] |
C. Rotation Matchingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b.Note that a permutation of n elements is a sequence of numbers a_1, a_2, \ldots, a_n, in which every number from 1 to n appears exactly once. The message can be decoded by an arrangement of sequence a and b, such that the number of matching pairs of elements between them is maximum. A pair of elements a_i and b_j is said to match if: i = j, that is, they are at the same index. a_i = b_j His two disciples are allowed to perform the following operation any number of times: choose a number k and cyclically shift one of the permutations to the left or right k times. A single cyclic shift to the left on any permutation c is an operation that sets c_1:=c_2, c_2:=c_3, \ldots, c_n:=c_1 simultaneously. Likewise, a single cyclic shift to the right on any permutation c is an operation that sets c_1:=c_n, c_2:=c_1, \ldots, c_n:=c_{n-1} simultaneously.Help Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.InputThe first line of the input contains a single integer n (1 \le n \le 2 \cdot 10^5) — the size of the arrays.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le n) — the elements of the first permutation.The third line contains n integers b_1, b_2, ..., b_n (1 \le b_i \le n) — the elements of the second permutation.OutputPrint the maximum number of matching pairs of elements after performing the above operations some (possibly zero) times.ExamplesInput
5
1 2 3 4 5
2 3 4 5 1
Output
5Input
5
5 4 3 2 1
1 2 3 4 5
Output
1Input
4
1 3 2 4
4 2 3 1
Output
2NoteFor the first case: b can be shifted to the right by k = 1. The resulting permutations will be \{1, 2, 3, 4, 5\} and \{1, 2, 3, 4, 5\}.For the second case: The operation is not required. For all possible rotations of a and b, the number of matching pairs won't exceed 1.For the third case: b can be shifted to the left by k = 1. The resulting permutations will be \{1, 3, 2, 4\} and \{2, 3, 1, 4\}. Positions 2 and 4 have matching pairs of elements. For all possible rotations of a and b, the number of matching pairs won't exceed 2. | 5
1 2 3 4 5
2 3 4 5 1
| 5 | 1 second | 256 megabytes | ['constructive algorithms', 'data structures', 'greedy', 'implementation', '*1400'] |
B. Trouble Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAshish has n elements arranged in a line. These elements are represented by two integers a_i — the value of the element and b_i — the type of the element (there are only two possible types: 0 and 1). He wants to sort the elements in non-decreasing values of a_i.He can perform the following operation any number of times: Select any two elements i and j such that b_i \ne b_j and swap them. That is, he can only swap two elements of different types in one move. Tell him if he can sort the elements in non-decreasing values of a_i after performing any number of operations.InputThe first line contains one 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 one integer n (1 \le n \le 500) — the size of the arrays.The second line contains n integers a_i (1 \le a_i \le 10^5) — the value of the i-th element.The third line containts n integers b_i (b_i \in \{0, 1\}) — the type of the i-th element.OutputFor each test case, print "Yes" or "No" (without quotes) depending on whether it is possible to sort elements in non-decreasing order of their value.You may print each letter in any case (upper or lower).ExampleInput
5
4
10 20 20 30
0 1 0 1
3
3 1 2
0 1 1
4
2 2 4 8
1 1 1 1
3
5 15 4
0 0 0
4
20 10 100 50
1 0 0 1
Output
Yes
Yes
Yes
No
Yes
NoteFor the first case: The elements are already in sorted order.For the second case: Ashish may first swap elements at positions 1 and 2, then swap elements at positions 2 and 3.For the third case: The elements are already in sorted order.For the fourth case: No swap operations may be performed as there is no pair of elements i and j such that b_i \ne b_j. The elements cannot be sorted.For the fifth case: Ashish may swap elements at positions 3 and 4, then elements at positions 1 and 2. | 5
4
10 20 20 30
0 1 0 1
3
3 1 2
0 1 1
4
2 2 4 8
1 1 1 1
3
5 15 4
0 0 0
4
20 10 100 50
1 0 0 1
| Yes Yes Yes No Yes | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*1300'] |
A. Matrix Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAshish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state.In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends.If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.InputThe first line consists of a single integer t (1 \le t \le 50) — the number of test cases. The description of the test cases follows.The first line of each test case consists of two space-separated integers n, m (1 \le n, m \le 50) — the number of rows and columns in the matrix.The following n lines consist of m integers each, the j-th integer on the i-th line denoting a_{i,j} (a_{i,j} \in \{0, 1\}).OutputFor each test case if Ashish wins the game print "Ashish" otherwise print "Vivek" (without quotes).ExampleInput
4
2 2
0 0
0 0
2 2
0 0
0 1
2 3
1 0 1
1 1 0
3 3
1 0 0
0 0 0
1 0 0
Output
Vivek
Ashish
Vivek
Ashish
NoteFor the first case: One possible scenario could be: Ashish claims cell (1, 1), Vivek then claims cell (2, 2). Ashish can neither claim cell (1, 2), nor cell (2, 1) as cells (1, 1) and (2, 2) are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win. For the second case: Ashish claims cell (1, 1), the only cell that can be claimed in the first move. After that Vivek has no moves left.For the third case: Ashish cannot make a move, so Vivek wins.For the fourth case: If Ashish claims cell (2, 3), Vivek will have no moves left. | 4
2 2
0 0
0 0
2 2
0 0
0 1
2 3
1 0 1
1 1 0
3 3
1 0 0
0 0 0
1 0 0
| Vivek Ashish Vivek Ashish | 1 second | 256 megabytes | ['games', 'greedy', 'implementation', '*1100'] |
E. X-ORtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem!Ehab has a hidden permutation p of length n consisting of the elements from 0 to n-1. You, for some reason, want to figure out the permutation. To do that, you can give Ehab 2 different indices i and j, and he'll reply with (p_i|p_j) where | is the bitwise-or operation.Ehab has just enough free time to answer 4269 questions, and while he's OK with answering that many questions, he's too lazy to play your silly games, so he'll fix the permutation beforehand and will not change it depending on your queries. Can you guess the permutation?InputThe only line contains the integer n (3 \le n \le 2048) — the length of the permutation.InteractionTo ask a question, print "? i j" (without quotes, i \neq j) Then, you should read the answer, which will be (p_i|p_j).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.To print the answer, print "! p_1 p_2 \ldots p_n" (without quotes). Note that answering doesn't count as one of the 4269 queries.After printing a query or printing the answer, do not forget to output end of line and flush the output. Otherwise, you will get idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; See the documentation for other languages.Hacks:The first line should contain the integer n (3 \le n \le 2^{11}) — the length of the permutation p.The second line should contain n space-separated integers p_1, p_2, \ldots, p_n (0 \le p_i < n) — the elements of the permutation p.ExampleInput
3
1
3
2Output
? 1 2
? 1 3
? 2 3
! 1 0 2NoteIn the first sample, the permutation is [1,0,2]. You start by asking about p_1|p_2 and Ehab replies with 1. You then ask about p_1|p_3 and Ehab replies with 3. Finally, you ask about p_2|p_3 and Ehab replies with 2. You then guess the permutation. | 3
1
3
2 | ? 1 2 ? 1 3 ? 2 3 ! 1 0 2 | 1 second | 256 megabytes | ['bitmasks', 'constructive algorithms', 'divide and conquer', 'interactive', 'probabilities', '*2700'] |
D. Ehab's Last Corollarytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a connected undirected graph with n vertices and an integer k, you have to either: either find an independent set that has exactly \lceil\frac{k}{2}\rceil vertices. or find a simple cycle of length at most k. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.InputThe first line contains three integers n, m, and k (3 \le k \le n \le 10^5, n-1 \le m \le 2 \cdot 10^5) — the number of vertices and edges in the graph, and the parameter k from the statement.Each of the next m lines contains two integers u and v (1 \le u,v \le n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print 1, followed by a line containing \lceil\frac{k}{2}\rceil distinct integers not exceeding n, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print 2, followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInput
4 4 3
1 2
2 3
3 4
4 1
Output
1
1 3 Input
4 5 3
1 2
2 3
3 4
4 1
2 4
Output
2
3
2 3 4 Input
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
Output
2
3
1 2 3 Input
5 4 5
1 2
1 3
2 4
2 5
Output
1
1 4 5 NoteIn the first sample:Notice that printing the independent set \{2,4\} is also OK, but printing the cycle 1-2-3-4 isn't, because its length must be at most 3.In the second sample:Notice that printing the independent set \{1,3\} or printing the cycle 2-1-4 is also OK.In the third sample:In the fourth sample: | 4 4 3
1 2
2 3
3 4
4 1
| 1 1 3 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', 'greedy', 'implementation', 'trees', '*2100'] |
C. Ehab and Prefix MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array a of length n, find another array, b, of length n such that: for each i (1 \le i \le n) MEX(\{b_1, b_2, \ldots, b_i\})=a_i. The MEX of a set of integers is the smallest non-negative integer that doesn't belong to this set.If such array doesn't exist, determine this.InputThe first line contains an integer n (1 \le n \le 10^5) — the length of the array a.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le i) — the elements of the array a. It's guaranteed that a_i \le a_{i+1} for 1\le i < n. OutputIf there's no such array, print a single line containing -1.Otherwise, print a single line containing n integers b_1, b_2, \ldots, b_n (0 \le b_i \le 10^6)If there are multiple answers, print any.ExamplesInput
3
1 2 3
Output
0 1 2 Input
4
0 0 0 2
Output
1 3 4 0 Input
3
1 1 3
Output
0 2 1 NoteIn the second test case, other answers like [1,1,1,0], for example, are valid. | 3
1 2 3
| 0 1 2 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', '*1600'] |
B. Most socially-distanced subsequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a permutation p of length n, find its subsequence s_1, s_2, \ldots, s_k of length at least 2 such that: |s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k| is as big as possible over all subsequences of p with length at least 2. Among all such subsequences, choose the one whose length, k, is as small as possible. If multiple subsequences satisfy these conditions, you are allowed to find any of them.A sequence a is a subsequence of an array b if a can be obtained from b by deleting some (possibly, zero or all) elements.A permutation of length n is an array of length n in which every element from 1 to n occurs exactly once.InputThe first line contains an integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (2 \le n \le 10^5) — the length of the permutation p.The second line of each test case contains n integers p_1, p_2, \ldots, p_{n} (1 \le p_i \le n, p_i are distinct) — the elements of the permutation p.The sum of n across the test cases doesn't exceed 10^5.OutputFor each test case, the first line should contain the length of the found subsequence, k. The second line should contain s_1, s_2, \ldots, s_k — its elements.If multiple subsequences satisfy these conditions, you are allowed to find any of them.ExampleInput
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
NoteIn the first test case, there are 4 subsequences of length at least 2: [3,2] which gives us |3-2|=1. [3,1] which gives us |3-1|=2. [2,1] which gives us |2-1|=1. [3,2,1] which gives us |3-2|+|2-1|=2. So the answer is either [3,1] or [3,2,1]. Since we want the subsequence to be as short as possible, the answer is [3,1]. | 2
3
3 2 1
4
1 3 4 2
| 2 3 1 3 1 4 2 | 1 second | 256 megabytes | ['greedy', 'two pointers', '*1300'] |
A. XXXXXtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist.An array a is a subarray of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputThe first line contains an integer t (1 \le t \le 5) — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains 2 integers n and x (1 \le n \le 10^5, 1 \le x \le 10^4) — the number of elements in the array a and the number that Ehab hates.The second line contains n space-separated integers a_1, a_2, \ldots, a_{n} (0 \le a_i \le 10^4) — the elements of the array a.OutputFor each testcase, print the length of the longest subarray whose sum isn't divisible by x. If there's no such subarray, print -1.ExampleInput
3
3 3
1 2 3
3 4
1 2 3
2 2
0 6
Output
2
3
-1
NoteIn the first test case, the subarray [2,3] has sum of elements 5, which isn't divisible by 3.In the second test case, the sum of elements of the whole array is 6, which isn't divisible by 4.In the third test case, all subarrays have an even sum, so the answer is -1. | 3
3 3
1 2 3
3 4
1 2 3
2 2
0 6
| 2 3 -1 | 1 second | 256 megabytes | ['brute force', 'data structures', 'number theory', 'two pointers', '*1200'] |
F. Rotating Substringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t. You can perform the following operation on s any number of times to achieve it — Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position. For example, on rotating the substring [2,4] , string "abcde" becomes "adbce". A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Find the minimum number of operations required to convert s to t, or determine that it's impossible.InputThe first line of the input contains a single integer t (1\leq t \leq 2000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1\leq n \leq 2000) — the length of the strings. The second and the third lines contain strings s and t respectively.The sum of n over all the test cases does not exceed 2000.OutputFor each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.ExampleInput
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
NoteFor the 1-st test case, since s and t are equal, you don't need to apply any operation.For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.For the 6-th test case, it is not possible to convert string s to t. | 6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
| 0 1 1 2 1 -1 | 2 seconds | 256 megabytes | ['dp', 'strings', '*2600'] |
E. Tree Shufflingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAshish has a tree consisting of n nodes numbered 1 to n rooted at node 1. The i-th node in the tree has a cost a_i, and binary digit b_i is written in it. He wants to have binary digit c_i written in the i-th node in the end.To achieve this, he can perform the following operation any number of times: Select any k nodes from the subtree of any node u, and shuffle the digits in these nodes as he wishes, incurring a cost of k \cdot a_u. Here, he can choose k ranging from 1 to the size of the subtree of u. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node u has digit c_u written in it, or determine that it is impossible.InputFirst line contains a single integer n (1 \le n \le 2 \cdot 10^5) denoting the number of nodes in the tree.i-th line of the next n lines contains 3 space-separated integers a_i, b_i, c_i (1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1) — the cost of the i-th node, its initial digit and its goal digit.Each of the next n - 1 lines contain two integers u, v (1 \leq u, v \leq n, \text{ } u \ne v), meaning that there is an edge between nodes u and v in the tree.OutputPrint the minimum total cost to make every node reach its target digit, and -1 if it is impossible.ExamplesInput
5
1 0 1
20 1 0
300 0 1
4000 0 0
50000 1 0
1 2
2 3
2 4
1 5
Output
4Input
5
10000 0 1
2000 1 0
300 0 1
40 0 0
1 1 0
1 2
2 3
2 4
1 5
Output
24000Input
2
109 0 1
205 0 1
1 2
Output
-1NoteThe tree corresponding to samples 1 and 2 are: In sample 1, we can choose node 1 and k = 4 for a cost of 4 \cdot 1 = 4 and select nodes {1, 2, 3, 5}, shuffle their digits and get the desired digits in every node.In sample 2, we can choose node 1 and k = 2 for a cost of 10000 \cdot 2, select nodes {1, 5} and exchange their digits, and similarly, choose node 2 and k = 2 for a cost of 2000 \cdot 2, select nodes {2, 3} and exchange their digits to get the desired digits in every node.In sample 3, it is impossible to get the desired digits, because there is no node with digit 1 initially. | 5
1 0 1
20 1 0
300 0 1
4000 0 0
50000 1 0
1 2
2 3
2 4
1 5
| 4 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'greedy', 'trees', '*2000'] |
D. Guess The Maximumstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Ayush devised a new scheme to set the password of his lock. The lock has k slots where each slot can hold integers from 1 to n. The password P is a sequence of k integers each in the range [1, n], i-th element of which goes into the i-th slot of the lock.To set the password of his lock, Ayush comes up with an array A of n integers each in the range [1, n] (not necessarily distinct). He then picks k non-empty mutually disjoint subsets of indices S_1, S_2, ..., S_k (S_i \underset{i \neq j} \cap S_j = \emptyset) and sets his password as P_i = \max\limits_{j \notin S_i} A[j]. In other words, the i-th integer in the password is equal to the maximum over all elements of A whose indices do not belong to S_i.You are given the subsets of indices chosen by Ayush. You need to guess the password. To make a query, you can choose a non-empty subset of indices of the array and ask the maximum of all elements of the array with index in this subset. You can ask no more than 12 queries.InputThe first line of the input contains a single integer t (1 \leq t \leq 10) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and k (2 \leq n \leq 1000, 1 \leq k \leq n) — the size of the array and the number of subsets. k lines follow. The i-th line contains an integer c (1 \leq c \lt n) — the size of subset S_i, followed by c distinct integers in the range [1, n] — indices from the subset S_i.It is guaranteed that the intersection of any two subsets is empty.InteractionTo ask a query print a single line: In the beginning print "? c " (without quotes) where c (1 \leq c \leq n) denotes the size of the subset of indices being queried, followed by c distinct space-separated integers in the range [1, n]. For each query, you will receive an integer x — the maximum of value in the array among all the indices queried. If the subset of indices queried is invalid or you exceeded the number of queries (for example one of the indices is greater than n) then you will get x = -1. In this case, you should terminate the program immediately.When you have guessed the password, print a single line "! " (without quotes), followed by k space-separated integers — the password sequence.Guessing the password does not count towards the number of queries asked.After this, you should read a string. If you guess the password correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases. If the guessed password is incorrect, you will receive the string "Incorrect". In this case, you should terminate the program immediately.The interactor is not adaptive. The array A does not change with queries.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 documentation for other languages.HacksTo hack the solution use the following test format:The first line of the input should contain a single integer t (1 \leq t \leq 10) — the number of test cases. The first line of each test case should contain two integers n and k (2 \leq n \leq 1000, 1 \leq k \leq n) — the size of the array and the number of subsets. The next line should consist of n space separated integers in the range [1, n] — the array A. k lines should follow. The i-th line should contain an integer c (1 \leq c \lt n) — the size of subset S_i, followed by c distinct integers in the range [1, n] — indices from the subset S_i.The intersection of any two subsets has to be empty.ExampleInput
1
4 2
2 1 3
2 2 4
1
2
3
4
CorrectOutput
? 1 1
? 1 2
? 1 3
? 1 4
! 4 3NoteThe array A in the example is [1, 2, 3, 4]. The length of the password is 2. The first element of the password is the maximum of A[2], A[4] (since the first subset contains indices 1 and 3, we take maximum over remaining indices). The second element of the password is the maximum of A[1], A[3] (since the second subset contains indices 2, 4).Do not forget to read the string "Correct" / "Incorrect" after guessing the password. | 1
4 2
2 1 3
2 2 4
1
2
3
4
Correct | ? 1 1 ? 1 2 ? 1 3 ? 1 4 ! 4 3 | 2 seconds | 256 megabytes | ['binary search', 'implementation', 'interactive', 'math', '*2100'] |
C. Game On Leavestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyush and Ashish play a game on an unrooted tree consisting of n nodes numbered 1 to n. Players make the following move in turns: Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to 1. A tree is a connected undirected graph without cycles.There is a special node numbered x. The player who removes this node wins the game. Ayush moves first. Determine the winner of the game if each player plays optimally.InputThe first line of the input contains a single integer t (1 \leq t \leq 10) — the number of testcases. The description of the test cases follows.The first line of each testcase contains two integers n and x (1\leq n \leq 1000, 1 \leq x \leq n) — the number of nodes in the tree and the special node respectively.Each of the next n-1 lines contain two integers u, v (1 \leq u, v \leq n, \text{ } u \ne v), meaning that there is an edge between nodes u and v in the tree.OutputFor every test case, if Ayush wins the game, print "Ayush", otherwise print "Ashish" (without quotes).ExamplesInput
1
3 1
2 1
3 1
Output
Ashish
Input
1
3 2
1 2
1 3
Output
Ayush
NoteFor the 1st test case, Ayush can only remove node 2 or 3, after which node 1 becomes a leaf node and Ashish can remove it in his turn.For the 2nd test case, Ayush can remove node 2 in the first move itself. | 1
3 1
2 1
3 1
| Ashish | 2 seconds | 256 megabytes | ['games', 'trees', '*1600'] |
B. Subsequence Hatetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputShubham has a binary string s. A binary string is a string containing only characters "0" and "1".He can perform the following operation on the string any amount of times: Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. A string is called good if it does not contain "010" or "101" as a subsequence — for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.InputThe first line of the input contains a single integer t (1\le t \le 100) — the number of test cases.Each of the next t lines contains a binary string s (1 \le |s| \le 1000).OutputFor every string, output the minimum number of operations required to make it good.ExampleInput
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
NoteIn test cases 1, 2, 5, 6 no operations are required since they are already good strings.For the 3rd test case: "001" can be achieved by flipping the first character — and is one of the possible ways to get a good string.For the 4th test case: "000" can be achieved by flipping the second character — and is one of the possible ways to get a good string.For the 7th test case: "000000" can be achieved by flipping the third and fourth characters — and is one of the possible ways to get a good string. | 7
001
100
101
010
0
1
001100
| 0 0 1 1 0 0 2 | 1 second | 256 megabytes | ['implementation', 'strings', '*1400'] |
A. Odd Selectiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputShubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.Tell him whether he can do so.InputThe first line of the input 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 and x (1 \le x \le n \le 1000) — the length of the array and the number of elements you need to choose.The next line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 1000) — elements of the array.OutputFor each test case, print "Yes" or "No" depending on whether it is possible to choose x elements such that their sum is odd.You may print every letter in any case you want.ExampleInput
5
1 1
999
1 1
1000
2 1
51 50
2 2
51 50
3 3
101 102 103
Output
Yes
No
Yes
Yes
No
NoteFor 1st case: We must select element 999, and the sum is odd.For 2nd case: We must select element 1000, so overall sum is not odd.For 3rd case: We can select element 51.For 4th case: We must select both elements 50 and 51 — so overall sum is odd.For 5th case: We must select all elements — but overall sum is not odd. | 5
1 1
999
1 1
1000
2 1
51 50
2 2
51 50
3 3
101 102 103
| Yes No Yes Yes No | 1 second | 256 megabytes | ['brute force', 'implementation', 'math', '*1200'] |
C. Johnny and Another Rating Droptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of 5 = 101_2 and 14 = 1110_2 equals to 3, since 0101 and 1110 differ in 3 positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of consecutive integers from 0 to n. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.InputThe input consists of multiple test cases. The first line contains one integer t (1 \leq t \leq 10\,000) — the number of test cases. The following t lines contain a description of test cases.The first and only line in each test case contains a single integer n (1 \leq n \leq 10^{18}).OutputOutput t lines. For each test case, you should output a single line with one integer — the unfairness of the contest if the rating sequence equals to 0, 1, ..., n - 1, n.ExampleInput
5
5
7
11
1
2000000000000
Output
8
11
19
1
3999999999987
NoteFor n = 5 we calculate unfairness of the following sequence (numbers from 0 to 5 written in binary with extra leading zeroes, so they all have the same length): 000 001 010 011 100 101 The differences are equal to 1, 2, 1, 3, 1 respectively, so unfairness is equal to 1 + 2 + 1 + 3 + 1 = 8. | 5
5
7
11
1
2000000000000
| 8 11 19 1 3999999999987 | 1 second | 256 megabytes | ['bitmasks', 'greedy', 'math', '*1400'] |
B. Johnny and His Hobbiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmong Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble.There is a set S containing very important numbers on his dad's desk. The minute Johnny heard about it, he decided that it's a good idea to choose a positive integer k and replace each element s of the set S with s \oplus k (\oplus denotes the exclusive or operation). Help him choose such k that Johnny's dad will not see any difference after his son is done playing (i.e. Johnny will get the same set as before playing). It is possible that no such number exists. It is also possible that there are many of them. In such a case, output the smallest one. Note that the order of elements in a set doesn't matter, i.e. set \{1, 2, 3\} equals to set \{2, 1, 3\}.Formally, find the smallest positive integer k such that \{s \oplus k | s \in S\} = S or report that there is no such number.For example, if S = \{1, 3, 4\} and k = 2, new set will be equal to \{3, 1, 6\}. If S = \{0, 1, 2, 3\} and k = 1, after playing set will stay the same.InputIn the first line of input, there is a single integer t (1 \leq t \leq 1024), the number of test cases. In the next lines, t test cases follow. Each of them consists of two lines. In the first line there is a single integer n (1 \leq n \leq 1024) denoting the number of elements in set S. Second line consists of n distinct integers s_i (0 \leq s_i < 1024), elements of S.It is guaranteed that the sum of n over all test cases will not exceed 1024.OutputPrint t lines; i-th line should contain the answer to the i-th test case, the minimal positive integer k satisfying the conditions or -1 if no such k exists.ExampleInput
6
4
1 0 2 3
6
10 7 14 8 3 12
2
0 2
3
1 2 3
6
1 4 6 10 11 12
2
0 1023
Output
1
4
2
-1
-1
1023
NoteIn the first test case, the answer is 1 because it is a minimum positive integer and it satisfies all the conditions. | 6
4
1 0 2 3
6
10 7 14 8 3 12
2
0 2
3
1 2 3
6
1 4 6 10 11 12
2
0 1023
| 1 4 2 -1 -1 1023 | 1 second | 256 megabytes | ['bitmasks', 'brute force', '*1200'] |
A. Johnny and Ancient Computertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can multiply or divide your number by 2, 4 or 8, and division is only allowed if the number is divisible by the chosen divisor. Formally, if the register contains a positive integer x, in one operation it can be replaced by one of the following: x \cdot 2 x \cdot 4 x \cdot 8 x / 2, if x is divisible by 2 x / 4, if x is divisible by 4 x / 8, if x is divisible by 8 For example, if x = 6, in one operation it can be replaced by 12, 24, 48 or 3. Value 6 isn't divisible by 4 or 8, so there're only four variants of replacement.Now Johnny wonders how many operations he needs to perform if he puts a in the register and wants to get b at the end.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 1000) — the number of test cases. The following t lines contain a description of test cases.The first and only line in each test case contains integers a and b (1 \leq a, b \leq 10^{18}) — the initial and target value of the variable, respectively.OutputOutput t lines, each line should contain one integer denoting the minimum number of operations Johnny needs to perform. If Johnny cannot get b at the end, then write -1.ExampleInput
10
10 5
11 44
17 21
1 1
96 3
2 128
1001 1100611139403776
1000000000000000000 1000000000000000000
7 1
10 8
Output
1
1
-1
0
2
2
14
0
-1
-1
NoteIn the first test case, Johnny can reach 5 from 10 by using the shift to the right by one (i.e. divide by 2).In the second test case, Johnny can reach 44 from 11 by using the shift to the left by two (i.e. multiply by 4).In the third test case, it is impossible for Johnny to reach 21 from 17.In the fourth test case, initial and target values are equal, so Johnny has to do 0 operations.In the fifth test case, Johnny can reach 3 from 96 by using two shifts to the right: one by 2, and another by 3 (i.e. divide by 4 and by 8). | 10
10 5
11 44
17 21
1 1
96 3
2 128
1001 1100611139403776
1000000000000000000 1000000000000000000
7 1
10 8
| 1 1 -1 0 2 2 14 0 -1 -1 | 1 second | 256 megabytes | ['implementation', '*1000'] |
F. Johnny and New Toytime limit per test15 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputJohnny has a new toy. As you may guess, it is a little bit extraordinary. The toy is a permutation P of numbers from 1 to n, written in one row next to each other. For each i from 1 to n - 1 between P_i and P_{i + 1} there is a weight W_i written, and those weights form a permutation of numbers from 1 to n - 1. There are also extra weights W_0 = W_n = 0.The instruction defines subsegment [L, R] as good if W_{L - 1} < W_i and W_R < W_i for any i in \{L, L + 1, \ldots, R - 1\}. For such subsegment it also defines W_M as minimum of set \{W_L, W_{L + 1}, \ldots, W_{R - 1}\}. Now the fun begins. In one move, the player can choose one of the good subsegments, cut it into [L, M] and [M + 1, R] and swap the two parts. More precisely, before one move the chosen subsegment of our toy looks like: W_{L - 1}, P_L, W_L, \ldots, W_{M - 1}, P_M, W_M, P_{M + 1}, W_{M + 1}, \ldots, W_{R - 1}, P_R, W_R and afterwards it looks like this: W_{L - 1}, P_{M + 1}, W_{M + 1}, \ldots, W_{R - 1}, P_R, W_M, P_L, W_L, \ldots, W_{M - 1}, P_M, W_R Such a move can be performed multiple times (possibly zero), and the goal is to achieve the minimum number of inversions in P. Johnny's younger sister Megan thinks that the rules are too complicated, so she wants to test her brother by choosing some pair of indices X and Y, and swapping P_X and P_Y (X might be equal Y). After each sister's swap, Johnny wonders, what is the minimal number of inversions that he can achieve, starting with current P and making legal moves?You can assume that the input is generated randomly. P and W were chosen independently and equiprobably over all permutations; also, Megan's requests were chosen independently and equiprobably over all pairs of indices.InputThe first line contains single integer n (2 \leq n \leq 2 \cdot 10^5) denoting the length of the toy.The second line contains n distinct integers P_1, P_2, \ldots, P_n (1 \leq P_i \leq n) denoting the initial permutation P. The third line contains n - 1 distinct integers W_1, W_2, \ldots, W_{n - 1} (1 \leq W_i \leq n - 1) denoting the weights.The fourth line contains single integer q (1 \leq q \leq 5 \cdot 10^4) — the number of Megan's swaps. The following q lines contain two integers X and Y (1 \leq X, Y \leq n) — the indices of elements of P to swap. The queries aren't independent; after each of them, the permutation is changed.OutputOutput q lines. The i-th line should contain exactly one integer — the minimum number of inversions in permutation, which can be obtained by starting with the P after first i queries and making moves described in the game's instruction.ExamplesInput
3
3 2 1
2 1
3
1 3
3 2
3 1
Output
0
1
0
Input
5
4 3 2 5 1
3 2 1 4
7
5 4
5 2
1 5
2 4
2 4
4 3
3 3
Output
3
1
2
1
2
3
3
NoteConsider the first sample. After the first query, P is sorted, so we already achieved a permutation with no inversions. After the second query, P is equal to [1, 3, 2], it has one inversion, it can be proven that it is impossible to achieve 0 inversions. In the end, P is equal to [2, 3, 1]; we can make a move on the whole permutation, as it is a good subsegment itself, which results in P equal to [1, 2, 3], which has 0 inversions. | 3
3 2 1
2 1
3
1 3
3 2
3 1
| 0 1 0 | 15 seconds | 1024 megabytes | ['data structures', 'implementation', 'math', '*3300'] |
E. James and the Chasetime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJames Bond has a new plan for catching his enemy. There are some cities and directed roads between them, such that it is possible to travel between any two cities using these roads. When the enemy appears in some city, Bond knows her next destination but has no idea which path she will choose to move there. The city a is called interesting, if for each city b, there is exactly one simple path from a to b. By a simple path, we understand a sequence of distinct cities, such that for every two neighboring cities, there exists a directed road from the first to the second city. Bond's enemy is the mistress of escapes, so only the chase started in an interesting city gives the possibility of catching her. James wants to arrange his people in such cities. However, if there are not enough interesting cities, the whole action doesn't make sense since Bond's people may wait too long for the enemy.You are responsible for finding all the interesting cities or saying that there is not enough of them. By not enough, James means strictly less than 20\% of all cities. InputThe first line contains one integer t (1 \leq t \leq 2\,000) — the number of test cases. Each test case is described as follows:The first line contains two integers n and m (1 \leq n \le 10^5, 0 \leq m \le 2 \cdot 10^5) — the number of cities and roads between them. Each of the following m lines contains two integers u, v (u \neq v; 1 \leq u, v \leq n), which denote that there is a directed road from u to v.You can assume that between each ordered pair of cities there is at most one road. The sum of n over all test cases doesn't exceed 10^5, and the sum of m doesn't exceed 2 \cdot 10^5.OutputIf strictly less than 20\% of all cities are interesting, print -1. Otherwise, let k be the number of interesting cities. Print k distinct integers in increasing order — the indices of interesting cities.ExampleInput
4
3 3
1 2
2 3
3 1
3 6
1 2
2 1
2 3
3 2
1 3
3 1
7 10
1 2
2 3
3 1
1 4
4 5
5 1
4 6
6 7
7 4
6 1
6 8
1 2
2 3
3 4
4 5
5 6
6 1
6 2
5 1
Output
1 2 3
-1
1 2 3 5
-1
NoteIn all drawings, if a city is colored green, then it is interesting; otherwise, it is colored red.In the first sample, each city is interesting. In the second sample, no city is interesting. In the third sample, cities 1, 2, 3 and 5 are interesting. In the last sample, only the city 1 is interesting. It is strictly less than 20\% of all cities, so the answer is -1. | 4
3 3
1 2
2 3
3 1
3 6
1 2
2 1
2 3
3 2
1 3
3 1
7 10
1 2
2 3
3 1
1 4
4 5
5 1
4 6
6 7
7 4
6 1
6 8
1 2
2 3
3 4
4 5
5 6
6 1
6 2
5 1
| 1 2 3 -1 1 2 3 5 -1 | 2.5 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'probabilities', 'trees', '*3000'] |
D. Johnny and Jamestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJames Bond, Johnny's favorite secret agent, has a new mission. There are n enemy bases, each of them is described by its coordinates so that we can think about them as points in the Cartesian plane. The bases can communicate with each other, sending a signal, which is the ray directed from the chosen point to the origin or in the opposite direction. The exception is the central base, which lies at the origin and can send a signal in any direction. When some two bases want to communicate, there are two possible scenarios. If they lie on the same line with the origin, one of them can send a signal directly to the other one. Otherwise, the signal is sent from the first base to the central, and then the central sends it to the second base. We denote the distance between two bases as the total Euclidean distance that a signal sent between them has to travel.Bond can damage all but some k bases, which he can choose arbitrarily. A damaged base can't send or receive the direct signal but still can pass it between two working bases. In particular, James can damage the central base, and the signal can still be sent between any two undamaged bases as before, so the distance between them remains the same. What is the maximal sum of the distances between all pairs of remaining bases that 007 can achieve by damaging exactly n - k of them?InputThe first line contains two integers n and k (2 \leq k \leq n \leq 5 \cdot 10^5) — the total number of bases and number of bases that have to remain, respectively.Each of the next n lines contains two integers x and y (-10^9 \leq x, y \leq 10^9), i-th line contains coordinates of the i-th base. You can assume that no two points coincide and that one of them is (0, 0).OutputYou should output one number — the maximal possible sum of distances between all pairs of some k from given bases. Your answer will be accepted if the absolute or relative error is less than 10^{-6}.ExamplesInput
6 2
0 0
1 1
2 2
3 3
0 1
0 2
Output
6.24264069
Input
6 5
0 0
1 1
2 2
3 3
0 1
0 2
Output
32.62741700
Input
13 10
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
0 -2
0 1
0 2
Output
237.00000000
Input
10 5
2 2
4 4
3 5
6 10
0 5
0 0
5 0
10 0
0 10
4 7
Output
181.52406315
NoteIn the first example, in an optimal solution Bond doesn't destroy bases with indices 4 and 6 (marked in orange): The following picture represents an optimal solution for the second example. These bases are are not destroyed: 2, 3, 4, 5, 6 (marked in orange). An optimal solution for the third test is visible in the picture. Only bases 3, 4, 5 are destroyed. Again, the not destroyed bases are marked in orange. | 6 2
0 0
1 1
2 2
3 3
0 1
0 2
| 6.24264069 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', 'trees', '*2900'] |
C. Johnny and Megan's Necklacetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputJohnny's younger sister Megan had a birthday recently. Her brother has bought her a box signed as "Your beautiful necklace — do it yourself!". It contains many necklace parts and some magic glue. The necklace part is a chain connecting two pearls. Color of each pearl can be defined by a non-negative integer. The magic glue allows Megan to merge two pearls (possibly from the same necklace part) into one. The beauty of a connection of pearls in colors u and v is defined as follows: let 2^k be the greatest power of two dividing u \oplus v — exclusive or of u and v. Then the beauty equals k. If u = v, you may assume that beauty is equal to 20.Each pearl can be combined with another at most once. Merging two parts of a necklace connects them. Using the glue multiple times, Megan can finally build the necklace, which is a cycle made from connected necklace parts (so every pearl in the necklace is combined with precisely one other pearl in it). The beauty of such a necklace is the minimum beauty of a single connection in it. The girl wants to use all available necklace parts to build exactly one necklace consisting of all of them with the largest possible beauty. Help her!InputThe first line contains n (1 \leq n \leq 5 \cdot 10^5) — the number of necklace parts in the box. Each of the next n lines contains two integers a and b (0 \leq a, b < 2^{20}), which denote colors of pearls presented in the necklace parts. Pearls in the i-th line have indices 2i - 1 and 2i respectively.OutputThe first line should contain a single integer b denoting the maximum possible beauty of a necklace built from all given parts.The following line should contain 2n distinct integers p_i (1 \leq p_i \leq 2n) — the indices of initial pearls in the order in which they appear on a cycle. Indices of pearls belonging to the same necklace part have to appear at neighboring positions in this permutation (so 1\,4\,3\,2 is not a valid output, whereas 2\,1\,4\,3 and 4\,3\,1\,2 are). If there are many possible answers, you can print any.ExamplesInput
5
13 11
11 1
3 5
17 1
9 27
Output
3
8 7 9 10 5 6 1 2 3 4
Input
5
13 11
11 1
3 5
17 1
7 29
Output
2
8 7 10 9 5 6 4 3 2 1
Input
1
1 1
Output
20
2 1
NoteIn the first example the following pairs of pearls are combined: (7, 9), (10, 5), (6, 1), (2, 3) and (4, 8). The beauties of connections equal correspondingly: 3, 3, 3, 20, 20.The following drawing shows this construction. | 5
13 11
11 1
3 5
17 1
9 27
| 3 8 7 9 10 5 6 1 2 3 4 | 3 seconds | 512 megabytes | ['binary search', 'bitmasks', 'constructive algorithms', 'dfs and similar', 'dsu', 'graphs', '*2500'] |
B. Johnny and Grandmastertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7.InputInput consists of multiple test cases. The first line contains one integer t (1 \leq t \leq 10^5) — the number of test cases. Each test case is described as follows:The first line contains two integers n and p (1 \leq n, p \leq 10^6). The second line contains n integers k_i (0 \leq k_i \leq 10^6).The sum of n over all test cases doesn't exceed 10^6.OutputOutput one integer — the reminder of division the answer by 1\,000\,000\,007.ExampleInput
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
Output
4
1
146981438
747093407
NoteYou have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1.In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. | 4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
| 4 1 146981438 747093407 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', 'sortings', '*1900'] |
A. Johnny and Contributiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?InputThe first line contains two integers n (1 \leq n \leq 5 \cdot 10^5) and m (0 \leq m \leq 5 \cdot 10^5) — the number of blogs and references, respectively.Each of the following m lines contains two integers a and b (a \neq b; 1 \leq a, b \leq n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.The last line contains n integers t_1, t_2, \ldots, t_n, i-th of them denotes desired topic number of the i-th blog (1 \le t_i \le n).OutputIf the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, \ldots, p_n (1 \leq p_i \leq n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.ExamplesInput
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
NoteIn the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.Second example: There does not exist any permutation fulfilling given conditions.Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2. | 3 3
1 2
2 3
3 1
2 1 3
| 2 1 3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'graphs', 'greedy', 'sortings', '*1700'] |
H. Binary Mediantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider all binary strings of length m (1 \le m \le 60). A binary string is a string that consists of the characters 0 and 1 only. For example, 0110 is a binary string, and 012aba is not. Obviously, there are exactly 2^m such strings in total.The string s is lexicographically smaller than the string t (both have the same length m) if in the first position i from the left in which they differ, we have s[i] < t[i]. This is exactly the way strings are compared in dictionaries and in most modern programming languages when comparing them in a standard way. For example, the string 01011 is lexicographically smaller than the string 01100, because the first two characters are the same, and the third character in the first string is less than that in the second.We remove from this set n (1 \le n \le \min(2^m-1, 100)) distinct binary strings a_1, a_2, \ldots, a_n, each of length m. Thus, the set will have k=2^m-n strings. Sort all strings of the resulting set in lexicographical ascending order (as in the dictionary).We number all the strings after sorting from 0 to k-1. Print the string whose index is \lfloor \frac{k-1}{2} \rfloor (such an element is called median), where \lfloor x \rfloor is the rounding of the number down to the nearest integer.For example, if n=3, m=3 and a=[010, 111, 001], then after removing the strings a_i and sorting, the result will take the form: [000, 011, 100, 101, 110]. Thus, the desired median is 100.InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases. Then, t test cases follow.The first line of each test case contains integers n (1 \le n \le \min(2^m-1, 100)) and m (1 \le m \le 60), where n is the number of strings to remove, and m is the length of binary strings. The next n lines contain a_1, a_2, \ldots, a_n — distinct binary strings of length m.The total length of all given binary strings in all test cases in one test does not exceed 10^5.OutputPrint t answers to the test cases. For each test case, print a string of length m — the median of the sorted sequence of remaining strings in the corresponding test case.ExampleInput
5
3 3
010
001
111
4 3
000
111
100
011
1 1
1
1 1
0
3 2
00
01
10
Output
100
010
0
1
11
NoteThe first test case is explained in the statement.In the second test case, the result after removing strings and sorting is [001, 010, 101, 110]. Therefore, the desired median is 010. | 5
3 3
010
001
111
4 3
000
111
100
011
1 1
1
1 1
0
3 2
00
01
10
| 100 010 0 1 11 | 2 seconds | 256 megabytes | ['binary search', 'bitmasks', 'brute force', 'constructive algorithms', '*2100'] |
G. A/B Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given four positive integers n, m, a, b (1 \le b \le n \le 50; 1 \le a \le m \le 50). Find any such rectangular matrix of size n \times m that satisfies all of the following conditions: each row of the matrix contains exactly a ones; each column of the matrix contains exactly b ones; all other elements are zeros. If the desired matrix does not exist, indicate this.For example, for n=3, m=6, a=2, b=1, there exists a matrix satisfying the conditions above: \begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 1 & 0 \end{vmatrix} InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.Each test case is described by four positive integers n, m, a, b (1 \le b \le n \le 50; 1 \le a \le m \le 50), where n and m are the sizes of the matrix, and a and b are the number of ones for rows and columns, respectively.OutputFor each test case print: "YES" (without quotes) and the required matrix (if there are several answers, print any) if it exists, or "NO" (without quotes) if it does not exist. To print the matrix n \times m, print n rows, each of which consists of m numbers 0 or 1 describing a row of the matrix. Numbers must be printed without spaces.ExampleInput
5
3 6 2 1
2 2 2 1
2 2 2 2
4 4 2 2
2 1 1 2
Output
YES
010001
100100
001010
NO
YES
11
11
YES
1100
1100
0011
0011
YES
1
1
| 5
3 6 2 1
2 2 2 1
2 2 2 2
4 4 2 2
2 1 1 2
| YES 010001 100100 001010 NO YES 11 11 YES 1100 1100 0011 0011 YES 1 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*1900'] |
F. Spy-stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n strings a_1, a_2, \ldots, a_n: all of them have the same length m. The strings consist of lowercase English letters.Find any string s of length m such that each of the given n strings differs from s in at most one position. Formally, for each given string a_i, there is no more than one position j such that a_i[j] \ne s[j].Note that the desired string s may be equal to one of the given strings a_i, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.InputThe first line contains an integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.Each test case starts with a line containing two positive integers n (1 \le n \le 10) and m (1 \le m \le 10) — the number of strings and their length.Then follow n strings a_i, one per line. Each of them has length m and consists of lowercase English letters.OutputPrint t answers to the test cases. Each answer (if it exists) is a string of length m consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).ExampleInput
5
2 4
abac
zbab
2 4
aaaa
bbbb
3 3
baa
aaa
aab
2 2
ab
bb
3 1
a
b
c
Output
abab
-1
aaa
ab
zNoteThe first test case was explained in the statement.In the second test case, the answer does not exist. | 5
2 4
abac
zbab
2 4
aaaa
bbbb
3 3
baa
aaa
aab
2 2
ab
bb
3 1
a
b
c
| abab -1 aaa ab z | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', 'constructive algorithms', 'dp', 'hashing', 'strings', '*1700'] |
E. Polygontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolygon is not only the best platform for developing problems but also a square matrix with side n, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly 2n cannons were placed. Initial polygon for n=4. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row i, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell (i, 1) and ends in some cell (i, j); if a cannon stands in the column j, above the first row, and shoots with a 1, then the 1 starts its flight from the cell (1, j) and ends in some cell (i, j). For example, consider the following sequence of shots: 1. Shoot the cannon in the row 2. 2. Shoot the cannon in the row 2. 3. Shoot the cannon in column 3. You have a report from the military training on your desk. This report is a square matrix with side length n consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.Each test case starts with a line containing an integer n (1 \le n \le 50) — the size of the polygon.This is followed by n lines of length n, consisting of 0 and 1 — the polygon matrix after the training.The total area of the matrices in all test cases in one test does not exceed 10^5.OutputFor each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.ExampleInput
5
4
0010
0011
0000
0000
2
10
01
2
00
00
4
0101
1111
0101
0111
4
0100
1110
0101
0111
Output
YES
NO
YES
YES
NO
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell (1, 1) flying out of any cannon would continue its flight further. | 5
4
0010
0011
0000
0000
2
10
01
2
00
00
4
0101
1111
0101
0111
4
0100
1110
0101
0111
| YES NO YES YES NO | 2 seconds | 256 megabytes | ['dp', 'graphs', 'implementation', 'shortest paths', '*1300'] |
D. Buying Shovelstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 \le i \le k). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels?For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly n shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. InputThe first line contains an integer t (1 \le t \le 100) — the number of test cases in the input. Then, t test cases follow, one per line.Each test case consists of two positive integers n (1 \le n \le 10^9) and k (1 \le k \le 10^9) — the number of shovels and the number of types of packages.OutputPrint t answers to the test cases. Each answer is a positive integer — the minimum number of packages.ExampleInput
5
8 7
8 1
6 10
999999733 999999732
999999733 999999733
Output
2
8
1
999999733
1
NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy 8 shovels — 8 packages of one shovel.In the third test case, you need to buy a 1 package of 6 shovels. | 5
8 7
8 1
6 10
999999733 999999732
999999733 999999733
| 2 8 1 999999733 1 | 2 seconds | 256 megabytes | ['math', 'number theory', '*1300'] |
C. Similar Pairstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x-y|=1. For example, in each of the pairs (2, 6), (4, 3), (11, 7), the numbers are similar to each other, and in the pairs (1, 4), (3, 12), they are not.You are given an array a of n (n is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.For example, for the array a = [11, 14, 16, 12], there is a partition into pairs (11, 12) and (14, 16). The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.Each test case consists of two lines.The first line contains an even positive integer n (2 \le n \le 50) — length of array a.The second line contains n positive integers a_1, a_2, \dots, a_n (1 \le a_i \le 100).OutputFor each test case print: YES if the such a partition exists, NO otherwise. The letters in the words YES and NO can be displayed in any case.ExampleInput
7
4
11 14 16 12
2
1 8
4
1 1 1 1
4
1 2 5 6
2
12 13
6
1 6 3 10 5 8
6
1 12 3 10 5 8
Output
YES
NO
YES
YES
YES
YES
NO
NoteThe first test case was explained in the statement.In the second test case, the two given numbers are not similar.In the third test case, any partition is suitable. | 7
4
11 14 16 12
2
1 8
4
1 1 1 1
4
1 2 5 6
2
12 13
6
1 6 3 10 5 8
6
1 12 3 10 5 8
| YES NO YES YES YES YES NO | 2 seconds | 256 megabytes | ['constructive algorithms', 'graph matchings', 'greedy', 'sortings', '*1100'] |
B. Honest Coachtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i.You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams A and B so that the value |\max(A) - \min(B)| is as small as possible, where \max(A) is the maximum strength of an athlete from team A, and \min(B) is the minimum strength of an athlete from team B.For example, if n=5 and the strength of the athletes is s=[3, 1, 2, 6, 4], then one of the possible split into teams is: first team: A = [1, 2, 4], second team: B = [3, 6]. In this case, the value |\max(A) - \min(B)| will be equal to |4-3|=1. This example illustrates one of the ways of optimal split into two teams.Print the minimum value |\max(A) - \min(B)|.InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases in the input. Then t test cases follow.Each test case consists of two lines. The first line contains positive integer n (2 \le n \le 50) — number of athletes. The second line contains n positive integers s_1, s_2, \ldots, s_n (1 \le s_i \le 1000), where s_i — is the strength of the i-th athlete. Please note that s values may not be distinct.OutputFor each test case print one integer — the minimum value of |\max(A) - \min(B)| with the optimal split of all athletes into two teams. Each of the athletes must be a member of exactly one of the two teams.ExampleInput
5
5
3 1 2 6 4
6
2 1 3 2 4 3
4
7 9 3 1
2
1 1000
3
100 150 200
Output
1
0
2
999
50
NoteThe first test case was explained in the statement. In the second test case, one of the optimal splits is A=[2, 1], B=[3, 2, 4, 3], so the answer is |2-2|=0. | 5
5
3 1 2 6 4
6
2 1 3 2 4 3
4
7 9 3 1
2
1 1000
3
100 150 200
| 1 0 2 999 50 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*800'] |
A. Minimal Squaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFind the minimum area of a square land on which you can place two identical rectangular a \times b houses. The sides of the houses should be parallel to the sides of the desired square land.Formally, You are given two identical rectangles with side lengths a and b (1 \le a, b \le 100) — positive integers (you are given just the sizes, but not their positions). Find the square of the minimum area that contains both given rectangles. Rectangles can be rotated (both or just one), moved, but the sides of the rectangles should be parallel to the sides of the desired square. Two rectangles can touch each other (side or corner), but cannot intersect. Rectangles can also touch the sides of the square but must be completely inside it. You can rotate the rectangles. Take a look at the examples for a better understanding. The picture shows a square that contains red and green rectangles. InputThe first line contains an integer t (1 \le t \le 10\,000) —the number of test cases in the input. Then t test cases follow.Each test case is a line containing two integers a, b (1 \le a, b \le 100) — side lengths of the rectangles.OutputPrint t answers to the test cases. Each answer must be a single integer — minimal area of square land, that contains two rectangles with dimensions a \times b.ExampleInput
8
3 2
4 2
1 1
3 1
4 7
1 3
7 4
100 100
Output
16
16
4
9
64
9
64
40000
NoteBelow are the answers for the first two test cases: | 8
3 2
4 2
1 1
3 1
4 7
1 3
7 4
100 100
| 16 16 4 9 64 9 64 40000 | 2 seconds | 256 megabytes | ['greedy', 'math', '*800'] |
F. RC Kaboom Showtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou know, it's hard to conduct a show with lots of participants and spectators at the same place nowadays. Still, you are not giving up on your dream to make a car crash showcase! You decided to replace the real cars with remote controlled ones, call the event "Remote Control Kaboom Show" and stream everything online.For the preparation you arranged an arena — an infinite 2D-field. You also bought n remote controlled cars and set them up on the arena. Unfortunately, the cars you bought can only go forward without turning left, right or around. So you additionally put the cars in the direction you want them to go.To be formal, for each car i (1 \le i \le n) you chose its initial position (x_i, y_i) and a direction vector (dx_i, dy_i). Moreover, each car has a constant speed s_i units per second. So after car i is launched, it stars moving from (x_i, y_i) in the direction (dx_i, dy_i) with constant speed s_i.The goal of the show is to create a car collision as fast as possible! You noted that launching every car at the beginning of the show often fails to produce any collisions at all. Thus, you plan to launch the i-th car at some moment t_i. You haven't chosen t_i, that's yet to be decided. Note that it's not necessary for t_i to be integer and t_i is allowed to be equal to t_j for any i, j.The show starts at time 0. The show ends when two cars i and j (i \ne j) collide (i. e. come to the same coordinate at the same time). The duration of the show is the time between the start and the end.What's the fastest crash you can arrange by choosing all t_i? If it's possible to arrange a crash then print the shortest possible duration of the show. Otherwise, report that it's impossible.InputThe first line contains a single integer n (1 \le n \le 25000) — the number of cars.Each of the next n lines contains five integers x_i, y_i, dx_i, dy_i, s_i (-10^3 \le x_i, y_i \le 10^3; 1 \le |dx_i| \le 10^3; 1 \le |dy_i| \le 10^3; 1 \le s_i \le 10^3) — the initial position of the i-th car, its direction vector and its speed, respectively.It's guaranteed that all cars start at distinct positions (i. e. (x_i, y_i) \neq (x_j, y_j) for i \neq j).OutputPrint the shortest possible duration of the show if it's possible to arrange a crash by choosing all t_i. Otherwise, print "No show :(".Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}.ExamplesInput
4
3 -1 -1 1 2
2 3 -3 -2 10
-4 2 1 -2 1
-2 -2 -1 2 4
Output
0.585902082262898
Input
2
-1 1 -1 1 200
1 1 1 5 200
Output
No show :(
NoteHere is the picture for the first example: The fastest cars to crash are cars 2 and 4. Let's launch car 2 at 0, car 4 at about 0.096762 and cars 1 and 3 at arbitrary time. That way cars 2 and 4 will crash into each other at about 0.585902. So here's what it looks like at the moment of the collision: Here's the picture for the second example: | 4
3 -1 -1 1 2
2 3 -3 -2 10
-4 2 1 -2 1
-2 -2 -1 2 4
| 0.585902082262898 | 6 seconds | 256 megabytes | ['binary search', 'brute force', 'data structures', 'geometry', 'math', '*2900'] |
E. Modular Stabilitytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe define x \bmod y as the remainder of division of x by y (\% operator in C++ or Java, mod operator in Pascal).Let's call an array of positive integers [a_1, a_2, \dots, a_k] stable if for every permutation p of integers from 1 to k, and for every non-negative integer x, the following condition is met: (((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k = (((x \bmod a_{p_1}) \bmod a_{p_2}) \dots \bmod a_{p_{k - 1}}) \bmod a_{p_k} That is, for each non-negative integer x, the value of (((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k does not change if we reorder the elements of the array a.For two given integers n and k, calculate the number of stable arrays [a_1, a_2, \dots, a_k] such that 1 \le a_1 < a_2 < \dots < a_k \le n.InputThe only line contains two integers n and k (1 \le n, k \le 5 \cdot 10^5).OutputPrint one integer — the number of stable arrays [a_1, a_2, \dots, a_k] such that 1 \le a_1 < a_2 < \dots < a_k \le n. Since the answer may be large, print it modulo 998244353.ExamplesInput
7 3
Output
16
Input
3 7
Output
0
Input
1337 42
Output
95147305
Input
1 1
Output
1
Input
500000 1
Output
500000
| 7 3
| 16 | 2 seconds | 512 megabytes | ['combinatorics', 'math', 'number theory', '*2000'] |
D. Yet Another Yet Another Tasktime limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing yet another card game. This time the rules are the following. There are n cards lying in a row in front of them. The i-th card has value a_i. First, Alice chooses a non-empty consecutive segment of cards [l; r] (l \le r). After that Bob removes a single card j from that segment (l \le j \le r). The score of the game is the total value of the remaining cards on the segment (a_l + a_{l + 1} + \dots + a_{j - 1} + a_{j + 1} + \dots + a_{r - 1} + a_r). In particular, if Alice chooses a segment with just one element, then the score after Bob removes the only card is 0.Alice wants to make the score as big as possible. Bob takes such a card that the score is as small as possible.What segment should Alice choose so that the score is maximum possible? Output the maximum score.InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of cards.The second line contains n integers a_1, a_2, \dots, a_n (-30 \le a_i \le 30) — the values on the cards.OutputPrint a single integer — the final score of the game.ExamplesInput
5
5 -2 10 -1 4
Output
6
Input
8
5 2 5 3 -30 -30 6 9
Output
10
Input
3
-10 6 -15
Output
0
NoteIn the first example Alice chooses a segment [1;5] — the entire row of cards. Bob removes card 3 with the value 10 from the segment. Thus, the final score is 5 + (-2) + (-1) + 4 = 6.In the second example Alice chooses a segment [1;4], so that Bob removes either card 1 or 3 with the value 5, making the answer 5 + 2 + 3 = 10.In the third example Alice can choose any of the segments of length 1: [1;1], [2;2] or [3;3]. Bob removes the only card, so the score is 0. If Alice chooses some other segment then the answer will be less than 0. | 5
5 -2 10 -1 4
| 6 | 1.5 seconds | 512 megabytes | ['data structures', 'dp', 'implementation', 'two pointers', '*2000'] |
C. Mixing Watertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are two infinite sources of water: hot water of temperature h; cold water of temperature c (c < h). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water \dots and so on \dots Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to t. So if the temperature in the barrel is t_b, then the absolute difference of t_b and t (|t_b - t|) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to t? If there are multiple answers with the minimum absolute difference, then print the smallest of them.InputThe first line contains a single integer T (1 \le T \le 3 \cdot 10^4) — the number of testcases.Each of the next T lines contains three integers h, c and t (1 \le c < h \le 10^6; c \le t \le h) — the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.OutputFor each testcase print a single positive integer — the minimum number of cups required to be poured into the barrel to achieve the closest temperature to t.ExampleInput
3
30 10 20
41 15 30
18 13 18
Output
2
7
1
NoteIn the first testcase the temperature after 2 poured cups: 1 hot and 1 cold is exactly 20. So that is the closest we can achieve.In the second testcase the temperature after 7 poured cups: 4 hot and 3 cold is about 29.857. Pouring more water won't get us closer to t than that.In the third testcase the temperature after 1 poured cup: 1 hot is 18. That's exactly equal to t. | 3
30 10 20
41 15 30
18 13 18
| 2 7 1 | 2 seconds | 256 megabytes | ['binary search', 'math', '*1700'] |
B. New Theatre Squaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou might have remembered Theatre square from the problem 1A. Now it's finally getting repaved.The square still has a rectangular shape of n \times m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pavement.You are given the picture of the squares: if a_{i,j} = "*", then the j-th square in the i-th row should be black; if a_{i,j} = ".", then the j-th square in the i-th row should be white. The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles: 1 \times 1 tiles — each tile costs x burles and covers exactly 1 square; 1 \times 2 tiles — each tile costs y burles and covers exactly 2 adjacent squares of the same row. Note that you are not allowed to rotate these tiles or cut them into 1 \times 1 tiles. You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles.What is the smallest total price of the tiles needed to cover all the white squares?InputThe first line contains a single integer t (1 \le t \le 500) — the number of testcases. Then the description of t testcases follow.The first line of each testcase contains four integers n, m, x and y (1 \le n \le 100; 1 \le m \le 1000; 1 \le x, y \le 1000) — the size of the Theatre square, the price of the 1 \times 1 tile and the price of the 1 \times 2 tile.Each of the next n lines contains m characters. The j-th character in the i-th line is a_{i,j}. If a_{i,j} = "*", then the j-th square in the i-th row should be black, and if a_{i,j} = ".", then the j-th square in the i-th row should be white.It's guaranteed that the sum of n \times m over all testcases doesn't exceed 10^5.OutputFor each testcase print a single integer — the smallest total price of the tiles needed to cover all the white squares in burles.ExampleInput
4
1 1 10 1
.
1 2 10 1
..
2 1 10 1
.
.
3 3 3 7
..*
*..
.*.
Output
10
1
20
18
NoteIn the first testcase you are required to use a single 1 \times 1 tile, even though 1 \times 2 tile is cheaper. So the total price is 10 burles.In the second testcase you can either use two 1 \times 1 tiles and spend 20 burles or use a single 1 \times 2 tile and spend 1 burle. The second option is cheaper, thus the answer is 1.The third testcase shows that you can't rotate 1 \times 2 tiles. You still have to use two 1 \times 1 tiles for the total price of 20.In the fourth testcase the cheapest way is to use 1 \times 1 tiles everywhere. The total cost is 6 \cdot 3 = 18. | 4
1 1 10 1
.
1 2 10 1
..
2 1 10 1
.
.
3 3 3 7
..*
*..
.*.
| 10 1 20 18 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'greedy', 'implementation', 'two pointers', '*1000'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.