problem_statement
stringlengths 147
8.53k
| input
stringlengths 1
771
| output
stringlengths 1
592
⌀ | time_limit
stringclasses 32
values | memory_limit
stringclasses 21
values | tags
stringlengths 6
168
|
---|---|---|---|---|---|
G. Minimum Differencetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer array a of size n.You have to perform m queries. Each query has one of two types: "1 l r k" — calculate the minimum value dif such that there are exist k distinct integers x_1, x_2, \dots, x_k such that cnt_i > 0 (for every i \in [1, k]) and |cnt_i - cnt_j| \le dif (for every i \in [1, k], j \in [1, k]), where cnt_i is the number of occurrences of x_i in the subarray a[l..r]. If it is impossible to choose k integers, report it; "2 p x" — assign a_{p} := x. InputThe first line contains two integers n and m (1 \le n, m \le 10^5) — the size of the array a and the number of queries.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^5).Next m lines contain queries (one per line). Each query has one of two types: "1 l r k" (1 \le l \le r \le n; 1 \le k \le 10^5) "2 p x" (1 \le p \le n; 1 \le x \le 10^5). It's guaranteed that there is at least one query of the first type.OutputFor each query of the first type, print the minimum value of dif that satisfies all required conditions, or -1 if it is impossible to choose k distinct integers.ExampleInput
12 11
2 1 1 2 1 1 3 2 1 1 3 3
1 2 10 3
1 2 11 3
2 7 2
1 3 9 2
1 1 12 1
1 1 12 4
2 12 4
1 1 12 4
2 1 5
1 3 12 2
1 1 4 3
Output
5
4
1
0
-1
5
0
1
| 12 11
2 1 1 2 1 1 3 2 1 1 3 3
1 2 10 3
1 2 11 3
2 7 2
1 3 9 2
1 1 12 1
1 1 12 4
2 12 4
1 1 12 4
2 1 5
1 3 12 2
1 1 4 3
| 5 4 1 0 -1 5 0 1 | 5 seconds | 256 megabytes | ['data structures', 'hashing', 'sortings', 'two pointers', '*3100'] |
F. Lanternstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n lanterns in a row. The lantern i is placed in position i and has power equal to p_i.Each lantern can be directed to illuminate either some lanterns to the left or some lanterns to the right. If the i-th lantern is turned to the left, it illuminates all such lanterns j that j \in [i - p_i, i - 1]. Similarly, if it is turned to the right, it illuminates all such lanterns j that j \in [i + 1, i + p_i].Your goal is to choose a direction for each lantern so each lantern is illuminated by at least one other lantern, or report that it is impossible.InputThe first line contains one integer t (1 \le t \le 10000) — the number of test cases.Each test case consists of two lines. The first line contains one integer n (2 \le n \le 3 \cdot 10^5) — the number of lanterns.The second line contains n integers p_1, p_2, \dots, p_n (0 \le p_i \le n) — the power of the i-th lantern.The sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, print the answer as follows:If it is possible to direct all lanterns so that each lantern is illuminated, print YES in the first line and a string of n characters L and/or R (the i-th character is L if the i-th lantern is turned to the left, otherwise this character is R) in the second line. If there are multiple answers, you may print any of them.If there is no answer, simply print NO for that test case.ExampleInput
4
8
0 0 3 1 1 1 1 2
2
1 1
2
2 2
2
0 1
Output
YES
RRLLLLRL
YES
RL
YES
RL
NO
| 4
8
0 0 3 1 1 1 1 2
2
1 1
2
2 2
2
0 1
| YES RRLLLLRL YES RL YES RL NO | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dp', '*3000'] |
E. Pattern Matchingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n patterns p_1, p_2, \dots, p_n and m strings s_1, s_2, \dots, s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.Can you perform such a rearrangement? If you can, then print any valid order.InputThe first line contains three integers n, m and k (1 \le n, m \le 10^5, 1 \le k \le 4) — the number of patterns, the number of strings and the length of each pattern and string.Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 \le mt \le n) — the index of the first pattern the corresponding string should match.OutputPrint "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.ExamplesInput
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
NoteThe order of patterns after the rearrangement in the first example is the following: aaaa __b_ ab__ _bcd _b_d Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].The answer to that test is not unique, other valid orders also exist.In the second example cba doesn't match __c, thus, no valid order exists.In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2. | 5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
| YES 3 2 4 5 1 | 2 seconds | 256 megabytes | ['bitmasks', 'data structures', 'dfs and similar', 'graphs', 'hashing', 'sortings', 'strings', '*2300'] |
D. Journeytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n + 1 cities, numbered from 0 to n. n roads connect these cities, the i-th road connects cities i - 1 and i (i \in [1, n]).Each road has a direction. The directions are given by a string of n characters such that each character is either L or R. If the i-th character is L, it means that the i-th road initially goes from the city i to the city i - 1; otherwise it goes from the city i - 1 to the city i.A traveler would like to visit as many cities of this country as possible. Initially, they will choose some city to start their journey from. Each day, the traveler must go from the city where they currently are to a neighboring city using one of the roads, and they can go along a road only if it is directed in the same direction they are going; i. e., if a road is directed from city i to the city i + 1, it is possible to travel from i to i + 1, but not from i + 1 to i. After the traveler moves to a neighboring city, all roads change their directions to the opposite ones. If the traveler cannot go from their current city to a neighboring city, their journey ends; it is also possible to end the journey whenever the traveler wants to.The goal of the traveler is to visit as many different cities as possible (they can visit a city multiple times, but only the first visit is counted). For each city i, calculate the maximum number of different cities the traveler can visit during exactly one journey if they start in the city i. InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of two lines. The first line contains one integer n (1 \le n \le 3 \cdot 10^5). The second line contains the string s consisting of exactly n characters, each character is either L or R.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, print n + 1 integers. The i-th integer should be equal to the maximum number of different cities the traveler can visit during one journey if this journey starts in the i-th city.ExampleInput
2
6
LRRRLL
3
LRL
Output
1 3 2 3 1 3 2
1 4 1 4
| 2
6
LRRRLL
3
LRL
| 1 3 2 3 1 3 2 1 4 1 4 | 2 seconds | 512 megabytes | ['dfs and similar', 'dp', 'dsu', 'implementation', '*1700'] |
C. Longest Simple Cycletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 \le j < c_i.Now you decided to unite chains in one graph in the following way: the first chain is skipped; the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph.A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains the single integer n (2 \le n \le 10^5) — the number of chains you have.The second line of each test case contains n integers c_1, c_2, \dots, c_n (2 \le c_i \le 10^9) — the number of vertices in the corresponding chains.The third line of each test case contains n integers a_1, a_2, \dots, a_n (a_1 = -1; 1 \le a_i \le c_{i - 1}).The fourth line of each test case contains n integers b_1, b_2, \dots, b_n (b_1 = -1; 1 \le b_i \le c_{i - 1}).Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5.OutputFor each test case, print the length of the longest simple cycle.ExampleInput
3
4
3 4 3 3
-1 1 2 2
-1 2 2 3
2
5 6
-1 5
-1 1
3
3 5 2
-1 1 1
-1 3 5
Output
7
11
8
NoteIn the first test case, the longest simple cycle is shown below: We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity. | 3
4
3 4 3 3
-1 1 2 2
-1 2 2 3
2
5 6
-1 5
-1 1
3
3 5 2
-1 1 1
-1 3 5
| 7 11 8 | 2 seconds | 256 megabytes | ['dp', 'graphs', 'greedy', '*1600'] |
B. Inflationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a statistic of price changes for one product represented as an array of n positive integers p_0, p_1, \dots, p_{n - 1}, where p_0 is the initial price of the product and p_i is how the price was increased during the i-th month.Using these price changes you are asked to calculate the inflation coefficients for each month as the ratio of current price increase p_i to the price at the start of this month (p_0 + p_1 + \dots + p_{i - 1}).Your boss said you clearly that the inflation coefficients must not exceed k %, so you decided to increase some values p_i in such a way, that all p_i remain integers and the inflation coefficients for each month don't exceed k %.You know, that the bigger changes — the more obvious cheating. That's why you need to minimize the total sum of changes.What's the minimum total sum of changes you need to make all inflation coefficients not more than k %?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains two integers n and k (2 \le n \le 100; 1 \le k \le 100) — the length of array p and coefficient k.The second line of each test case contains n integers p_0, p_1, \dots, p_{n - 1} (1 \le p_i \le 10^9) — the array p.OutputFor each test case, print the minimum total sum of changes you need to make all inflation coefficients not more than k %.ExampleInput
2
4 1
20100 1 202 202
3 100
1 1 1
Output
99
0
NoteIn the first test case, you can, for example, increase p_0 by 50 and p_1 by 49 and get array [20150, 50, 202, 202]. Then you get the next inflation coefficients: \frac{50}{20150} \le \frac{1}{100}; \frac{202}{20150 + 50} \le \frac{1}{100}; \frac{202}{20200 + 202} \le \frac{1}{100}; In the second test case, you don't need to modify array p, since the inflation coefficients are already good: \frac{1}{1} \le \frac{100}{100}; \frac{1}{1 + 1} \le \frac{100}{100}; | 2
4 1
20100 1 202 202
3 100
1 1 1
| 99 0 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'greedy', 'math', '*1300'] |
A. K-divisible Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers n and k.You should create an array of n positive integers a_1, a_2, \dots, a_n such that the sum (a_1 + a_2 + \dots + a_n) is divisible by k and maximum element in a is minimum possible.What is the minimum possible maximum element in a?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first and only line of each test case contains two integers n and k (1 \le n \le 10^9; 1 \le k \le 10^9).OutputFor each test case, print one integer — the minimum possible maximum element in array a such that the sum (a_1 + \dots + a_n) is divisible by k. ExampleInput
4
1 5
4 3
8 8
8 17
Output
5
2
1
3
NoteIn the first test case n = 1, so the array consists of one element a_1 and if we make a_1 = 5 it will be divisible by k = 5 and the minimum possible.In the second test case, we can create array a = [1, 2, 1, 2]. The sum is divisible by k = 3 and the maximum is equal to 2.In the third test case, we can create array a = [1, 1, 1, 1, 1, 1, 1, 1]. The sum is divisible by k = 8 and the maximum is equal to 1. | 4
1 5
4 3
8 8
8 17
| 5 2 1 3 | 1 second | 256 megabytes | ['binary search', 'constructive algorithms', 'greedy', 'math', '*1000'] |
G. Strange Beautytime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp found on the street an array a of n elements.Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i \ne j: a_i is divisible by a_j; or a_j is divisible by a_i. For example, if: n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); n=3 and a=[2, 14, 42], then the a array is beautiful; n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful.InputThe first line contains one integer t (1 \leq t \leq 10) — the number of test cases. Then t test cases follow.The first line of each test case contains one integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the array a.The second line of each test case contains n numbers a_1, a_2, \ldots, a_n (1 \le a_i \le 2 \cdot 10^5) — elements of the array a.OutputFor each test case output one integer — the minimum number of elements that must be removed to make the array a beautiful.ExampleInput
4
5
7 9 3 14 63
3
2 14 42
4
45 9 3 18
3
2 2 8
Output
2
0
1
0
NoteIn the first test case, removing 7 and 14 will make array a beautiful.In the second test case, the array a is already beautiful.In the third test case, removing one of the elements 45 or 18 will make the array a beautiful.In the fourth test case, the array a is beautiful. | 4
5
7 9 3 14 63
3
2 14 42
4
45 9 3 18
3
2 2 8
| 2 0 1 0 | 5 seconds | 256 megabytes | ['dp', 'math', 'number theory', 'sortings', '*1900'] |
F. Unusual Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two binary square matrices a and b of size n \times n. A matrix is called binary if each of its elements is equal to 0 or 1. You can do the following operations on the matrix a arbitrary number of times (0 or more): vertical xor. You choose the number j (1 \le j \le n) and for all i (1 \le i \le n) do the following: a_{i, j} := a_{i, j} \oplus 1 (\oplus — is the operation xor (exclusive or)). horizontal xor. You choose the number i (1 \le i \le n) and for all j (1 \le j \le n) do the following: a_{i, j} := a_{i, j} \oplus 1. Note that the elements of the a matrix change after each operation.For example, if n=3 and the matrix a is: \begin{pmatrix} 1 & 1 & 0 \\ 0 & 0 & 1 \\ 1 & 1 & 0 \end{pmatrix} Then the following sequence of operations shows an example of transformations: vertical xor, j=1. a= \begin{pmatrix} 0 & 1 & 0 \\ 1 & 0 & 1 \\ 0 & 1 & 0 \end{pmatrix} horizontal xor, i=2. a= \begin{pmatrix} 0 & 1 & 0 \\ 0 & 1 & 0 \\ 0 & 1 & 0 \end{pmatrix} vertical xor, j=2. a= \begin{pmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{pmatrix} Check if there is a sequence of operations such that the matrix a becomes equal to the matrix b.InputThe first line contains one integer t (1 \leq t \leq 1000) — the number of test cases. Then t test cases follow.The first line of each test case contains one integer n (1 \leq n \leq 1000) — the size of the matrices.The following n lines contain strings of length n, consisting of the characters '0' and '1' — the description of the matrix a.An empty line follows.The following n lines contain strings of length n, consisting of the characters '0' and '1' — the description of the matrix b.It is guaranteed that the sum of n over all test cases does not exceed 1000.OutputFor each test case, output on a separate line: "YES", there is such a sequence of operations that the matrix a becomes equal to the matrix b; "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).ExampleInput
3
3
110
001
110
000
000
000
3
101
010
101
010
101
010
2
01
11
10
10
Output
YES
YES
NO
NoteThe first test case is explained in the statements.In the second test case, the following sequence of operations is suitable: horizontal xor, i=1; horizontal xor, i=2; horizontal xor, i=3; It can be proved that there is no sequence of operations in the third test case so that the matrix a becomes equal to the matrix b. | 3
3
110
001
110
000
000
000
3
101
010
101
010
101
010
2
01
11
10
10
| YES YES NO | 2 seconds | 256 megabytes | ['2-sat', 'brute force', 'constructive algorithms', '*1900'] |
E. Advertising Agencytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers.Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers.Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers).For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7.InputThe first line contains one 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 two integers n and k (1 \le k \le n \le 1000) — the number of bloggers and how many of them you can sign a contract with.The second line of each test case contains n integers a_1, a_2, \ldots a_n (1 \le a_i \le n) — the number of followers of each blogger.It is guaranteed that the sum of n over all test cases does not exceed 1000.OutputFor each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible.ExampleInput
3
4 3
1 3 1 2
4 2
1 1 1 1
2 1
1 2
Output
2
6
1
NoteThe test case is explained in the statements.In the second test case, the following ways are valid: conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. | 3
4 3
1 3 1 2
4 2
1 1 1 1
2 1
1 2
| 2 6 1 | 2 seconds | 256 megabytes | ['combinatorics', 'math', 'sortings', '*1600'] |
D. Cleaning the Phonetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp often uses his smartphone. He has already installed n applications on it. Application with number i takes up a_i units of memory.Polycarp wants to free at least m units of memory (by removing some applications).Of course, some applications are more important to Polycarp than others. He came up with the following scoring system — he assigned an integer b_i to each application: b_i = 1 — regular application; b_i = 2 — important application. According to this rating system, his phone has b_1 + b_2 + \ldots + b_n convenience points.Polycarp believes that if he removes applications with numbers i_1, i_2, \ldots, i_k, then he will free a_{i_1} + a_{i_2} + \ldots + a_{i_k} units of memory and lose b_{i_1} + b_{i_2} + \ldots + b_{i_k} convenience points.For example, if n=5, m=7, a=[5, 3, 2, 1, 4], b=[2, 1, 1, 2, 1], then Polycarp can uninstall the following application sets (not all options are listed below): applications with numbers 1, 4 and 5. In this case, it will free a_1+a_4+a_5=10 units of memory and lose b_1+b_4+b_5=5 convenience points; applications with numbers 1 and 3. In this case, it will free a_1+a_3=7 units of memory and lose b_1+b_3=3 convenience points. applications with numbers 2 and 5. In this case, it will free a_2+a_5=7 memory units and lose b_2+b_5=2 convenience points. Help Polycarp, choose a set of applications, such that if removing them will free at least m units of memory and lose the minimum number of convenience points, or indicate that such a set does not exist.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of each test case contains two integers n and m (1 \le n \le 2 \cdot 10^5, 1 \le m \le 10^9) — the number of applications on Polycarp's phone and the number of memory units to be freed.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the number of memory units used by applications.The third line of each test case contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le 2) — the convenience points of each application.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output on a separate line: -1, if there is no set of applications, removing which will free at least m units of memory; the minimum number of convenience points that Polycarp will lose if such a set exists. ExampleInput
5
5 7
5 3 2 1 4
2 1 1 2 1
1 3
2
1
5 10
2 3 2 3 2
1 2 1 2 1
4 10
5 1 3 4
1 2 1 2
4 5
3 2 1 2
2 1 2 1
Output
2
-1
6
4
3
NoteIn the first test case, it is optimal to remove applications with numbers 2 and 5, freeing 7 units of memory. b_2+b_5=2.In the second test case, by removing the only application, Polycarp will be able to clear only 2 of memory units out of the 3 needed.In the third test case, it is optimal to remove applications with numbers 1, 2, 3 and 4, freeing 10 units of memory. b_1+b_2+b_3+b_4=6.In the fourth test case, it is optimal to remove applications with numbers 1, 3 and 4, freeing 12 units of memory. b_1+b_3+b_4=4.In the fifth test case, it is optimal to remove applications with numbers 1 and 2, freeing 5 units of memory. b_1+b_2=3. | 5
5 7
5 3 2 1 4
2 1 1 2 1
1 3
2
1
5 10
2 3 2 3 2
1 2 1 2 1
4 10
5 1 3 4
1 2 1 2
4 5
3 2 1 2
2 1 2 1
| 2 -1 6 4 3 | 1 second | 256 megabytes | ['binary search', 'dp', 'sortings', 'two pointers', '*1800'] |
C. Ball in Berlandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls.Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs.Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair.For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): (1, 3) and (2, 2); (3, 4) and (1, 3); But the following combinations are not possible: (1, 3) and (1, 2) — the first boy enters two pairs; (1, 2) and (2, 2) — the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of each test case contains three integers a, b and k (1 \le a, b, k \le 2 \cdot 10^5) — the number of boys and girls in the class and the number of couples ready to dance together.The second line of each test case contains k integers a_1, a_2, \ldots a_k. (1 \le a_i \le a), where a_i is the number of the boy in the pair with the number i.The third line of each test case contains k integers b_1, b_2, \ldots b_k. (1 \le b_i \le b), where b_i is the number of the girl in the pair with the number i.It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 \cdot 10^5.It is guaranteed that each pair is specified at most once in one test case.OutputFor each test case, on a separate line print one integer — the number of ways to choose two pairs that match the condition above.ExampleInput
3
3 4 4
1 1 2 3
2 3 2 4
1 1 1
1
1
2 2 4
1 1 2 2
1 2 1 2
Output
4
0
2
NoteIn the first test case, the following combinations of pairs fit: (1, 2) and (3, 4); (1, 3) and (2, 2); (1, 3) and (3, 4); (2, 2) and (3, 4). There is only one pair in the second test case.In the third test case, the following combinations of pairs fit: (1, 1) and (2, 2); (1, 2) and (2, 1). | 3
3 4 4
1 1 2 3
2 3 2 4
1 1 1
1
1
2 2 4
1 1 2 2
1 2 1 2
| 4 0 2 | 2 seconds | 256 megabytes | ['combinatorics', 'graphs', 'math', '*1400'] |
B. New Year's Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021.For example, if: n=4041, then the number n can be represented as the sum 2020 + 2021; n=4042, then the number n can be represented as the sum 2021 + 2021; n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021.InputThe first line contains one integer t (1 \leq t \leq 10^4) — the number of test cases. Then t test cases follow.Each test case contains one integer n (1 \leq n \leq 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021.OutputFor each test case, output on a separate line: "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).ExampleInput
5
1
4041
4042
8081
8079
Output
NO
YES
YES
YES
NO
| 5
1
4041
4042
8081
8079
| NO YES YES YES NO | 2 seconds | 256 megabytes | ['brute force', 'dp', 'math', '*900'] |
A. Odd Divisortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n. Check if n has an odd divisor, greater than one (does there exist such a number x (x > 1) that n is divisible by x and x is odd).For example, if n=6, then there is x=3. If n=4, then such a number does not exist.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.Each test case contains one integer n (2 \le n \le 10^{14}).Please note, that the input 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.OutputFor each test case, output on a separate line: "YES" if n has an odd divisor, greater than one; "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).ExampleInput
6
2
3
4
5
998244353
1099511627776
Output
NO
YES
NO
YES
YES
NO
| 6
2
3
4
5
998244353
1099511627776
| NO YES NO YES YES NO | 2 seconds | 256 megabytes | ['math', 'number theory', '*900'] |
F. 1 2 3 4 ...time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor had a sequence d_1, d_2, \dots, d_n of integers. When Igor entered the classroom there was an integer x written on the blackboard.Igor generated sequence p using the following algorithm: initially, p = [x]; for each 1 \leq i \leq n he did the following operation |d_i| times: if d_i \geq 0, then he looked at the last element of p (let it be y) and appended y + 1 to the end of p; if d_i < 0, then he looked at the last element of p (let it be y) and appended y - 1 to the end of p. For example, if x = 3, and d = [1, -1, 2], p will be equal [3, 4, 3, 4, 5].Igor decided to calculate the length of the longest increasing subsequence of p and the number of them.A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements.A sequence a is an increasing sequence if each element of a (except the first one) is strictly greater than the previous element.For p = [3, 4, 3, 4, 5], the length of longest increasing subsequence is 3 and there are 3 of them: [\underline{3}, \underline{4}, 3, 4, \underline{5}], [\underline{3}, 4, 3, \underline{4}, \underline{5}], [3, 4, \underline{3}, \underline{4}, \underline{5}].InputThe first line contains a single integer n (1 \leq n \leq 50) — the length of the sequence d.The second line contains a single integer x (-10^9 \leq x \leq 10^9) — the integer on the blackboard.The third line contains n integers d_1, d_2, \ldots, d_n (-10^9 \leq d_i \leq 10^9).OutputPrint two integers: the first integer should be equal to the length of the longest increasing subsequence of p; the second should be equal to the number of them modulo 998244353. You should print only the second number modulo 998244353.ExamplesInput
3
3
1 -1 2
Output
3 3
Input
3
100
5 -3 6
Output
9 7
Input
3
1
999999999 0 1000000000
Output
2000000000 1
Input
5
34
1337 -146 42 -69 228
Output
1393 3876
NoteThe first test case was explained in the statement.In the second test case p = [100, 101, 102, 103, 104, 105, 104, 103, 102, 103, 104, 105, 106, 107, 108].In the third test case p = [1, 2, \ldots, 2000000000]. | 3
3
1 -1 2
| 3 3 | 5 seconds | 256 megabytes | ['dp', 'math', 'matrices', '*3000'] |
E. What Is It?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLunar rover finally reached planet X. After landing, he met an obstacle, that contains permutation p of length n. Scientists found out, that to overcome an obstacle, the robot should make p an identity permutation (make p_i = i for all i).Unfortunately, scientists can't control the robot. Thus the only way to make p an identity permutation is applying the following operation to p multiple times: Select two indices i and j (i \neq j), such that p_j = i and swap the values of p_i and p_j. It takes robot (j - i)^2 seconds to do this operation. Positions i and j are selected by the robot (scientists can't control it). He will apply this operation while p isn't an identity permutation. We can show that the robot will make no more than n operations regardless of the choice of i and j on each operation.Scientists asked you to find out the maximum possible time it will take the robot to finish making p an identity permutation (i. e. worst-case scenario), so they can decide whether they should construct a new lunar rover or just rest and wait. They won't believe you without proof, so you should build an example of p and robot's operations that maximizes the answer.For a better understanding of the statement, read the sample description.InputThe first line of input contains a single integer t (1 \leq t \leq 10^4) — the number of test cases.Each of next t lines contains the single integer n (2 \leq n \leq 10^5) – the length of p.Note, that p is not given to you. You should find the maximum possible time over all permutations of length n.It is guaranteed, that the total sum of n over all test cases doesn't exceed 10^5.OutputFor each test case in the first line, print how many seconds will the robot spend in the worst case.In the next line, print the initial value of p that you used to construct an answer.In the next line, print the number of operations m \leq n that the robot makes in your example.In the each of next m lines print two integers i and j — indices of positions that the robot will swap on this operation. Note that p_j = i must holds (at the time of operation).ExampleInput
3
2
3
3
Output
1
2 1
1
2 1
5
2 3 1
2
1 3
3 2
5
2 3 1
2
1 3
2 3NoteFor n = 2, p can be either [1, 2] or [2, 1]. In the first case p is already identity, otherwise robot will make it an identity permutation in 1 second regardless of choise i and j on the first operation.For n = 3, p can be equals [2, 3, 1]. If robot will select i = 3, j = 2 on the first operation, p will become [2, 1, 3] in one second. Now robot can select only i = 1, j = 2 or i = 2, j = 1. In both cases, p will become identity in one more second (2 seconds in total). If robot will select i = 1, j = 3 on the first operation, p will become [1, 3, 2] in four seconds. Regardless of choise of i and j on the second operation, p will become identity in five seconds. We can show, that for permutation of length 3 robot will always finish all operation in no more than 5 seconds. | 3
2
3
3
| 1 2 1 1 2 1 5 2 3 1 2 1 3 3 2 5 2 3 1 2 1 3 2 3 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*2500'] |
D. Cleaningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring cleaning the coast, Alice found n piles of stones. The i-th pile has a_i stones.Piles i and i + 1 are neighbouring for all 1 \leq i \leq n - 1. If pile i becomes empty, piles i - 1 and i + 1 doesn't become neighbouring.Alice is too lazy to remove these stones, so she asked you to take this duty. She allowed you to do only the following operation: Select two neighboring piles and, if both of them are not empty, remove one stone from each of them. Alice understands that sometimes it's impossible to remove all stones with the given operation, so she allowed you to use the following superability: Before the start of cleaning, you can select two neighboring piles and swap them. Determine, if it is possible to remove all stones using the superability not more than once.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases.The first line of each test case contains the single integer n (2 \leq n \leq 2 \cdot 10^5) — the number of piles.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^9) — the number of stones in each pile.It is guaranteed that the total sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print YES or NO — is it possible to remove all stones using the superability not more than once or not.ExampleInput
5
3
1 2 1
3
1 1 2
5
2 2 2 1 3
5
2100 1900 1600 3000 1600
2
2443 2445
Output
YES
YES
YES
YES
NO
NoteIn the first test case, you can remove all stones without using a superability: [1, 2, 1] \rightarrow [1, 1, 0] \rightarrow [0, 0, 0].In the second test case, you can apply superability to the second and the third piles and then act like in the first testcase.In the third test case, you can apply superability to the fourth and the fifth piles, thus getting a = [2, 2, 2, 3, 1].In the fourth test case, you can apply superability to the first and the second piles, thus getting a = [1900, 2100, 1600, 3000, 1600]. | 5
3
1 2 1
3
1 1 2
5
2 2 2 1 3
5
2100 1900 1600 3000 1600
2
2443 2445
| YES YES YES YES NO | 2 seconds | 256 megabytes | ['data structures', 'dp', 'greedy', 'math', '*2200'] |
C. Array Destructiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a.It could have been an easy task, but it turned out that you should follow some rules: In the beginning, you select any positive integer x. Then you do the following operation n times: select two elements of array with sum equals x; remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation.Note, that you choose x before the start and can't change it as you want between the operations.Determine how should you behave to throw out all elements of a.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains the single integer n (1 \leq n \leq 1000).The second line of each test case contains 2n integers a_1, a_2, \dots, a_{2n} (1 \leq a_i \leq 10^6) — the initial array a.It is guaranteed that the total sum of n over all test cases doesn't exceed 1000.OutputFor each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise.If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove.ExampleInput
4
2
3 5 1 2
3
1 1 8 8 64 64
2
1 1 2 4
5
1 2 3 4 5 6 7 14 3 11
Output
YES
6
1 5
2 3
NO
NO
YES
21
14 7
3 11
5 6
2 4
3 1NoteThe first test case was described in the statement.In the second and third test cases, we can show that it is impossible to throw out all elements of array a. | 4
2
3 5 1 2
3
1 1 8 8 64 64
2
1 1 2 4
5
1 2 3 4 5 6 7 14 3 11
| YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'data structures', 'greedy', 'implementation', 'sortings', '*1700'] |
B. Different Divisorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPositive integer x is called divisor of positive integer y, if y is divisible by x without remainder. For example, 1 is a divisor of 7 and 3 is not divisor of 8.We gave you an integer d and asked you to find the smallest positive integer a, such that a has at least 4 divisors; difference between any two divisors of a is at least d.InputThe first line contains a single integer t (1 \leq t \leq 3000) — the number of test cases.The first line of each test case contains a single integer d (1 \leq d \leq 10000).OutputFor each test case print one integer a — the answer for this test case.ExampleInput
2
1
2
Output
6
15
NoteIn the first test case, integer 6 have following divisors: [1, 2, 3, 6]. There are 4 of them and the difference between any two of them is at least 1. There is no smaller integer with at least 4 divisors.In the second test case, integer 15 have following divisors: [1, 3, 5, 15]. There are 4 of them and the difference between any two of them is at least 2.The answer 12 is INVALID because divisors are [1, 2, 3, 4, 6, 12]. And the difference between, for example, divisors 2 and 3 is less than d=2. | 2
1
2
| 6 15 | 1 second | 256 megabytes | ['binary search', 'constructive algorithms', 'greedy', 'math', 'number theory', '*1000'] |
A. Puzzle From the Futuretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the 2022 year, Mike found two binary integers a and b of length n (both of them are written only by digits 0 and 1) that can have leading zeroes. In order not to forget them, he wanted to construct integer d in the following way: he creates an integer c as a result of bitwise summing of a and b without transferring carry, so c may have one or more 2-s. For example, the result of bitwise summing of 0110 and 1101 is 1211 or the sum of 011000 and 011000 is 022000; after that Mike replaces equal consecutive digits in c by one digit, thus getting d. In the cases above after this operation, 1211 becomes 121 and 022000 becomes 020 (so, d won't have equal consecutive digits). Unfortunately, Mike lost integer a before he could calculate d himself. Now, to cheer him up, you want to find any binary integer a of length n such that d will be maximum possible as integer.Maximum possible as integer means that 102 > 21, 012 < 101, 021 = 21 and so on.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains the integer n (1 \leq n \leq 10^5) — the length of a and b.The second line of each test case contains binary integer b of length n. The integer b consists only of digits 0 and 1.It is guaranteed that the total sum of n over all t test cases doesn't exceed 10^5.OutputFor each test case output one binary integer a of length n. Note, that a or b may have leading zeroes but must have the same length n.ExampleInput
5
1
0
3
011
3
110
6
111000
6
001011
Output
1
110
100
101101
101110
NoteIn the first test case, b = 0 and choosing a = 1 gives d = 1 as a result.In the second test case, b = 011 so: if you choose a = 000, c will be equal to 011, so d = 01; if you choose a = 111, c will be equal to 122, so d = 12; if you choose a = 010, you'll get d = 021. If you select a = 110, you'll get d = 121. We can show that answer a = 110 is optimal and d = 121 is maximum possible.In the third test case, b = 110. If you choose a = 100, you'll get d = 210 and it's the maximum possible d.In the fourth test case, b = 111000. If you choose a = 101101, you'll get d = 212101 and it's maximum possible d.In the fifth test case, b = 001011. If you choose a = 101110, you'll get d = 102121 and it's maximum possible d. | 5
1
0
3
011
3
110
6
111000
6
001011
| 1 110 100 101101 101110 | 1 second | 256 megabytes | ['greedy', '*800'] |
G. Tilestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a road consisting of several rows. Each row is divided into several rectangular tiles, and all tiles in the same row are equal. The first row contains exactly one rectangular tile. Look at the picture below which shows how the tiles are arranged.The road is constructed as follows: the first row consists of 1 tile; then a_1 rows follow; each of these rows contains 1 tile greater than the previous row; then b_1 rows follow; each of these rows contains 1 tile less than the previous row; then a_2 rows follow; each of these rows contains 1 tile greater than the previous row; then b_2 rows follow; each of these rows contains 1 tile less than the previous row; ... then a_n rows follow; each of these rows contains 1 tile greater than the previous row; then b_n rows follow; each of these rows contains 1 tile less than the previous row. An example of the road with n = 2, a_1 = 4, b_1 = 2, a_2 = 2, b_2 = 3. Rows are arranged from left to right. You start from the only tile in the first row and want to reach the last row (any tile of it). From your current tile, you can move to any tile in the next row which touches your current tile.Calculate the number of different paths from the first row to the last row. Since it can be large, print it modulo 998244353.InputThe first line contains one integer n (1 \le n \le 1000).Then n lines follow. The i-th of them contains two integers a_i and b_i (1 \le a_i, b_i \le 10^5; |a_i - b_i| \le 5).Additional constraint on the input: the sequence of a_i and b_i never results in a row with non-positive number of tiles.OutputPrint one integer — the number of paths from the first row to the last row, taken modulo 998244353.ExamplesInput
2
4 2
2 3
Output
850
Input
3
4 1
2 3
3 1
Output
10150
Input
8
328 323
867 868
715 718
721 722
439 435
868 870
834 834
797 796
Output
759099319
| 2
4 2
2 3
| 850 | 4 seconds | 256 megabytes | ['combinatorics', 'dp', 'fft', 'math', '*2800'] |
F. Strange Settime limit per test4 secondsmemory limit per test32 megabytesinputstandard inputoutputstandard outputNote that the memory limit is unusual.You are given an integer n and two sequences a_1, a_2, \dots, a_n and b_1, b_2, \dots, b_n.Let's call a set of integers S such that S \subseteq \{1, 2, 3, \dots, n\} strange, if, for every element i of S, the following condition is met: for every j \in [1, i - 1], if a_j divides a_i, then j is also included in S. An empty set is always strange.The cost of the set S is \sum\limits_{i \in S} b_i. You have to calculate the maximum possible cost of a strange set.InputThe first line contains one integer n (1 \le n \le 3000).The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100).The third line contains n integers b_1, b_2, \dots, b_n (-10^5 \le b_i \le 10^5).OutputPrint one integer — the maximum cost of a strange set.ExamplesInput
9
4 7 3 4 5 6 7 8 13
-2 3 -19 5 -6 7 -8 9 1
Output
16
Input
2
42 42
-37 13
Output
0
Input
2
42 42
13 -37
Output
13
NoteThe strange set with the maximum cost in the first example is \{1, 2, 4, 8, 9\}.The strange set with the maximum cost in the second example is empty. | 9
4 7 3 4 5 6 7 8 13
-2 3 -19 5 -6 7 -8 9 1
| 16 | 4 seconds | 32 megabytes | ['flows', 'math', '*2700'] |
E. Minimum Pathtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Let's define the weight of the path consisting of k edges with indices e_1, e_2, \dots, e_k as \sum\limits_{i=1}^{k}{w_{e_i}} - \max\limits_{i=1}^{k}{w_{e_i}} + \min\limits_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 \le i \le n).InputThe first line contains two integers n and m (2 \le n \le 2 \cdot 10^5; 1 \le m \le 2 \cdot 10^5) — the number of vertices and the number of edges in the graph.Following m lines contains three integers v_i, u_i, w_i (1 \le v_i, u_i \le n; 1 \le w_i \le 10^9; v_i \neq u_i) — endpoints of the i-th edge and its weight respectively.OutputPrint n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 \le i \le n).ExamplesInput
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
| 5 4
5 3 4
2 1 1
3 2 2
2 4 2
| 1 2 2 4 | 3 seconds | 256 megabytes | ['graphs', 'shortest paths', '*2400'] |
D. Programtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types: increase x by 1; decrease x by 1. You are given m queries of the following format: query l r — how many distinct values is x assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order? InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Then the description of t testcases follows.The first line of each testcase contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the number of instructions in the program and the number of queries.The second line of each testcase contains a program — a string of n characters: each character is either '+' or '-' — increment and decrement instruction, respectively.Each of the next m lines contains two integers l and r (1 \le l \le r \le n) — the description of the query.The sum of n over all testcases doesn't exceed 2 \cdot 10^5. The sum of m over all testcases doesn't exceed 2 \cdot 10^5. OutputFor each testcase print m integers — for each query l, r print the number of distinct values variable x is assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order.ExampleInput
2
8 4
-+--+--+
1 8
2 8
2 5
1 1
4 10
+-++
1 1
1 2
2 2
1 3
2 3
3 3
1 4
2 4
3 4
4 4
Output
1
2
4
4
3
3
4
2
3
2
1
2
2
2
NoteThe instructions that remain for each query of the first testcase are: empty program — x was only equal to 0; "-" — x had values 0 and -1; "---+" — x had values 0, -1, -2, -3, -2 — there are 4 distinct values among them; "+--+--+" — the distinct values are 1, 0, -1, -2. | 2
8 4
-+--+--+
1 8
2 8
2 5
1 1
4 10
+-++
1 1
1 2
2 2
1 3
2 3
3 3
1 4
2 4
3 4
4 4
| 1 2 4 4 3 3 4 2 3 2 1 2 2 2 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'implementation', 'strings', '*1700'] |
C. No More Inversionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a sequence a with n elements 1, 2, 3, \dots, k - 1, k, k - 1, k - 2, \dots, k - (n - k) (k \le n < 2k).Let's call as inversion in a a pair of indices i < j such that a[i] > a[j].Suppose, you have some permutation p of size k and you build a sequence b of size n in the following manner: b[i] = p[a[i]].Your goal is to find such permutation p that the total number of inversions in b doesn't exceed the total number of inversions in a, and b is lexicographically maximum.Small reminder: the sequence of k integers is called a permutation if it contains all integers from 1 to k exactly once.Another small reminder: a sequence s is lexicographically smaller than another sequence t, if either s is a prefix of t, or for the first i such that s_i \ne t_i, s_i < t_i holds (in the first position that these sequences are different, s has smaller number than t).InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first and only line of each test case contains two integers n and k (k \le n < 2k; 1 \le k \le 10^5) — the length of the sequence a and its maximum.It's guaranteed that the total sum of k over test cases doesn't exceed 10^5.OutputFor each test case, print k integers — the permutation p which maximizes b lexicographically without increasing the total number of inversions.It can be proven that p exists and is unique.ExampleInput
4
1 1
2 2
3 2
4 3
Output
1
1 2
2 1
1 3 2
NoteIn the first test case, the sequence a = [1], there is only one permutation p = [1].In the second test case, the sequence a = [1, 2]. There is no inversion in a, so there is only one permutation p = [1, 2] which doesn't increase the number of inversions.In the third test case, a = [1, 2, 1] and has 1 inversion. If we use p = [2, 1], then b = [p[a[1]], p[a[2]], p[a[3]]] = [2, 1, 2] and also has 1 inversion.In the fourth test case, a = [1, 2, 3, 2], and since p = [1, 3, 2] then b = [1, 3, 2, 3]. Both a and b have 1 inversion and b is the lexicographically maximum. | 4
1 1
2 2
3 2
4 3
| 1 1 2 2 1 1 3 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', '*1500'] |
B. String LCMtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a multiplication operation between a string a and a positive integer x: a \cdot x is the string that is a result of writing x copies of a one after another. For example, "abc" \cdot~2~= "abcabc", "a" \cdot~5~= "aaaaa".A string a is divisible by another string b if there exists an integer x such that b \cdot x = a. For example, "abababab" is divisible by "ab", but is not divisible by "ababab" or "aa".LCM of two strings s and t (defined as LCM(s, t)) is the shortest non-empty string that is divisible by both s and t.You are given two strings s and t. Find LCM(s, t) or report that it does not exist. It can be shown that if LCM(s, t) exists, it is unique.InputThe first line contains one integer q (1 \le q \le 2000) — the number of test cases.Each test case consists of two lines, containing strings s and t (1 \le |s|, |t| \le 20). Each character in each of these strings is either 'a' or 'b'.OutputFor each test case, print LCM(s, t) if it exists; otherwise, print -1. It can be shown that if LCM(s, t) exists, it is unique.ExampleInput
3
baba
ba
aa
aaa
aba
ab
Output
baba
aaaaaa
-1
NoteIn the first test case, "baba" = "baba" \cdot~1~= "ba" \cdot~2.In the second test case, "aaaaaa" = "aa" \cdot~3~= "aaa" \cdot~2. | 3
baba
ba
aa
aaa
aba
ab
| baba aaaaaa -1 | 2 seconds | 256 megabytes | ['brute force', 'math', 'number theory', 'strings', '*1000'] |
A. Replacing Elementstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a_1, a_2, \dots, a_n. All a_i are positive integers.In one step you can choose three distinct indices i, j, and k (i \neq j; i \neq k; j \neq k) and assign the sum of a_j and a_k to a_i, i. e. make a_i = a_j + a_k.Can you make all a_i lower or equal to d using the operation above any number of times (possibly, zero)?InputThe first line contains a single integer t (1 \le t \le 2000) — the number of test cases.The first line of each test case contains two integers n and d (3 \le n \le 100; 1 \le d \le 100) — the number of elements in the array a and the value d.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100) — the array a.OutputFor each test case, print YES, if it's possible to make all elements a_i less or equal than d using the operation above. Otherwise, print NO.You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).ExampleInput
3
5 3
2 3 2 5 4
3 4
2 4 4
5 4
2 1 5 3 6
Output
NO
YES
YES
NoteIn the first test case, we can prove that we can't make all a_i \le 3.In the second test case, all a_i are already less or equal than d = 4.In the third test case, we can, for example, choose i = 5, j = 1, k = 2 and make a_5 = a_1 + a_2 = 2 + 1 = 3. Array a will become [2, 1, 5, 3, 3].After that we can make a_3 = a_5 + a_2 = 3 + 1 = 4. Array will become [2, 1, 4, 3, 3] and all elements are less or equal than d = 4. | 3
5 3
2 3 2 5 4
3 4
2 4 4
5 4
2 1 5 3 6
| NO YES YES | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', 'sortings', '*800'] |
G. Moving to the Capitaltime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.Before the trip, Polycarp for each city found out the value of d_i — the shortest distance from the capital (the 1-st city) to the i-th city.Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i \geq d_j; Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): 2 \rightarrow 5 \rightarrow 1 \rightarrow 2 \rightarrow 5; 3 \rightarrow 6 \rightarrow 2; 1 \rightarrow 3 \rightarrow 6 \rightarrow 2 \rightarrow 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.InputThe first line contains one integer t (1 \leq t \leq 10^4) — the number of test cases. Then t test cases follow.Each test case is preceded by an empty line.The first line of each test case contains two integers n (2 \leq n \leq 2 \cdot 10^5) and m (1 \leq m \leq 2 \cdot 10^5) — number of cities and roads, respectively.This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 \leq u, v \leq n, u \ne v) — the numbers of cities connected by a one-way road.It is guaranteed that the sums of n and m over all test cases do not exceed 2 \cdot 10^5.It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u — is valid).It is guaranteed that there is a path from the capital to all cities.OutputFor each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.ExampleInput
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
| 3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
| 0 0 1 2 0 1 0 0 0 0 2 1 1 0 | 4 seconds | 256 megabytes | ['dfs and similar', 'dp', 'graphs', 'shortest paths', '*2100'] |
F. New Year's Puzzletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvery year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.Polycarp got the following problem: given a grid strip of size 2 \times n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 \times 1 and 1 \times 2 tiles (dominoes).For example, if n = 5 and the strip looks like this (black cells are blocked): Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors). And if n = 3 and the strip looks like this: It is impossible to tile free cells.Polycarp easily solved this task and received his New Year's gift. Can you solve it?InputThe first line contains an integer t (1 \leq t \leq 10^4) — the number of test cases. Then t test cases follow.Each test case is preceded by an empty line.The first line of each test case contains two integers n and m (1 \le n \le 10^9, 1 \le m \le 2 \cdot 10^5) — the length of the strip and the number of blocked cells on it.Each of the next m lines contains two integers r_i, c_i (1 \le r_i \le 2, 1 \le c_i \le n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) \ne (r_j, c_j), i \ne j.It is guaranteed that the sum of m over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print on a separate line: "YES", if it is possible to tile all unblocked squares with the 2 \times 1 and 1 \times 2 tiles; "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).ExampleInput
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
NoteThe first two test cases are explained in the statement.In the third test case the strip looks like this: It is easy to check that the unblocked squares on it can not be tiled. | 3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
| YES NO NO | 2 seconds | 256 megabytes | ['brute force', 'dp', 'graph matchings', 'greedy', 'sortings', '*2100'] |
E. Correct Placementtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has invited n friends to celebrate the New Year. During the celebration, he decided to take a group photo of all his friends. Each friend can stand or lie on the side.Each friend is characterized by two values h_i (their height) and w_i (their width). On the photo the i-th friend will occupy a rectangle h_i \times w_i (if they are standing) or w_i \times h_i (if they are lying on the side).The j-th friend can be placed in front of the i-th friend on the photo if his rectangle is lower and narrower than the rectangle of the i-th friend. Formally, at least one of the following conditions must be fulfilled: h_j < h_i and w_j < w_i (both friends are standing or both are lying); w_j < h_i and h_j < w_i (one of the friends is standing and the other is lying). For example, if n = 3, h=[3,5,3] and w=[4,4,3], then: the first friend can be placed in front of the second: w_1 < h_2 and h_1 < w_2 (one of the them is standing and the other one is lying); the third friend can be placed in front of the second: h_3 < h_2 and w_3 < w_2 (both friends are standing or both are lying). In other cases, the person in the foreground will overlap the person in the background.Help Polycarp for each i find any j, such that the j-th friend can be located in front of the i-th friend (i.e. at least one of the conditions above is fulfilled).Please note that you do not need to find the arrangement of all people for a group photo. You just need to find for each friend i any other friend j who can be located in front of him. Think about it as you need to solve n separate independent subproblems.InputThe first line contains one integer t (1 \leq t \leq 10^4) — the number of test cases. Then t test cases follow.The first line of each test case contains one integer n (1 \leq n \leq 2 \cdot 10^5) — the number of friends.This is followed by n lines, each of which contains a description of the corresponding friend. Each friend is described by two integers h_i and w_i (1 \leq h_i, w_i \leq 10^9) — height and width of the i-th friend, respectively.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case output n integers on a separate line, where the i-th number is the index of a friend that can be placed in front of the i-th. If there is no such friend, then output -1.If there are several answers, output any.ExampleInput
4
3
3 4
5 4
3 3
3
1 3
2 2
3 1
4
2 2
3 1
6 3
5 4
4
2 2
2 3
1 1
4 4
Output
-1 3 -1
-1 -1 -1
-1 -1 2 2
3 3 -1 3
NoteThe first test case is described in the statement.In the third test case, the following answers are also correct: [-1, -1, 1, 2]; [-1, -1, 1, 1]; [-1, -1, 2, 1]. | 4
3
3 4
5 4
3 3
3
1 3
2 2
3 1
4
2 2
3 1
6 3
5 4
4
2 2
2 3
1 1
4 4
| -1 3 -1 -1 -1 -1 -1 -1 2 2 3 3 -1 3 | 4 seconds | 256 megabytes | ['binary search', 'data structures', 'dp', 'sortings', 'two pointers', '*1700'] |
D. Even-Odd Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring their New Year holidays, Alice and Bob play the following game using an array a of n integers: Players take turns, Alice moves first. Each turn a player chooses any element and removes it from the array. If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared.For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array.InputThe first line contains an integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of each test case contains an integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in the array a.The next line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the array a used to play the game.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output on a separate line: "Alice" if Alice wins with the optimal play; "Bob" if Bob wins with the optimal play; "Tie", if a tie is declared during the optimal play. ExampleInput
4
4
5 2 7 3
3
3 2 1
4
2 2 2 2
2
7 8
Output
Bob
Tie
Alice
Alice
| 4
4
5 2 7 3
3
3 2 1
4
2 2 2 2
2
7 8
| Bob Tie Alice Alice | 2 seconds | 256 megabytes | ['dp', 'games', 'greedy', 'sortings', '*1200'] |
C. Long Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp found under the Christmas tree an array a of n elements and instructions for playing with it: At first, choose index i (1 \leq i \leq n) — starting position in the array. Put the chip at the index i (on the value a_i). While i \leq n, add a_i to your score and move the chip a_i positions to the right (i.e. replace i with i + a_i). If i > n, then Polycarp ends the game. For example, if n = 5 and a = [7, 3, 1, 2, 3], then the following game options are possible: Polycarp chooses i = 1. Game process: i = 1 \overset{+7}{\longrightarrow} 8. The score of the game is: a_1 = 7. Polycarp chooses i = 2. Game process: i = 2 \overset{+3}{\longrightarrow} 5 \overset{+3}{\longrightarrow} 8. The score of the game is: a_2 + a_5 = 6. Polycarp chooses i = 3. Game process: i = 3 \overset{+1}{\longrightarrow} 4 \overset{+2}{\longrightarrow} 6. The score of the game is: a_3 + a_4 = 3. Polycarp chooses i = 4. Game process: i = 4 \overset{+2}{\longrightarrow} 6. The score of the game is: a_4 = 2. Polycarp chooses i = 5. Game process: i = 5 \overset{+3}{\longrightarrow} 8. The score of the game is: a_5 = 3. Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.InputThe first line contains one integer t (1 \leq t \leq 10^4) — the number of test cases. Then t test cases follow.The first line of each test case contains one integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the array a.The next line contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^9) — elements of the array a.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output on a separate line one number — the maximum score that Polycarp can get by playing the game on the corresponding array according to the instruction from the statement. Note that Polycarp chooses any starting position from 1 to n in such a way as to maximize his result.ExampleInput
4
5
7 3 1 2 3
3
2 1 4
6
2 1000 2 3 995 1
5
1 1 1 1 1
Output
7
6
1000
5
NoteThe first test case is explained in the statement.In the second test case, the maximum score can be achieved by choosing i = 1.In the third test case, the maximum score can be achieved by choosing i = 2.In the fourth test case, the maximum score can be achieved by choosing i = 1. | 4
5
7 3 1 2 3
3
2 1 4
6
2 1000 2 3 995 1
5
1 1 1 1 1
| 7 6 1000 5 | 2 seconds | 256 megabytes | ['dp', 'graphs', '*1100'] |
B. Fair Divisiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob received n candies from their parents. Each candy weighs either 1 gram or 2 grams. Now they want to divide all candies among themselves fairly so that the total weight of Alice's candies is equal to the total weight of Bob's candies.Check if they can do that.Note that candies are not allowed to be cut in half.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of each test case contains an integer n (1 \le n \le 100) — the number of candies that Alice and Bob received.The next line contains n integers a_1, a_2, \ldots, a_n — the weights of the candies. The weight of each candy is either 1 or 2.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output on a separate line: "YES", if all candies can be divided into two sets with the same weight; "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).ExampleInput
5
2
1 1
2
1 2
4
1 2 1 2
3
2 2 2
3
2 1 2
Output
YES
NO
YES
NO
NO
NoteIn the first test case, Alice and Bob can each take one candy, then both will have a total weight of 1.In the second test case, any division will be unfair.In the third test case, both Alice and Bob can take two candies, one of weight 1 and one of weight 2.In the fourth test case, it is impossible to divide three identical candies between two people.In the fifth test case, any division will also be unfair. | 5
2
1 1
2
1 2
4
1 2 1 2
3
2 2 2
3
2 1 2
| YES NO YES NO NO | 2 seconds | 256 megabytes | ['dp', 'greedy', 'math', '*800'] |
A. Cards for Friendstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor the New Year, Polycarp decided to send postcards to all his n friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size w \times h, which can be cut into pieces.Polycarp can cut any sheet of paper w \times h that he has in only two cases: If w is even, then he can cut the sheet in half and get two sheets of size \frac{w}{2} \times h; If h is even, then he can cut the sheet in half and get two sheets of size w \times \frac{h}{2}; If w and h are even at the same time, then Polycarp can cut the sheet according to any of the rules above.After cutting a sheet of paper, the total number of sheets of paper is increased by 1.Help Polycarp to find out if he can cut his sheet of size w \times h at into n or more pieces, using only the rules described above.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.Each test case consists of one line containing three integers w, h, n (1 \le w, h \le 10^4, 1 \le n \le 10^9) — the width and height of the sheet Polycarp has and the number of friends he needs to send a postcard to.OutputFor each test case, output on a separate line: "YES", if it is possible to cut a sheet of size w \times h into at least n pieces; "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).ExampleInput
5
2 2 3
3 3 2
5 10 2
11 13 1
1 4 4
Output
YES
NO
YES
YES
YES
NoteIn the first test case, you can first cut the 2 \times 2 sheet into two 2 \times 1 sheets, and then cut each of them into two more sheets. As a result, we get four sheets 1 \times 1. We can choose any three of them and send them to our friends.In the second test case, a 3 \times 3 sheet cannot be cut, so it is impossible to get two sheets.In the third test case, you can cut a 5 \times 10 sheet into two 5 \times 5 sheets.In the fourth test case, there is no need to cut the sheet, since we only need one sheet.In the fifth test case, you can first cut the 1 \times 4 sheet into two 1 \times 2 sheets, and then cut each of them into two more sheets. As a result, we get four sheets 1 \times 1. | 5
2 2 3
3 3 2
5 10 2
11 13 1
1 4 4
| YES NO YES YES YES | 1 second | 256 megabytes | ['greedy', 'math', '*800'] |
B. Strange Listtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have given an array a of length n and an integer x to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be q. If q is divisible by x, the robot adds x copies of the integer \frac{q}{x} to the end of the array, and moves on to the next element. Note that the newly added elements could be processed by the robot later. Otherwise, if q is not divisible by x, the robot shuts down.Please determine the sum of all values of the array at the end of the process.InputThe first input line contains a single integer t (1 \leq t \leq 100) — the number of test cases.The first line of each test case contains two integers n and x (1 \leq n \leq 10^5, 2 \leq x \leq 10^9) — the length of the array and the value which is used by the robot.The next line contains integers a_1, a_2, ..., a_n (1 \leq a_i \leq 10^9) — the initial values in the array.It is guaranteed that the sum of values n over all test cases does not exceed 10^5.OutputFor each test case output one integer — the sum of all elements at the end of the process.ExampleInput
2
1 2
12
4 2
4 6 8 2
Output
36
44
NoteIn the first test case the array initially consists of a single element [12], and x=2. After the robot processes the first element, the array becomes [12, 6, 6]. Then the robot processes the second element, and the array becomes [12, 6, 6, 3, 3]. After the robot processes the next element, the array becomes [12, 6, 6, 3, 3, 3, 3], and then the robot shuts down, since it encounters an element that is not divisible by x = 2. The sum of the elements in the resulting array is equal to 36.In the second test case the array initially contains integers [4, 6, 8, 2], and x=2. The resulting array in this case looks like [4, 6, 8, 2, 2, 2, 3, 3, 4, 4, 1, 1, 1, 1, 1, 1]. | 2
1 2
12
4 2
4 6 8 2
| 36 44 | 1 second | 256 megabytes | ['brute force', 'greedy', 'implementation', 'math', '*1100'] |
A. Strange Partitiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n, and an integer x. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was [3, 6, 9], in a single operation one can replace the last two elements by their sum, yielding an array [3, 15], or replace the first two elements to get an array [9, 9]. Note that the size of the array decreases after each operation.The beauty of an array b=[b_1, \ldots, b_k] is defined as \sum_{i=1}^k \left\lceil \frac{b_i}{x} \right\rceil, which means that we divide each element by x, round it up to the nearest integer, and sum up the resulting values. For example, if x = 3, and the array is [4, 11, 6], the beauty of the array is equal to \left\lceil \frac{4}{3} \right\rceil + \left\lceil \frac{11}{3} \right\rceil + \left\lceil \frac{6}{3} \right\rceil = 2 + 4 + 2 = 8.Please determine the minimum and the maximum beauty you can get by performing some operations on the original array.InputThe first input line contains a single integer t — the number of test cases (1 \le t \le 1000).The first line of each test case contains two integers n and x (1 \leq n \leq 10^5, 1 \leq x \leq 10^9).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. It is guaranteed that the sum of values of n over all test cases does not exceed 10^5.OutputFor each test case output two integers — the minimal and the maximal possible beauty.ExampleInput
2
3 3
3 6 9
3 3
6 4 11
Output
6 6
7 8
NoteIn the first test case the beauty of the array does not change if we perform any operations.In the second example we can leave the array unchanged to attain the maximum beauty, and to get the minimum beauty one can replace two elements 4 and 11 with their sum, yielding an array [6, 15], which has its beauty equal to 7. | 2
3 3
3 6 9
3 3
6 4 11
| 6 6 7 8 | 1 second | 256 megabytes | ['greedy', 'math', 'number theory', '*900'] |
F. Strange Coveringtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n points on a plane. Please find the minimum sum of areas of two axis-aligned rectangles, such that each point is contained in at least one of these rectangles.Note that the chosen rectangles can be degenerate. Rectangle contains all the points that lie inside it or on its boundary.InputThe first line contains one integer t (1 \le t \le 2 \cdot 10^5) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of points.The following n lines contain the coordinates of the points x_i and y_i (0 \le x_i, y_i \le 10^9). It is guaranteed that the points are distinct.It is guaranteed that the sum of values n over all test cases does not exceed 2\cdot10^5.OutputFor each test case print one integer — the minimum sum of areas.ExampleInput
3
2
9 1
1 6
2
8 10
0 7
4
0 0
1 1
9 9
10 10
Output
0
0
2
NoteIn the first two test cases the answer consists of 2 degenerate rectangles. In the third test case one of the possible answers consists of two rectangles 1 \times 1 with bottom left corners (0,0) and (9,9). | 3
2
9 1
1 6
2
8 10
0 7
4
0 0
1 1
9 9
10 10
| 0 0 2 | 6 seconds | 256 megabytes | ['divide and conquer', '*3500'] |
E. Strange Permutationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice had a permutation p_1, p_2, \ldots, p_n. Unfortunately, the permutation looked very boring, so she decided to change it and choose some non-overlapping subranges of this permutation and reverse them. The cost of reversing a single subrange [l, r] (elements from position l to position r, inclusive) is equal to r - l, and the cost of the operation is the sum of costs of reversing individual subranges. Alice had an integer c in mind, so she only considered operations that cost no more than c.Then she got really bored, and decided to write down all the permutations that she could possibly obtain by performing exactly one operation on the initial permutation. Of course, Alice is very smart, so she wrote down each obtainable permutation exactly once (no matter in how many ways it can be obtained), and of course the list was sorted lexicographically.Now Bob would like to ask Alice some questions about her list. Each question is in the following form: what is the i-th number in the j-th permutation that Alice wrote down? Since Alice is too bored to answer these questions, she asked you to help her out.InputThe first line contains a single integer t (1 \leq t \leq 30) — the number of test cases.The first line of each test case contains three integers n, c, q (1 \leq n \leq 3 \cdot 10^4, 1 \leq c \leq 4, 1 \leq q \leq 3 \cdot 10^5) — the length of the permutation, the maximum cost of the operation, and the number of queries.The next line of each test case contains n integers p_1, p_2, \dots, p_n (1 \leq p_i \leq n, p_i \neq p_j if i \neq j), describing the initial permutation.The following q lines describe the queries. Each of them contains two integers i and j (1 \leq i \leq n, 1 \leq j \leq 10^{18}), denoting parameters of this query.It is guaranteed that the sum of values n over all test cases does not exceed 3 \cdot 10^5, and the sum of values q over all test cases does not exceed 3 \cdot 10^5.OutputFor each query output the answer for this query, or -1 if j-th permutation does not exist in her list.ExamplesInput
2
3 1 9
1 2 3
1 1
2 1
3 1
1 2
2 2
3 2
1 3
2 3
3 3
6 4 4
6 5 4 3 1 2
1 1
3 14
1 59
2 6
Output
1
2
3
1
3
2
2
1
3
1
4
-1
5
Input
1
12 4 2
1 2 3 4 5 6 7 8 9 10 11 12
2 20
2 21
Output
2
2
NoteIn the first test case, Alice wrote down the following permutations: [1, 2, 3], [1, 3, 2], [2, 1, 3].Note that, for a permutation [3, 2, 1] Alice would have to reverse the whole array, and it would cost her 2, which is greater than the specified value c=1. The other two permutations can not be obtained by performing exactly one operation described in the problem statement. | 2
3 1 9
1 2 3
1 1
2 1
3 1
1 2
2 2
3 2
1 3
2 3
3 3
6 4 4
6 5 4 3 1 2
1 1
3 14
1 59
2 6
| 1 2 3 1 3 2 2 1 3 1 4 -1 5 | 3 seconds | 256 megabytes | ['binary search', 'combinatorics', 'data structures', 'dp', 'graphs', 'implementation', 'two pointers', '*3200'] |
D. Strange Housingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputStudents of Winter Informatics School are going to live in a set of houses connected by underground passages. Teachers are also going to live in some of these houses, but they can not be accommodated randomly. For safety reasons, the following must hold: All passages between two houses will be closed, if there are no teachers in both of them. All other passages will stay open. It should be possible to travel between any two houses using the underground passages that are open. Teachers should not live in houses, directly connected by a passage. Please help the organizers to choose the houses where teachers will live to satisfy the safety requirements or determine that it is impossible.InputThe first input line contains a single integer t — the number of test cases (1 \le t \le 10^5). Each test case starts with two integers n and m (2 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5) — the number of houses and the number of passages.Then m lines follow, each of them contains two integers u and v (1 \le u, v \le n, u \neq v), describing a passage between the houses u and v. It is guaranteed that there are no two passages connecting the same pair of houses.The sum of values n over all test cases does not exceed 3 \cdot 10^5, and the sum of values m over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, if there is no way to choose the desired set of houses, output "NO". Otherwise, output "YES", then the total number of houses chosen, and then the indices of the chosen houses in arbitrary order.ExamplesInput
2
3 2
3 2
2 1
4 2
1 4
2 3
Output
YES
2
1 3
NO
Input
1
17 27
1 8
2 9
3 10
4 11
5 12
6 13
7 14
8 9
8 14
8 15
9 10
9 15
10 11
10 15
10 17
11 12
11 17
12 13
12 16
12 17
13 14
13 16
14 16
14 15
15 16
15 17
16 17
Output
YES
8
1 3 4 5 6 9 14 17
NoteThe picture below shows the second example test. | 2
3 2
3 2
2 1
4 2
1 4
2 3
| YES 2 1 3 NO | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graph matchings', 'graphs', 'greedy', '*2200'] |
C. Strange Shuffletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.n people sitting in a circle are trying to shuffle a deck of cards. The players are numbered from 1 to n, so that players i and i+1 are neighbours (as well as players 1 and n). Each of them has exactly k cards, where k is even. The left neighbour of a player i is player i - 1, and their right neighbour is player i + 1 (except for players 1 and n, who are respective neighbours of each other).Each turn the following happens: if a player has x cards, they give \lfloor x / 2 \rfloor to their neighbour on the left and \lceil x / 2 \rceil cards to their neighbour on the right. This happens for all players simultaneously.However, one player p is the impostor and they just give all their cards to their neighbour on the right. You know the number of players n and the number of cards k each player has initially, but p is unknown to you. Your task is to determine the value of p, by asking questions like "how many cards does player q have?" for an index q of your choice. After each question all players will make exactly one move and give their cards to their neighbours. You need to find the impostor by asking no more than 1000 questions.InputThe first line contains two integers n and k (4 \le n \le 10^5, 2 \le k \le 10^9, k is even) — the number of players and the number of cards.InteractionYou can ask questions by printing "? q". The answer to this question is the number of cards player q has now (1 \le q \le n). The shuffling process starts immediately after your first question, so the answer to the first one is always equal to k.Once you have identified the impostor, you can output the answer by printing "! p", where p is the player who is the impostor (1 \le p \le n). Then you have to terminate your program.You have to find the impostor by asking no more than 1000 questions. 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 make a hack, use the following test format.The only line of input should contain three integers n, k and p (4 \le n \le 10^5, 2 \le k \le 10^9, k is even, 1 \le p \le n) — the number of people, the number of cards each person has initially, and the position of the impostor.ExampleInput
4 2
2
1
2
3
2
Output
? 1
? 1
? 2
? 3
? 4
! 2
NoteIn the example the cards are transferred in the following way: 2 2 2 2 — player 1 has 2 cards. 1 2 3 2 — player 1 has 1 card.After this turn the number of cards remains unchanged for each player. | 4 2
2
1
2
3
2
| ? 1 ? 1 ? 2 ? 3 ? 4 ! 2 | 1 second | 256 megabytes | ['binary search', 'brute force', 'constructive algorithms', 'interactive', '*2500'] |
B. Strange Definitiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet us call two integers x and y adjacent if \frac{lcm(x, y)}{gcd(x, y)} is a perfect square. For example, 3 and 12 are adjacent, but 6 and 9 are not.Here gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y, and lcm(x, y) denotes the least common multiple (LCM) of integers x and y.You are given an array a of length n. Each second the following happens: each element a_i of the array is replaced by the product of all elements of the array (including itself), that are adjacent to the current value. Let d_i be the number of adjacent elements to a_i (including a_i itself). The beauty of the array is defined as \max_{1 \le i \le n} d_i. You are given q queries: each query is described by an integer w, and you have to output the beauty of the array after w seconds.InputThe first input line contains a single integer t (1 \le t \le 10^5) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 3 \cdot 10^5) — the length of the array.The following line contains n integers a_1, \ldots, a_n (1 \le a_i \le 10^6) — array elements. The next line contain a single integer q (1 \le q \le 3 \cdot 10^5) — the number of queries.The following q lines contain a single integer w each (0 \le w \le 10^{18}) — the queries themselves.It is guaranteed that the sum of values n over all test cases does not exceed 3 \cdot 10^5, and the sum of values q over all test cases does not exceed 3 \cdot 10^5OutputFor each query output a single integer — the beauty of the array at the corresponding moment.ExampleInput
2
4
6 8 4 2
1
0
6
12 3 20 5 80 1
1
1
Output
2
3
NoteIn the first test case, the initial array contains elements [6, 8, 4, 2]. Element a_4=2 in this array is adjacent to a_4=2 (since \frac{lcm(2, 2)}{gcd(2, 2)}=\frac{2}{2}=1=1^2) and a_2=8 (since \frac{lcm(8,2)}{gcd(8, 2)}=\frac{8}{2}=4=2^2). Hence, d_4=2, and this is the maximal possible value d_i in this array.In the second test case, the initial array contains elements [12, 3, 20, 5, 80, 1]. The elements adjacent to 12 are \{12, 3\}, the elements adjacent to 3 are \{12, 3\}, the elements adjacent to 20 are \{20, 5, 80\}, the elements adjacent to 5 are \{20, 5, 80\}, the elements adjacent to 80 are \{20, 5, 80\}, the elements adjacent to 1 are \{1\}. After one second, the array is transformed into [36, 36, 8000, 8000, 8000, 1]. | 2
4
6 8 4 2
1
0
6
12 3 20 5 80 1
1
1
| 2 3 | 2 seconds | 256 megabytes | ['bitmasks', 'graphs', 'hashing', 'math', 'number theory', '*1900'] |
A. Strange Birthday Partytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya organized a strange birthday party. He invited n friends and assigned an integer k_i to the i-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are m unique presents available, the j-th present costs c_j dollars (1 \le c_1 \le c_2 \le \ldots \le c_m). It's not allowed to buy a single present more than once.For the i-th friend Petya can either buy them a present j \le k_i, which costs c_j dollars, or just give them c_{k_i} dollars directly.Help Petya determine the minimum total cost of hosting his party.InputThe first input line contains a single integer t (1 \leq t \leq 10^3) — the number of test cases.The first line of each test case contains two integers n and m (1 \leq n, m \leq 3 \cdot 10^5) — the number of friends, and the number of unique presents available.The following line contains n integers k_1, k_2, \ldots, k_n (1 \leq k_i \leq m), assigned by Petya to his friends. The next line contains m integers c_1, c_2, \ldots, c_m (1 \le c_1 \le c_2 \le \ldots \le c_m \le 10^9) — the prices of the presents.It is guaranteed that sum of values n over all test cases does not exceed 3 \cdot 10^5, and the sum of values m over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case output a single integer — the minimum cost of the party.ExamplesInput
2
5 4
2 3 4 3 2
3 5 12 20
5 5
5 4 3 2 1
10 40 90 160 250
Output
30
190
Input
1
1 1
1
1
Output
1
NoteIn the first example, there are two test cases. In the first one, Petya has 5 friends and 4 available presents. Petya can spend only 30 dollars if he gives 5 dollars to the first friend. A present that costs 12 dollars to the second friend. A present that costs 5 dollars to the third friend. A present that costs 3 dollars to the fourth friend. 5 dollars to the fifth friend. In the second one, Petya has 5 and 5 available presents. Petya can spend only 190 dollars if he gives A present that costs 10 dollars to the first friend. A present that costs 40 dollars to the second friend. 90 dollars to the third friend. 40 dollars to the fourth friend. 10 dollars to the fifth friend. | 2
5 4
2 3 4 3 2
3 5 12 20
5 5
5 4 3 2 1
10 40 90 160 250
| 30 190 | 1 second | 256 megabytes | ['binary search', 'dp', 'greedy', 'sortings', 'two pointers', '*1300'] |
F. Power Socketstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output// We decided to drop the legend about the power sockets but feel free to come up with your own :^)Define a chain: a chain of length 1 is a single vertex; a chain of length x is a chain of length x-1 with a new vertex connected to the end of it with a single edge. You are given n chains of lengths l_1, l_2, \dots, l_n. You plan to build a tree using some of them. Each vertex of the tree is either white or black. The tree initially only has a white root vertex. All chains initially consist only of white vertices. You can take one of the chains and connect any of its vertices to any white vertex of the tree with an edge. The chain becomes part of the tree. Both endpoints of this edge become black. Each chain can be used no more than once. Some chains can be left unused. The distance between two vertices of the tree is the number of edges on the shortest path between them.If there is at least k white vertices in the resulting tree, then the value of the tree is the distance between the root and the k-th closest white vertex.What's the minimum value of the tree you can obtain? If there is no way to build a tree with at least k white vertices, then print -1.InputThe first line contains two integers n and k (1 \le n \le 2 \cdot 10^5, 2 \le k \le 10^9) — the number of chains and the minimum number of white vertices a tree should have to have a value.The second line contains n integers l_1, l_2, \dots, l_n (3 \le l_i \le 2 \cdot 10^5) — the lengths of the chains.OutputPrint a single integer. If there is no way to build a tree with at least k white vertices, then print -1. Otherwise, print the minimum value the tree can have.ExamplesInput
1 2
3
Output
2
Input
3 3
4 3 3
Output
3
Input
3 5
4 3 4
Output
4
Input
2 10
5 7
Output
-1
Note You are allowed to not use all the chains, so it's optimal to only use chain of length 4 in the second example. | 1 2
3
| 2 | 4 seconds | 256 megabytes | ['binary search', 'data structures', 'greedy', '*2600'] |
E. A Bit Similartime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputLet's call two strings a and b (both of length k) a bit similar if they have the same character in some position, i. e. there exists at least one i \in [1, k] such that a_i = b_i.You are given a binary string s of length n (a string of n characters 0 and/or 1) and an integer k. Let's denote the string s[i..j] as the substring of s starting from the i-th character and ending with the j-th character (that is, s[i..j] = s_i s_{i + 1} s_{i + 2} \dots s_{j - 1} s_j).Let's call a binary string t of length k beautiful if it is a bit similar to all substrings of s having length exactly k; that is, it is a bit similar to s[1..k], s[2..k+1], \dots, s[n-k+1..n].Your goal is to find the lexicographically smallest string t that is beautiful, or report that no such string exists. String x is lexicographically less than string y if either x is a prefix of y (and x \ne y), or there exists such i (1 \le i \le \min(|x|, |y|)), that x_i < y_i, and for any j (1 \le j < i) x_j = y_j.InputThe first line contains one integer q (1 \le q \le 10000) — the number of test cases. Each test case consists of two lines.The first line of each test case contains two integers n and k (1 \le k \le n \le 10^6). The second line contains the string s, consisting of n characters (each character is either 0 or 1).It is guaranteed that the sum of n over all test cases does not exceed 10^6.OutputFor each test case, print the answer as follows: if it is impossible to construct a beautiful string, print one line containing the string NO (note: exactly in upper case, you can't print No, for example); otherwise, print two lines. The first line should contain the string YES (exactly in upper case as well); the second line — the lexicographically smallest beautiful string, consisting of k characters 0 and/or 1. ExampleInput
7
4 2
0110
4 2
1001
9 3
010001110
9 3
101110001
10 3
0101110001
10 10
1111111111
11 10
11111111110
Output
YES
11
YES
00
YES
010
YES
101
NO
YES
0000000001
YES
0000000010
| 7
4 2
0110
4 2
1001
9 3
010001110
9 3
101110001
10 3
0101110001
10 10
1111111111
11 10
11111111110
| YES 11 YES 00 YES 010 YES 101 NO YES 0000000001 YES 0000000010 | 2 seconds | 1024 megabytes | ['bitmasks', 'brute force', 'hashing', 'string suffix structures', 'strings', 'two pointers', '*2400'] |
D. Ceil Divisionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a_1, a_2, \dots, a_n where a_i = i.In one step, you can choose two indices x and y (x \neq y) and set a_x = \left\lceil \frac{a_x}{a_y} \right\rceil (ceiling function).Your goal is to make array a consist of n - 1 ones and 1 two in no more than n + 5 steps. Note that you don't have to minimize the number of steps.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first and only line of each test case contains the single integer n (3 \le n \le 2 \cdot 10^5) — the length of array a.It's guaranteed that the sum of n over test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print the sequence of operations that will make a as n - 1 ones and 1 two in the following format: firstly, print one integer m (m \le n + 5) — the number of operations; next print m pairs of integers x and y (1 \le x, y \le n; x \neq y) (x may be greater or less than y) — the indices of the corresponding operation.It can be proven that for the given constraints it's always possible to find a correct sequence of operations.ExampleInput
2
3
4
Output
2
3 2
3 2
3
3 4
4 2
4 2
NoteIn the first test case, you have array a = [1, 2, 3]. For example, you can do the following: choose 3, 2: a_3 = \left\lceil \frac{a_3}{a_2} \right\rceil = 2 and array a = [1, 2, 2]; choose 3, 2: a_3 = \left\lceil \frac{2}{2} \right\rceil = 1 and array a = [1, 2, 1]. You've got array with 2 ones and 1 two in 2 steps.In the second test case, a = [1, 2, 3, 4]. For example, you can do the following: choose 3, 4: a_3 = \left\lceil \frac{3}{4} \right\rceil = 1 and array a = [1, 2, 1, 4]; choose 4, 2: a_4 = \left\lceil \frac{4}{2} \right\rceil = 2 and array a = [1, 2, 1, 2]; choose 4, 2: a_4 = \left\lceil \frac{2}{2} \right\rceil = 1 and array a = [1, 2, 1, 1]. | 2
3
4
| 2 3 2 3 2 3 3 4 4 2 4 2 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'math', 'number theory', '*1700'] |
C. Building a Fencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to build a fence that will consist of n equal sections. All sections have a width equal to 1 and height equal to k. You will place all sections in one line side by side.Unfortunately, the ground beneath the fence is not flat. For simplicity, you can think that the ground level under the i-th section is equal to h_i. You should follow several rules to build the fence: the consecutive sections should have a common side of length at least 1; the first and the last sections should stand on the corresponding ground levels; the sections between may be either on the ground level or higher, but not higher than k - 1 from the ground level h_i (the height should be an integer); One of possible fences (blue color) for the first test case Is it possible to build a fence that meets all rules?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 two integers n and k (2 \le n \le 2 \cdot 10^5; 2 \le k \le 10^8) — the number of sections in the fence and the height of each section.The second line of each test case contains n integers h_1, h_2, \dots, h_n (0 \le h_i \le 10^8), where h_i is the ground level beneath the i-th section.It's guaranteed that the sum of n over test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case print YES if it's possible to build the fence that meets all rules. Otherwise, print NO.You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).ExampleInput
3
6 3
0 0 2 5 1 1
2 3
0 2
3 2
3 0 2
Output
YES
YES
NO
NoteIn the first test case, one of the possible fences is shown in the picture.In the second test case, according to the second rule, you should build both sections on the corresponding ground levels, and since k = 3, h_1 = 0, and h_2 = 2 the first rule is also fulfilled.In the third test case, according to the second rule, you should build the first section on height 3 and the third section on height 2. According to the first rule, the second section should be on the height of at least 2 (to have a common side with the first section), but according to the third rule, the second section can be built on the height of at most h_2 + k - 1 = 1. | 3
6 3
0 0 2 5 1 1
2 3
0 2
3 2
3 0 2
| YES YES NO | 2 seconds | 256 megabytes | ['dp', 'greedy', 'implementation', 'two pointers', '*1600'] |
B. Red and Bluetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp had a sequence a consisting of n + m integers a_1, a_2, \dots, a_{n + m}. He painted the elements into two colors, red and blue; n elements were painted red, all other m elements were painted blue.After painting the elements, he has written two sequences r_1, r_2, \dots, r_n and b_1, b_2, \dots, b_m. The sequence r consisted of all red elements of a in the order they appeared in a; similarly, the sequence b consisted of all blue elements of a in the order they appeared in a as well.Unfortunately, the original sequence was lost, and Monocarp only has the sequences r and b. He wants to restore the original sequence. In case there are multiple ways to restore it, he wants to choose a way to restore that maximizes the value of f(a) = \max(0, a_1, (a_1 + a_2), (a_1 + a_2 + a_3), \dots, (a_1 + a_2 + a_3 + \dots + a_{n + m}))Help Monocarp to calculate the maximum possible value of f(a).InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases. Then the test cases follow. Each test case consists of four lines.The first line of each test case contains one integer n (1 \le n \le 100).The second line contains n integers r_1, r_2, \dots, r_n (-100 \le r_i \le 100).The third line contains one integer m (1 \le m \le 100).The fourth line contains m integers b_1, b_2, \dots, b_m (-100 \le b_i \le 100).OutputFor each test case, print one integer — the maximum possible value of f(a).ExampleInput
4
4
6 -5 7 -3
3
2 3 -4
2
1 1
4
10 -3 2 2
5
-1 -2 -3 -4 -5
5
-1 -2 -3 -4 -5
1
0
1
0
Output
13
13
0
0
NoteIn the explanations for the sample test cases, red elements are marked as bold.In the first test case, one of the possible sequences a is [\mathbf{6}, 2, \mathbf{-5}, 3, \mathbf{7}, \mathbf{-3}, -4].In the second test case, one of the possible sequences a is [10, \mathbf{1}, -3, \mathbf{1}, 2, 2].In the third test case, one of the possible sequences a is [\mathbf{-1}, -1, -2, -3, \mathbf{-2}, -4, -5, \mathbf{-3}, \mathbf{-4}, \mathbf{-5}].In the fourth test case, one of the possible sequences a is [0, \mathbf{0}]. | 4
4
6 -5 7 -3
3
2 3 -4
2
1 1
4
10 -3 2 2
5
-1 -2 -3 -4 -5
5
-1 -2 -3 -4 -5
1
0
1
0
| 13 13 0 0 | 2 seconds | 512 megabytes | ['dp', 'greedy', '*1000'] |
A. Regular Bracket Sequencetime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS".You are given a sequence s of n characters (, ), and/or ?. There is exactly one character ( and exactly one character ) in this sequence.You have to replace every character ? with either ) or ( (different characters ? can be replaced with different brackets). You cannot reorder the characters, remove them, insert other characters, and each ? must be replaced.Determine if it is possible to obtain an RBS after these replacements.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Each test case consists of one line containing s (2 \le |s| \le 100) — a sequence of characters (, ), and/or ?. There is exactly one character ( and exactly one character ) in this sequence.OutputFor each test case, print YES if it is possible to obtain a regular bracket sequence, or NO otherwise}. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).ExampleInput
5
()
(?)
(??)
??()
)?(?
Output
YES
NO
YES
YES
NO
NoteIn the first test case, the sequence is already an RBS.In the third test case, you can obtain an RBS as follows: ()() or (()).In the fourth test case, you can obtain an RBS as follows: ()(). | 5
()
(?)
(??)
??()
)?(?
| YES NO YES YES NO | 1 second | 512 megabytes | ['constructive algorithms', 'greedy', '*1000'] |
N. Waste Sortingtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe progress is not standing still in Berland. Recently all garbage containers in Bertown, the capital of Berland, were replaced by differentiated recycling bins, each accepting some category of waste. While this will definitely improve the ecological situation, for some citizens it's difficult to get used to the habit of sorting waste.Monocarp is one of those citizens who tries to get used to waste sorting. Today he has to take out the trash from his house. There are three containers near the Monocarp's house, the first one accepts paper waste, the second one accepts plastic waste, and the third one — all other types of waste. It is possible to fit c_1 items into the first container, c_2 items into the second container and c_3 items into the third container.Monocarp has a lot of items to throw into containers. Some are made of paper, so Monocarp has to put them into the first container (he has a_1 such items), some are made of plastic, so he has to put them into the second container (he has a_2 such items), and some are neither paper nor plastic — so Monocarp has to put them into the third container (he has a_3 such items).Unfortunately, there are also two categories of items that Monocarp is unsure of: he has a_4 items which are partially made of paper, so he will put each of these items either into the first container or into the third container. Similarly, he has a_5 items partially made of plastic, so he has to put each of them either into the second container or into the third container. Obviously, this choice is made separately for each item — for example, Monocarp can throw several partially-plastic items into the second container, and all other partially-plastic items — into the third one.Now Monocarp wonders: is it possible to put each item into some container so that the first container will hold no more than c_1 items, the second one — no more than c_2 items, and the third one — no more than c_3 items?InputThe first line contains one integer t (1 \le t \le 3 \cdot 10^4) — the number of test cases. Each test case consists of two lines. The first line of each test case contains three integers c_1, c_2, c_3 (0 \le c_1, c_2, c_3 \le 10^8) — the capacities of the containers. The second line of each test case contains five integers a_1, a_2, a_3, a_4, a_5 (0 \le a_i \le 10^8), where a_i is the number of items of the i-th category Monocarp has to throw out (i = 1 is paper waste, i = 2 is plastic waste, i = 3 is general waste, i = 4 is partially-paper waste, i = 5 is partially-plastic waste).OutputFor each test case, print either YES if it is possible to fit all items into containers, or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).ExampleInput
7
1 2 3
1 2 3 0 0
2 2 3
1 2 3 1 0
2 2 3
1 2 3 0 1
1 2 5
1 2 3 1 1
0 0 0
0 0 0 0 0
0 0 4
1 0 0 0 0
13 37 42
0 0 0 40 47
Output
YES
YES
NO
YES
YES
NO
YES
NoteExplanations for the example test cases: Monocarp can put 1 item of paper waste into the first container, 2 items of plastic waste into the second container, and 3 items of general waste into the third container; Monocarp can put 1 item of paper waste and 1 item of partially-paper waste into the first container, 2 items of plastic waste into the second container, and 3 items of general waste into the third container; there is no answer since either the second container should contain 3 items, or the third container should contain 4 items; Monocarp can put 1 item of paper waste into the first container, 2 items of plastic waste into the second container, and 3 items of general waste, 1 item of partially-paper waste and 1 item of partially-plastic waste into the third container; there is no waste at all, so all containers can be left empty; there's no answer since it's impossible to put a paper item into the third container; Monocarp can put 10 items of partially-paper waste into the first container, 37 items of partially-plastic waste into the second container, and 30 items of partially-paper waste and 10 items of partially-plastic waste into the third container. | 7
1 2 3
1 2 3 0 0
2 2 3
1 2 3 1 0
2 2 3
1 2 3 0 1
1 2 5
1 2 3 1 1
0 0 0
0 0 0 0 0
0 0 4
1 0 0 0 0
13 37 42
0 0 0 40 47
| YES YES NO YES YES NO YES | 2 seconds | 512 megabytes | ['greedy', 'implementation', '*900'] |
M. Similar Setstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given n sets of integers. The i-th set contains k_i integers.Two sets are called similar if they share at least two common elements, i. e. there exist two integers x and y such that x \ne y, and they both belong to each of the two sets.Your task is to find two similar sets among the given ones, or report that there is no such pair of sets.InputThe first line contains a single integer t (1 \le t \le 50000) — the number of test cases. Then t test cases follow.The first line of each test case contains a single integer n (2 \le n \le 10^5) the number of given sets. The following n lines describe the sets. The i-th line starts with an integer k_i (2 \le k_i \le 10^5) — the number of integers in the i-th set. Then k_i integers a_{i,1}, a_{i,2}, ..., a_{i,k_i} (1 \le a_{i,j} \le 10^9) follow — the elements of the i-th set. It is guaranteed that all elements in each set are different.The total number of elements in all sets in all test cases is not greater than 2\cdot 10^5.OutputFor each test case, print the answer on a single line. If there is no pair of similar sets, print -1. Otherwise, print two different integers — the indices of the similar sets. The sets are numbered from 1 to n in the order they are given in the input. If there are multiple answers, print any of them.ExampleInput
342 1 103 1 3 55 5 4 3 2 13 10 20 3034 1 2 3 44 2 3 4 54 3 4 5 623 1 3 53 4 3 2Output
2 3
1 2
-1
| 342 1 103 1 3 55 5 4 3 2 13 10 20 3034 1 2 3 44 2 3 4 54 3 4 5 623 1 3 53 4 3 2 | 2 3 1 2 -1 | 1 second | 512 megabytes | ['data structures', 'graphs', 'implementation', '*2300'] |
L. Prime Divisors Selectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSuppose you have a sequence of k integers A = [a_1, a_2, \dots , a_k] where each a_i \geq 2. A sequence of prime integers P = [p_1, p_2, \dots, p_k] is called suitable for the sequence A if a_1 is divisible by p_1, a_2 is divisible by p_2 and so on. A sequence of prime integers P is called friendly if there are no unique integers in this sequence. A sequence A is called ideal, if each sequence P that is suitable for A is friendly as well (i. e. there is no sequence P that is suitable for A, but not friendly). For example, the sequence [2, 4, 16] is ideal, while the sequence [2, 4, 6] is not ideal (there exists a sequence P = [2, 2, 3] which is suitable for A, but not friendly).You are given n different integers x_1, x_2, ..., x_n. You have to choose exactly k of them in such a way that they form an ideal sequence, or report that it is impossible. Note that no integer can be chosen more than once.InputThe first line contains two integers n and k (1 \leq k \leq n \leq 1000). The second line contains n pairwise distinct integers x_1, x_2, ..., x_n (2 \leq x_i \leq 10^{18}).OutputIf it is impossible to choose exactly k integers from x_1, x_2, ..., x_n in such a way that the chosen integers form an ideal sequence, print 0.Otherwise, print k pairwise distinct integers — the elements of the chosen ideal sequence. If there are multiple answers, print any of them.ExamplesInput3 32 4 6Output0Input3 32 4 16Output2 4 16 Input4 32 4 6 16Output2 4 16 | Input3 32 4 6 | Output0 | 2 seconds | 512 megabytes | ['binary search', 'greedy', 'math', 'number theory', '*2700'] |
K. The Robottime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is a robot on a checkered field that is endless in all directions. Initially, the robot is located in the cell with coordinates (0, 0). He will execute commands which are described by a string of capital Latin letters 'L', 'R', 'D', 'U'. When a command is executed, the robot simply moves in the corresponding direction: 'L': one cell to the left (the x-coordinate of the current cell decreases by 1); 'R': one cell to the right (the x-coordinate of the current cell is increased by 1); 'D': one cell down (the y-coordinate of the current cell decreases by 1); 'U': one cell up (the y-coordinate of the current cell is increased by 1). Your task is to put an obstacle in one cell of the field so that after executing the commands, the robot will return to the original cell of its path (0, 0). Of course, an obstacle cannot be placed in the starting cell (0, 0). It is guaranteed that if the obstacle is not placed, then the robot will not return to the starting cell.An obstacle affects the movement of the robot in the following way: if it tries to go in a certain direction, and there is an obstacle, then it simply remains in place (the obstacle also remains, that is, it does not disappear).Find any such cell of the field (other than (0, 0)) that if you put an obstacle there, the robot will return to the cell (0, 0) after the execution of all commands. If there is no solution, then report it.InputThe first line contains one integer t (1 \le t \le 500) — the number of test cases.Each test case consists of a single line containing s — the sequence of commands, which are uppercase Latin letters 'L', 'R', 'D', 'U' only. The length of s is between 1 and 5000, inclusive. Additional constraint on s: executing this sequence of commands leads the robot to some cell other than (0, 0), if there are no obstacles.The sum of lengths of all s in a test doesn't exceed 5000.OutputFor each test case print a single line: if there is a solution, print two integers x and y (-10^9 \le x,y \le 10^9) such that an obstacle in (x, y) will force the robot to return back to the cell (0, 0); otherwise, print two zeroes (i. e. 0 0). If there are multiple answers, you can print any of them.ExampleInput
4LRUUDLLLUUDDDUUUUUOutput
-1 0
1 2
0 0
0 1
| 4LRUUDLLLUUDDDUUUUU | -1 0 1 2 0 0 0 1 | 2 seconds | 512 megabytes | ['brute force', 'implementation', '*1600'] |
J. Road Reformtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n cities and m bidirectional roads in Berland. The i-th road connects the cities x_i and y_i, and has the speed limit s_i. The road network allows everyone to get from any city to any other city. The Berland Transport Ministry is planning a road reform.First of all, maintaining all m roads is too costly, so m - (n - 1) roads will be demolished in such a way that the remaining (n - 1) roads still allow to get to any city from any other city. Formally, the remaining roads should represent an undirected tree.Secondly, the speed limits on the remaining roads might be changed. The changes will be done sequentially, each change is either increasing the speed limit on some road by 1, or decreasing it by 1. Since changing the speed limit requires a lot of work, the Ministry wants to minimize the number of changes.The goal of the Ministry is to have a road network of (n - 1) roads with the maximum speed limit over all roads equal to exactly k. They assigned you the task of calculating the minimum number of speed limit changes they have to perform so the road network meets their requirements.For example, suppose the initial map of Berland looks like that, and k = 7: Then one of the optimal courses of action is to demolish the roads 1–4 and 3–4, and then decrease the speed limit on the road 2–3 by 1, so the resulting road network looks like that: InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains three integers n, m and k (2 \le n \le 2 \cdot 10^5; n - 1 \le m \le \min(2 \cdot 10^5, \frac{n(n-1)}{2}); 1 \le k \le 10^9) — the number of cities, the number of roads and the required maximum speed limit, respectively.Then m lines follow. The i-th line contains three integers x_i, y_i and s_i (1 \le x_i, y_i \le n; x_i \ne y_i; 1 \le s_i \le 10^9) — the cities connected by the i-th road and the speed limit on it, respectively. All roads are bidirectional.The road network in each test case is connected (that is, it is possible to reach any city from any other city by traveling along the road), and each pair of cities is connected by at most one road.The sum of n over all test cases does not exceed 2 \cdot 10^5. Similarly, the sum of m over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the minimum number of changes the Ministry has to perform so that the maximum speed limit among the remaining (n - 1) roads is exactly k.ExampleInput
44 5 74 1 31 2 52 3 82 4 13 4 44 6 51 2 11 3 11 4 22 4 14 3 13 2 13 2 101 2 81 3 105 5 151 2 173 1 152 3 101 4 142 5 8Output
1
3
0
0
NoteThe explanation for the example test:The first test case is described in the problem statement.In the second test case, the road network initially looks like that: The Ministry can demolish the roads 1–2, 3–2 and 3–4, and then increase the speed limit on the road 1–4 three times.In the third test case, the road network already meets all the requirements.In the fourth test case, it is enough to demolish the road 1–2 so the resulting road network meets the requirements. | 44 5 74 1 31 2 52 3 82 4 13 4 44 6 51 2 11 3 11 4 22 4 14 3 13 2 13 2 101 2 81 3 105 5 151 2 173 1 152 3 101 4 142 5 8 | 1 3 0 0 | 2 seconds | 512 megabytes | ['dsu', 'graphs', 'greedy', '*1800'] |
I. Plane Tilingtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given five integers n, dx_1, dy_1, dx_2 and dy_2. You have to select n distinct pairs of integers (x_i, y_i) in such a way that, for every possible pair of integers (x, y), there exists exactly one triple of integers (a, b, i) meeting the following constraints: \begin{cases} x \, = \, x_i + a \cdot dx_1 + b \cdot dx_2, \\ y \, = \, y_i + a \cdot dy_1 + b \cdot dy_2. \end{cases} InputThe first line contains a single integer n (1 \le n \le 10^5).The second line contains two integers dx_1 and dy_1 (-10^6 \le dx_1, dy_1 \le 10^6).The third line contains two integers dx_2 and dy_2 (-10^6 \le dx_2, dy_2 \le 10^6).OutputIf it is impossible to correctly select n pairs of integers, print NO.Otherwise, print YES in the first line, and then n lines, the i-th of which contains two integers x_i and y_i (-10^9 \le x_i, y_i \le 10^9).If there are multiple solutions, print any of them.ExamplesInput
4
2 0
0 2
Output
YES
0 0
0 1
1 0
1 1
Input
5
2 6
1 5
Output
NO
Input
2
3 4
1 2
Output
YES
0 0
0 1
| 4
2 0
0 2
| YES 0 0 0 1 1 0 1 1 | 1 second | 512 megabytes | ['geometry', 'implementation', 'math', '*2500'] |
H. K and Medianstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3.You have a sequence of n integers [1, 2, \dots, n] and an odd integer k.In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them).For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps?You'll be given t test cases. Solve each test case independently.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains three integers n, k, and m (3 \le n \le 2 \cdot 10^5; 3 \le k \le n; k is odd; 1 \le m < n) — the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get.The second line of each test case contains m integers b_1, b_2, \dots, b_m (1 \le b_1 < b_2 < \dots < b_m \le n) — the sequence you'd like to get, given in the ascending order.It's guaranteed that the total sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).ExampleInput
43 3 117 3 31 5 710 5 34 5 613 7 71 3 5 7 9 11 12Output
NO
YES
NO
YES
NoteIn the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements — it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b. | 43 3 117 3 31 5 710 5 34 5 613 7 71 3 5 7 9 11 12 | NO YES NO YES | 2 seconds | 512 megabytes | ['constructive algorithms', 'greedy', 'math', '*2200'] |
G. Hobbitstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe hobbits Frodo and Sam are carrying the One Ring to Mordor. In order not to be spotted by orcs, they decided to go through the mountains.The mountain relief can be represented as a polyline with n points (x_i, y_i), numbered from 1 to n (x_i < x_{i + 1} for 1 \le i \le n - 1). Hobbits start their journey at the point (x_1, y_1) and should reach the point (x_n, y_n) to complete their mission.The problem is that there is a tower with the Eye of Sauron, which watches them. The tower is located at the point (x_n, y_n) and has the height H, so the Eye is located at the point (x_n, y_n + H). In order to complete the mission successfully, the hobbits have to wear cloaks all the time when the Sauron Eye can see them, i. e. when there is a direct line from the Eye to the hobbits which is not intersected by the relief.The hobbits are low, so their height can be considered negligibly small, but still positive, so when a direct line from the Sauron Eye to the hobbits only touches the relief, the Eye can see them. The Sauron Eye can't see hobbits when they are in the left position, but can see them when they are in the right position. The hobbits do not like to wear cloaks, so they wear them only when they can be spotted by the Eye. Your task is to calculate the total distance the hobbits have to walk while wearing cloaks.InputThe first line of the input contains two integers n and H (2 \le n \le 2 \cdot 10^5; 1 \le H \le 10^4) — the number of vertices in polyline and the tower height.The next n lines contain two integers x_i, y_i each (0 \le x_i \le 4 \cdot 10^5; 0 \le y_i \le 10^4) — the coordinates of the polyline vertices. It is guaranteed that x_i < x_{i + 1} for 1 \le i \le n - 1.OutputPrint one real number — the total distance the hobbits have to walk while wearing cloaks. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6} — formally, if your answer is a, and the jury's answer is b, your answer will be accepted if \dfrac{|a - b|}{\max(1, b)} \le 10^{-6}.ExamplesInput
6 10
10 40
20 10
25 30
30 15
50 15
65 30
Output
70.4034587602
Input
9 5
0 0
5 10
15 10
20 0
25 11
30 0
35 10
50 10
60 5
Output
27.2787986124
Input
2 10000
0 10000
400000 0
Output
400124.9804748512
| 6 10
10 40
20 10
25 30
30 15
50 15
65 30
| 70.4034587602 | 1 second | 512 megabytes | ['binary search', 'geometry', '*2500'] |
F. Full Turntime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n persons located on a plane. The i-th person is located at the point (x_i, y_i) and initially looks at the point (u_i, v_i).At the same moment of time, all persons will start to rotate clockwise synchronously with the same angular speed. They will rotate until they do one full 360-degree turn. It is said that persons A and B made eye contact if person A looks in person B's direction at the same moment when person B looks in person A's direction. If there is a person C located between persons A and B, that will not obstruct A and B from making eye contact. A person can make eye contact with more than one person at the same time.Calculate the number of pairs of persons that will make eye contact at least once during the rotation (including the initial moment).InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the number of persons. The following n lines describe persons, each line containing four space-separated integers x_i, y_i, u_i, v_i (|x_i|, |y_i|, |u_i|, |v_i| \le 10^9; x_i \ne u_i or y_i \ne v_i), where (x_i, y_i) are the coordinates of the point where the i-th person is located and (u_i, v_i) are the coordinates of the point that the i-th person looks at initially. Each person's location is unique in each test case.The sum of n over all test cases does not exceed 10^5.OutputFor each test case, print one integer — the number of pairs of persons who will make eye contact at least once during the rotation, including the initial moment.ExampleInput
320 0 0 11 0 2 030 0 1 11 1 0 01 0 2 060 0 0 11 0 1 22 0 2 33 0 3 -54 0 4 -55 0 5 -5Output
0
1
9
| 320 0 0 11 0 2 030 0 1 11 1 0 01 0 2 060 0 0 11 0 1 22 0 2 33 0 3 -54 0 4 -55 0 5 -5 | 0 1 9 | 2 seconds | 512 megabytes | ['geometry', 'hashing', 'number theory', '*1700'] |
E. Four Segmentstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp wants to draw four line segments on a sheet of paper. He wants the i-th segment to have its length equal to a_i (1 \le i \le 4). These segments can intersect with each other, and each segment should be either horizontal or vertical.Monocarp wants to draw the segments in such a way that they enclose a rectangular space, and the area of that rectangular space should be maximum possible.For example, if Monocarp wants to draw four segments with lengths 1, 2, 3 and 4, he can do it the following way: Here, Monocarp has drawn segments AB (with length 1), CD (with length 2), BC (with length 3) and EF (with length 4). He got a rectangle ABCF with area equal to 3 that is enclosed by the segments. Calculate the maximum area of a rectangle Monocarp can enclose with four segments.InputThe first line contains one integer t (1 \le t \le 3 \cdot 10^4) — the number of test cases.Each test case consists of a single line containing four integers a_1, a_2, a_3, a_4 (1 \le a_i \le 10^4) — the lengths of the segments Monocarp wants to draw.OutputFor each test case, print one integer — the maximum area of a rectangle Monocarp can enclose with four segments (it can be shown that the answer is always an integer).ExampleInput
4
1 2 3 4
5 5 5 5
3 1 4 1
100 20 20 100
Output
3
25
3
2000
NoteThe first test case of the example is described in the statement.For the second test case, Monocarp can draw the segments AB, BC, CD and DA as follows: Here, Monocarp has drawn segments AB (with length 5), BC (with length 5), CD (with length 5) and DA (with length 5). He got a rectangle ABCD with area equal to 25 that is enclosed by the segments. | 4
1 2 3 4
5 5 5 5
3 1 4 1
100 20 20 100
| 3 25 3 2000 | 2 seconds | 512 megabytes | ['greedy', '*800'] |
D. Firecrackerstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider a long corridor which can be divided into n square cells of size 1 \times 1. These cells are numbered from 1 to n from left to right.There are two people in this corridor, a hooligan and a security guard. Initially, the hooligan is in the a-th cell, the guard is in the b-th cell (a \ne b). One of the possible situations. The corridor consists of 7 cells, the hooligan is in the 3-rd cell, the guard is in the 6-th (n = 7, a = 3, b = 6). There are m firecrackers in the hooligan's pocket, the i-th firecracker explodes in s_i seconds after being lit.The following events happen each second (sequentially, exactly in the following order): firstly, the hooligan either moves into an adjacent cell (from the cell i, he can move to the cell (i + 1) or to the cell (i - 1), and he cannot leave the corridor) or stays in the cell he is currently. If the hooligan doesn't move, he can light one of his firecrackers and drop it. The hooligan can't move into the cell where the guard is; secondly, some firecrackers that were already dropped may explode. Formally, if the firecracker j is dropped on the T-th second, then it will explode on the (T + s_j)-th second (for example, if a firecracker with s_j = 2 is dropped on the 4-th second, it explodes on the 6-th second); finally, the guard moves one cell closer to the hooligan. If the guard moves to the cell where the hooligan is, the hooligan is caught. Obviously, the hooligan will be caught sooner or later, since the corridor is finite. His goal is to see the maximum number of firecrackers explode before he is caught; that is, he will act in order to maximize the number of firecrackers that explodes before he is caught.Your task is to calculate the number of such firecrackers, if the hooligan acts optimally.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Each test case consists of two lines. The first line contains four integers n, m, a and b (2 \le n \le 10^9; 1 \le m \le 2 \cdot 10^5; 1 \le a, b \le n; a \ne b) — the size of the corridor, the number of firecrackers, the initial location of the hooligan and the initial location of the guard, respectively.The second line contains m integers s_1, s_2, ..., s_m (1 \le s_i \le 10^9), where s_i is the time it takes the i-th firecracker to explode after it is lit.It is guaranteed that the sum of m over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the maximum number of firecrackers that the hooligan can explode before he is caught.ExampleInput
37 2 3 61 47 2 3 65 17 2 3 64 4Output
2
1
1
NoteIn the first test case, the hooligan should act, for example, as follows: second 1: drop the second firecracker, so it will explode on the 5-th second. The guard moves to the cell 5; second 2: move to the cell 2. The guard moves to the cell 4; second 3: drop the first firecracker, so it will explode on the 4-th second. The guard moves to the cell 3; second 4: move to the cell 1. The first firecracker explodes. The guard moves to the cell 2; second 5: stay in the cell 1. The second firecracker explodes. The guard moves to the cell 1 and catches the hooligan. | 37 2 3 61 47 2 3 65 17 2 3 64 4 | 2 1 1 | 4 seconds | 512 megabytes | ['binary search', 'sortings', '*1700'] |
C. Berpizzatime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer. On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them). Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries: 1 m — a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m; 2 — Monocarp serves a customer which came to the pizzeria first; 3 — Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen). For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).InputThe first line contains one integer q (2 \le q \le 5 \cdot 10^5) — the number of queries.Then q lines follow, each describing a query in one of the following formats: 1 m (1 \le m \le 5 \cdot 10^5) — a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m; 2 — Monocarp serves a customer which came to the pizzeria first; 3 — Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen). Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.OutputFor each query of type 2 or 3, print one integer — the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.ExamplesInput
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4 Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3 Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3 | 8
1 8
1 10
1 6
3
2
1 9
2
3
| 2 1 3 4 | 5 seconds | 512 megabytes | ['data structures', 'implementation', '*1400'] |
B. Bakerytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp would like to open a bakery in his local area. But, at first, he should figure out whether he can compete with other shops.Monocarp plans that the bakery will work for n days. On the i-th day, a_i loaves of bread will be baked in the morning before the opening. At the end of the n-th day, Monocarp will sell all the remaining bread that wasn't sold earlier with a huge discount.Because of how bread is stored, the bakery seller sells the bread in the following order: firstly, he sells the loaves that were baked that morning; secondly, he sells the loaves that were baked the day before and weren't sold yet; then the loaves that were baked two days before and weren't sold yet, and so on. That's why some customers may buy a rather stale bread and will definitely spread negative rumors.Let's define loaf spoilage as the difference between the day it was baked and the day it was sold. Then the unattractiveness of the bakery will be equal to the maximum spoilage among all loaves of bread baked at the bakery.Suppose Monocarp's local area has consumer demand equal to k, it means that each day k customers will come to the bakery and each of them will ask for one loaf of bread (the loaves are sold according to the aforementioned order). If there is no bread left, then the person just doesn't buy anything. During the last day sale, all the remaining loaves will be sold (and they will still count in the calculation of the unattractiveness).Monocarp analyzed his competitors' data and came up with m possible consumer demand values k_1, k_2, \dots, k_m, and now he'd like to calculate the unattractiveness of the bakery for each value of demand. Can you help him?InputThe first line contains two integers n and m (1 \le n \le 2 \cdot 10^5; 1 \le m \le 2 \cdot 10^5) — the number of days the bakery is open and the number of possible values of consumer demand.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the number of bread loaves that will be baked each day.The third line contains m integers k_1, k_2, \dots, k_m (1 \le k_1 < k_2 < \dots < k_m \le 10^9) — the possible consumer demand values in the ascending order.OutputPrint m integers: for each consumer demand, print the unattractiveness of the bakery.ExamplesInput
5 4
5 2 1 3 7
1 3 4 10
Output
4 2 1 0
Input
8 9
3 1 4 1 5 9 2 6
1 2 3 4 5 6 7 8 9
Output
7 5 3 3 2 1 1 1 0
NoteIn the first example, let's describe what happens for couple consumer demands:If consumer demand is equal to 1: at day 1: 5 loaves are baked and only 1 is sold with spoilage equal to 1 - 1 = 0; at day 2: 4 loaves are left and 2 more are baked. Only 1 loaf was sold and it was the loaf baked today with spoilage 2 - 2 = 0; at day 3: 4 loaves from the first day and 1 loaf from the second day left. One more loaf was baked and was sold this day with spoilage 3 - 3 = 0; at day 4: 4 loaves from the first day and 1 loaf from the second day left. 3 more loaves were baked and one of them was sold this day with spoilage 4 - 4 = 0; at day 5: 4 loaves from the first day, 1 loaf from the second day and 2 loaves from the fourth day left. 7 more loaves were baked and, since it's the last day, all 14 loaves were sold. 4 loaves from the first day have the maximum spoilage equal to 5 - 1 = 4. In total, the unattractiveness of the bakery will be equal to 4.If consumer demand is equal to 10 then all baked bread will be sold in the day it was baked and will have spoilage equal to 0. | 5 4
5 2 1 3 7
1 3 4 10
| 4 2 1 0 | 2 seconds | 512 megabytes | ['data structures', 'dsu', '*2900'] |
A. LaIStime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's call a sequence b_1, b_2, b_3 \dots, b_{k - 1}, b_k almost increasing if \min(b_1, b_2) \le \min(b_2, b_3) \le \dots \le \min(b_{k - 1}, b_k). In particular, any sequence with no more than two elements is almost increasing.You are given a sequence of integers a_1, a_2, \dots, a_n. Calculate the length of its longest almost increasing subsequence.You'll be given t test cases. Solve each test case independently.Reminder: a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of independent test cases.The first line of each test case contains a single integer n (2 \le n \le 5 \cdot 10^5) — the length of the sequence a.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — the sequence itself.It's guaranteed that the total sum of n over all test cases doesn't exceed 5 \cdot 10^5.OutputFor each test case, print one integer — the length of the longest almost increasing subsequence.ExampleInput
381 2 7 3 2 1 2 322 174 1 5 2 6 3 7Output
6
2
7
NoteIn the first test case, one of the optimal answers is subsequence 1, 2, 7, 2, 2, 3.In the second and third test cases, the whole sequence a is already almost increasing. | 381 2 7 3 2 1 2 322 174 1 5 2 6 3 7 | 6 2 7 | 3 seconds | 512 megabytes | ['data structures', 'dp', 'greedy', '*2200'] |
E. Distinctive Roots in a Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree with n vertices. Each vertex i has a value a_i associated with it.Let us root the tree at some vertex v. The vertex v is called a distinctive root if the following holds: in all paths that start at v and end at some other node, all the values encountered are distinct. Two different paths may have values in common but a single path must have all distinct values.Find the number of distinctive roots in the tree.InputThe first line of the input contains a single integer n (1 \le n \le 2\cdot10^5) — the number of vertices in the tree.The next line contains n space-separated integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).The following n-1 lines each contain two space-separated integers u and v (1 \le u, v \le n), denoting an edge from u to v.It is guaranteed that the edges form a tree.OutputPrint a single integer — the number of distinctive roots in the tree.ExamplesInput
5
2 5 1 1 4
1 2
1 3
2 4
2 5
Output
3Input
5
2 1 1 1 4
1 2
1 3
2 4
2 5
Output
0NoteIn the first example, 1, 2 and 5 are distinctive roots. | 5
2 5 1 1 4
1 2
1 3
2 4
2 5
| 3 | 3 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'dp', 'trees', '*2500'] |
D. Sum of Pathstime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThere are n cells, numbered 1,2,\dots, n from left to right. You have to place a robot at any cell initially. The robot must make exactly k moves.In one move, the robot must move one cell to the left or right, provided that it doesn't move out of bounds. In other words, if the robot was in the cell i, it must move to either the cell i-1 or the cell i+1, as long as it lies between 1 and n (endpoints inclusive). The cells, in the order they are visited (including the cell the robot is placed), together make a good path.Each cell i has a value a_i associated with it. Let c_0, c_1, \dots, c_k be the sequence of cells in a good path in the order they are visited (c_0 is the cell robot is initially placed, c_1 is the cell where the robot is after its first move, and so on; more formally, c_i is the cell that the robot is at after i moves). Then the value of the path is calculated as a_{c_0} + a_{c_1} + \dots + a_{c_k}.Your task is to calculate the sum of values over all possible good paths. Since this number can be very large, output it modulo 10^9 + 7. Two good paths are considered different if the starting cell differs or there exists an integer i \in [1, k] such that the current cell of the robot after exactly i moves is different in those paths.You must process q updates to a and print the updated sum each time. Each update changes the value of exactly one cell. See the input format and the sample input-output for more details.InputThe first line of the input contains three space-separated integers n, k and q (2 \le n \le 5000; 1 \le k \le 5000; 1 \le q \le 2 \cdot 10^5).The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).q lines follow. Each line contains two space-separated integers i and x (1 \le i \le n; 1 \le x \le 10^9) indicating that you must change the value of a_i to x.OutputPrint q integers. The i-th integer should be the sum of values over all good paths after the first i updates are performed. Since the answers may be large, print them modulo 10^9 + 7.ExamplesInput
5 1 5
3 5 1 4 2
1 9
2 4
3 6
4 6
5 2
Output
62
58
78
86
86
Input
5 2 5
3 5 1 4 2
1 9
2 4
3 6
4 6
5 2
Output
157
147
207
227
227
Input
4 40 6
92 21 82 46
3 56
1 72
4 28
1 97
2 49
2 88
Output
239185261
666314041
50729936
516818968
766409450
756910476
NoteIn the first example, the good paths are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), (4, 3), (4, 5), (5, 4).Initially the values of a are [3, 5, 1, 4, 2]. After the first update, they become [9, 5, 1, 4, 2]. After the second update, they become [9, 4, 1, 4, 2], and so on. | 5 1 5
3 5 1 4 2
1 9
2 4
3 6
4 6
5 2
| 62 58 78 86 86 | 3 seconds | 1024 megabytes | ['combinatorics', 'dp', 'math', '*2200'] |
C. Three Bagstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three bags. Each bag contains a non-empty multiset of numbers. You can perform a number of operations on these bags. In one operation, you can choose any two non-empty bags, and choose one number from each of the bags. Let's say that you choose number a from the first bag and number b from the second bag. Then, you remove b from the second bag and replace a with a-b in the first bag. Note that if there are multiple occurrences of these numbers, then you shall only remove/replace exactly one occurrence.You have to perform these operations in such a way that you have exactly one number remaining in exactly one of the bags (the other two bags being empty). It can be shown that you can always apply these operations to receive such a configuration in the end. Among all these configurations, find the one which has the maximum number left in the end.InputThe first line of the input contains three space-separated integers n_1, n_2 and n_3 (1 \le n_1, n_2, n_3 \le 3\cdot10^5, 1 \le n_1+n_2+n_3 \le 3\cdot10^5) — the number of numbers in the three bags.The i-th of the next three lines contain n_i space-separated integers a_{{i,1}}, a_{{i,2}}, ..., a_{{i,{{n_i}}}} (1 \le a_{{i,j}} \le 10^9) — the numbers in the i-th bag.OutputPrint a single integer — the maximum number which you can achieve in the end.ExamplesInput
2 4 1
1 2
6 3 4 5
5
Output
20Input
3 2 2
7 5 4
2 9
7 1
Output
29NoteIn the first example input, let us perform the following operations:[1, 2], [6, 3, 4, 5], [5][-5, 2], [3, 4, 5], [5] (Applying an operation to (1, 6))[-10, 2], [3, 4], [5] (Applying an operation to (-5, 5))[2], [3, 4], [15] (Applying an operation to (5, -10))[-1], [4], [15] (Applying an operation to (2, 3))[-5], [], [15] (Applying an operation to (-1, 4))[], [], [20] (Applying an operation to (15, -5))You can verify that you cannot achieve a bigger number. Hence, the answer is 20. | 2 4 1
1 2
6 3 4 5
5
| 20 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*1900'] |
B. Hills And Valleystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of n integers a_1, a_2, ..., a_n. Let us call an index j (2 \le j \le {{n-1}}) a hill if a_j > a_{{j+1}} and a_j > a_{{j-1}}; and let us call it a valley if a_j < a_{{j+1}} and a_j < a_{{j-1}}.Let us define the intimidation value of a sequence as the sum of the number of hills and the number of valleys in the sequence. You can change exactly one integer in the sequence to any number that you want, or let the sequence remain unchanged. What is the minimum intimidation value that you can achieve?InputThe first line of the input contains a single integer t (1 \le t \le 10000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 3\cdot10^5).The second line of each test case contains n space-separated integers a_1, a_2, ..., a_n (1 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 3\cdot10^5.OutputFor each test case, print a single integer — the minimum intimidation value that you can achieve.ExampleInput
4
3
1 5 3
5
2 2 2 2 2
6
1 6 2 5 2 10
5
1 6 2 5 1
Output
0
0
1
0
NoteIn the first test case, changing a_2 to 2 results in no hills and no valleys.In the second test case, the best answer is just to leave the array as it is.In the third test case, changing a_3 to 6 results in only one valley (at the index 5).In the fourth test case, changing a_3 to 6 results in no hills and no valleys. | 4
3
1 5 3
5
2 2 2 2 2
6
1 6 2 5 2 10
5
1 6 2 5 1
| 0 0 1 0 | 1 second | 256 megabytes | ['brute force', 'implementation', '*1700'] |
A. Wizard of Orztime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n digital panels placed in a straight line. Each panel can show any digit from 0 to 9. Initially, all panels show 0.Every second, the digit shown by each panel increases by 1. In other words, at the end of every second, a panel that showed 9 would now show 0, a panel that showed 0 would now show 1, a panel that showed 1 would now show 2, and so on.When a panel is paused, the digit displayed on the panel does not change in the subsequent seconds.You must pause exactly one of these panels, at any second you wish. Then, the panels adjacent to it get paused one second later, the panels adjacent to those get paused 2 seconds later, and so on. In other words, if you pause panel x, panel y (for all valid y) would be paused exactly |x−y| seconds later.For example, suppose there are 4 panels, and the 3-rd panel is paused when the digit 9 is on it. The panel 1 pauses 2 seconds later, so it has the digit 1; the panel 2 pauses 1 second later, so it has the digit 0; the panel 4 pauses 1 second later, so it has the digit 0. The resulting 4-digit number is 1090. Note that this example is not optimal for n = 4.Once all panels have been paused, you write the digits displayed on them from left to right, to form an n digit number (it can consist of leading zeros). What is the largest possible number you can get? Initially, all panels show 0.InputThe first line of the input contains a single integer t (1 \le t \le 100) — the number of test cases. Each test case consists of a single line containing a single integer n (1 \le n \le 2\cdot10^5).It is guaranteed that the sum of n over all test cases does not exceed 2\cdot10^5.OutputFor each test case, print the largest number you can achieve, if you pause one panel optimally.ExampleInput
2
1
2
Output
9
98
NoteIn the first test case, it is optimal to pause the first panel when the number 9 is displayed on it.In the second test case, it is optimal to pause the second panel when the number 8 is displayed on it. | 2
1
2
| 9 98 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*900'] |
I. The Riddle of the Sphinxtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhat walks on four feet in the morning, two in the afternoon, and three at night?This is an interactive problem. This problem doesn't support hacks.Sphinx's duty is to guard the city of Thebes by making sure that no unworthy traveler crosses its gates. Only the ones who answer her riddle timely and correctly (or get an acc for short) are allowed to pass. As of those who fail, no one heard of them ever again...So you don't have a choice but to solve the riddle. Sphinx has an array a_1, a_2, \ldots, a_n of nonnegative integers strictly smaller than 2^b and asked you to find the maximum value among its elements. Of course, she will not show you the array, but she will give you n and b. As it is impossible to answer this riddle blindly, you can ask her some questions. For given i, y, she'll answer you whether a_i is bigger than y. As sphinxes are not very patient, you can ask at most 3 \cdot (n + b) such questions.Although cunning, sphinxes are honest. Even though the array can change between your queries, answers to the previously asked questions will remain valid.InputThe first line contains two integers n and b (1 \leq n, b \leq 200). The remaining parts of the input will be given throughout the interaction process.InteractionIn each round your program must output a single line with an integer i (0 \leq i \leq n) and a binary string of length exactly b denoting the binary representation of y (most significant bit first).If i > 0, this line encodes the question: Is a_i bigger than y?. There should be at most 3 \cdot (n+b) such lines; after each of them, the interactor will print yes or no in a single line.If i = 0, this is the last round of interaction, after which your program should terminate, and y should be the maximal value among the elements of Sphinx's array. Note that this round does not count to the query limit.Note that the interactor is adaptive.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.If your solution does not correctly follow the interaction guideline above, it may receive an arbitrary verdict. Otherwise, your program will receive the Wrong Answer judgment if it reports the wrong maximum.ExamplesInput
5 3
yes
no
no
no
no
yes
Output
5 101
5 110
4 100
3 101
2 001
1 000
0 110
Input
4 3
no
no
no
no
Output
1 000
2 000
3 000
4 000
0 000
Input
1 1
Output
0 0
NoteIn all examples, the sequence is fixed beforehand.In the first example, the sequence is 2, 1, 4, 0, 6.In the second example, the sequence is 0, 0, 0, 0.In the third example, the sequence is 0.Note that if the interactor was adaptive, then the interaction in the first and the third example would not be sufficient to return the correct value of maximum. | 5 3
yes
no
no
no
no
yes
| 5 101 5 110 4 100 3 101 2 001 1 000 0 110 | 1 second | 256 megabytes | ['binary search', 'data structures', 'data structures', 'interactive', '*3400'] |
H. Finding satisfactory solutionstime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputGetting so far in this contest is not an easy feat. By solving all the previous problems, you have impressed the gods greatly. Thus, they decided to spare you the story for this problem and grant a formal statement instead.Consider n agents. Each one of them initially has exactly one item, i-th agent has the item number i. We are interested in reassignments of these items among the agents. An assignment is valid iff each item is assigned to exactly one agent, and each agent is assigned exactly one item.Each agent has a preference over the items, which can be described by a permutation p of items sorted from the most to the least desirable. In other words, the agent prefers item i to item j iff i appears earlier in the permutation p. A preference profile is a list of n permutations of length n each, such that i-th permutation describes preferences of the i-th agent.It is possible that some of the agents are not happy with the assignment of items. A set of dissatisfied agents may choose not to cooperate with other agents. In such a case, they would exchange the items they possess initially (i-th item belongs to i-th agent) only between themselves. Agents from this group don't care about the satisfaction of agents outside of it. However, they need to exchange their items in such a way that will make at least one of them happier, and none of them less happy (in comparison to the given assignment).Formally, consider a valid assignment of items — A. Let A(i) denote the item assigned to i-th agent. Also, consider a subset of agents. Let S be the set of their indices. We will say this subset of agents is dissatisfied iff there exists a valid assignment B(i) such that: For each i \in S, B(i) \in S. No agent i \in S prefers A(i) to B(i) (no agent from the S is less happy). At least one agent i \in S prefers B(i) to A(i) (at least one agent from the S is happier). An assignment is optimal if no subset of the agents is dissatisfied. Note that the empty subset cannot be dissatisfied. It can be proven that for each preference profile, there is precisely one optimal assignment.Example: Consider 3 agents with the following preference profile: [2, 1, 3] [1, 2, 3] [1, 3, 2] And such an assignment: First agent gets item 2 Second agent gets item 3. Third agent gets item 1. See that the set of agents \{1, 2\} is dissatisfied, because they can reassign their (initial) items in the following way: First agent gets item 2. Second agent gets item 1. Third agent gets item 3. This reassignment will make the second agent happier and make no difference to the first agent. As a result, the third agent got an item that is worse for him, but this does not prevent the set \{1,2\} from being dissatisfied (he is not in this set).The following assignment would be optimal: First agent gets item 2. Second agent gets item 1. Third agent gets item 3. Given an assignment A, calculate the number of distinct preference profiles for which assignment A is optimal. As the answer can be huge, output it modulo 10^9+7.Two preference profiles are different iff they assign different preference permutations to any agent.InputIn the first line of input there is an integer n (1 \leq n \leq 40). The next line contains n space separated integers, a permutation of numbers from 1 to n. The i-th number denotes the item assigned to agent i in the optimal assignment.OutputIn a single line output one non-negative integer, the number of preference profiles for which the assignment of items given in the input is optimal modulo 10^9+7.ExamplesInput
2
2 1
Output
1
Input
3
1 2 3
Output
98
Input
4
2 1 3 4
Output
27408
NoteAssignment from the first test case is optimal only for the following preference profile:2, 11, 2If any agent wants his initial item the most and is given another item, he would form a dissatisfied set. Hence the allocation is not optimal for any other preference profile. | 2
2 1
| 1 | 5 seconds | 1024 megabytes | ['combinatorics', 'dp', 'graphs', 'greedy', 'math', '*3300'] |
G. Song of the Sirenstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output Whoso in ignorance draws near to them and hears the Sirens' voice, he nevermore returns.Homer, OdysseyIn the times of Jason and the Argonauts, it was well known that sirens use the sound of their songs to lure sailors into their demise. Yet only a few knew that every time sirens call a sailor by his name, his will weakens, making him more vulnerable. For the purpose of this problem, both siren songs and names of the sailors will be represented as strings of lowercase English letters. The more times the sailor's name occurs as a contiguous substring of the song, the greater danger he is in.Jason found out that sirens can sing one of the n+1 songs, which have the following structure: let s_i (0 \leq i \leq n) be the i-th song and t be a string of length n, then for every i < n: s_{i+1} = s_i t_i s_i. In other words i+1-st song is the concatenation of i-th song, i-th letter (0-indexed) of t and the i-th song. Fortunately, he also knows s_0 and t. Jason wonders how many times a sailor's name is mentioned in a particular song. Answer q queries: given the sailor's name (w) and the index of a song (i) output the number of occurrences of w in s_i as a substring. As this number can be quite large, output its remainder modulo 10^9+7.InputIn the first line of input there are two integers n, q ( 1 \leq n, q \leq 10^5) meaning that there are n+1 songs and q queries. In the next two lines strings s_0 and t follow (1 \leq |s_0| \leq 100, |t| = n). Next q lines describe the queries; each one contains an integer k ( 0 \leq k \leq n), the index of the song sung by the sirens, and a non-empty string w, which is the name of a sailor. All strings in this problem consist only of lowercase English letters, and the sum of lengths of sailors' names does not exceed 10^6.OutputOutput q lines, i-th of them should contain the remainder modulo 10^9+7 of the number of occurrences of w in s_k.ExamplesInput
3 3
aa
bcd
2 aba
3 ca
3 aa
Output
2
2
8
Input
4 5
aba
bbac
1 a
3 baca
3 ab
2 bab
4 aba
Output
4
0
14
6
28
NoteIn the first example songs of the sirens are as follows: Song 0: aa Song 1: aabaa Song 2: aabaacaabaa Song 3: aabaacaabaadaabaacaabaa | 3 3
aa
bcd
2 aba
3 ca
3 aa
| 2 2 8 | 2 seconds | 256 megabytes | ['combinatorics', 'divide and conquer', 'hashing', 'math', 'string suffix structures', 'strings', '*2600'] |
F. Euclid's nightmaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare. In his bad dream Euclid has a set S of n m-dimensional vectors over the \mathbb{Z}_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) \bmod 2. Euclid can sum any subset of S and archive another m-dimensional vector over \mathbb{Z}_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1. Help Euclid and calculate |T|, the number of m-dimensional vectors over \mathbb{Z}_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input. Consider sets A and B such that |A| = |B|. Let a_1, a_2, \dots a_{|A|} and b_1, b_2, \dots b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.InputIn the first line of input, there are two integers n, m (1 \leq n, m \leq 5 \cdot 10^5) denoting the number of vectors in S and the number of dimensions. Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 \leq k \leq 2) and then follow k distinct integers x_1, \dots x_k (1 \leq x_i \leq m). This encodes an m-dimensional vector having 1s on coordinates x_1, \dots x_k and 0s on the rest of them.Among the n vectors, no two are the same.OutputIn the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.ExamplesInput
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
NoteIn the first example we are given three vectors: 10 01 11 It turns out that we can represent all vectors from our 2-dimensional space using these vectors: 00 is a sum of the empty subset of above vectors; 01 = 11 + 10, is a sum of the first and third vector; 10 = 10, is just the first vector; 11 = 10 + 01, is a sum of the first and the second vector. Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below: 00 is a sum of the empty subset; 01 = 01 is just the second vector; 10 = 10 is just the first vector; 11 = 10 + 01 is a sum of the first and the second vector. | 3 2
1 1
1 2
2 2 1
| 4 2 1 2 | 2 seconds | 256 megabytes | ['bitmasks', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'math', 'sortings', '*2100'] |
E. Apollo versus Pantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnly a few know that Pan and Apollo weren't only battling for the title of the GOAT musician. A few millenniums later, they also challenged each other in math (or rather in fast calculations). The task they got to solve is the following:Let x_1, x_2, \ldots, x_n be the sequence of n non-negative integers. Find this value: \sum_{i=1}^n \sum_{j=1}^n \sum_{k=1}^n (x_i \, \& \, x_j) \cdot (x_j \, | \, x_k)Here \& denotes the bitwise and, and | denotes the bitwise or.Pan and Apollo could solve this in a few seconds. Can you do it too? For convenience, find the answer modulo 10^9 + 7.InputThe first line of the input contains a single integer t (1 \leq t \leq 1\,000) denoting the number of test cases, then t test cases follow.The first line of each test case consists of a single integer n (1 \leq n \leq 5 \cdot 10^5), the length of the sequence. The second one contains n non-negative integers x_1, x_2, \ldots, x_n (0 \leq x_i < 2^{60}), elements of the sequence.The sum of n over all test cases will not exceed 5 \cdot 10^5.OutputPrint t lines. The i-th line should contain the answer to the i-th text case.ExampleInput
8
2
1 7
3
1 2 4
4
5 5 5 5
5
6 2 2 1 0
1
0
1
1
6
1 12 123 1234 12345 123456
5
536870912 536870911 1152921504606846975 1152921504606846974 1152921504606846973
Output
128
91
1600
505
0
1
502811676
264880351
| 8
2
1 7
3
1 2 4
4
5 5 5 5
5
6 2 2 1 0
1
0
1
1
6
1 12 123 1234 12345 123456
5
536870912 536870911 1152921504606846975 1152921504606846974 1152921504606846973
| 128 91 1600 505 0 1 502811676 264880351 | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', 'math', '*1800'] |
D. 13th Labour of Heraclestime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've probably heard about the twelve labors of Heracles, but do you have any idea about the thirteenth? It is commonly assumed it took him a dozen years to complete the twelve feats, so on average, a year to accomplish every one of them. As time flows faster these days, you have minutes rather than months to solve this task. But will you manage?In this problem, you are given a tree with n weighted vertices. A tree is a connected graph with n - 1 edges.Let us define its k-coloring as an assignment of k colors to the edges so that each edge has exactly one color assigned to it. Note that you don't have to use all k colors.A subgraph of color x consists of these edges from the original tree, which are assigned color x, and only those vertices that are adjacent to at least one such edge. So there are no vertices of degree 0 in such a subgraph.The value of a connected component is the sum of weights of its vertices. Let us define the value of a subgraph as a maximum of values of its connected components. We will assume that the value of an empty subgraph equals 0.There is also a value of a k-coloring, which equals the sum of values of subgraphs of all k colors. Given a tree, for each k from 1 to n - 1 calculate the maximal value of a k-coloring.InputIn the first line of input, there is a single integer t (1 \leq t \leq 10^5) denoting the number of test cases. Then t test cases follow. First line of each test case contains a single integer n (2 \leq n \leq 10^5). The second line consists of n integers w_1, w_2, \dots, w_n (0 \leq w_i \leq 10^9), w_i equals the weight of i-th vertex. In each of the following n - 1 lines, there are two integers u, v (1 \leq u,v \leq n) describing an edge between vertices u and v. It is guaranteed that these edges form a tree. The sum of n in all test cases will not exceed 2 \cdot 10^5.OutputFor every test case, your program should print one line containing n - 1 integers separated with a single space. The i-th number in a line should be the maximal value of a i-coloring of the tree.ExampleInput
4
4
3 5 4 6
2 1
3 1
4 3
2
21 32
2 1
6
20 13 17 13 13 11
2 1
3 1
4 1
5 1
6 1
4
10 6 6 6
1 2
2 3
4 1
Output
18 22 25
53
87 107 127 147 167
28 38 44
NoteThe optimal k-colorings from the first test case are the following: In the 1-coloring all edges are given the same color. The subgraph of color 1 contains all the edges and vertices from the original graph. Hence, its value equals 3 + 5 + 4 + 6 = 18. In an optimal 2-coloring edges (2, 1) and (3,1) are assigned color 1. Edge (4, 3) is of color 2. Hence the subgraph of color 1 consists of a single connected component (vertices 1, 2, 3) and its value equals 3 + 5 + 4 = 12. The subgraph of color 2 contains two vertices and one edge. Its value equals 4 + 6 = 10. In an optimal 3-coloring all edges are assigned distinct colors. Hence subgraphs of each color consist of a single edge. They values are as follows: 3 + 4 = 7, 4 + 6 = 10, 3 + 5 = 8. | 4
4
3 5 4 6
2 1
3 1
4 3
2
21 32
2 1
6
20 13 17 13 13 11
2 1
3 1
4 1
5 1
6 1
4
10 6 6 6
1 2
2 3
4 1
| 18 22 25 53 87 107 127 147 167 28 38 44 | 2.5 seconds | 256 megabytes | ['data structures', 'greedy', 'sortings', 'trees', '*1500'] |
C. Canine poetrytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter his wife's tragic death, Eurydice, Orpheus descended to the realm of death to see her. Reaching its gates was uneasy, but passing through them proved to be even more challenging. Mostly because of Cerberus, the three-headed hound of Hades. Orpheus, a famous poet, and musician plans to calm Cerberus with his poetry and safely walk past him. He created a very peculiar poem for Cerberus. It consists only of lowercase English letters. We call a poem's substring a palindrome if and only if it reads the same backwards and forwards. A string a is a substring of a string b if a can be obtained from b by deleting several (possibly zero or all) characters from the beginning and several (possibly zero or all) characters from the end.Unfortunately, Cerberus dislikes palindromes of length greater than 1. For example in the poem abaa the hound of Hades wouldn't like substrings aba and aa.Orpheus can only calm Cerberus if the hound likes his poetry. That's why he wants to change his poem so that it does not contain any palindrome substrings of length greater than 1.Orpheus can modify the poem by replacing a letter at any position with any lowercase English letter. He can use this operation arbitrarily many times (possibly zero). Since there can be many palindromes in his poem, he may have to make some corrections. But how many, exactly? Given the poem, determine the minimal number of letters that have to be changed so that the poem does not contain any palindromes of length greater than 1.InputThe first line of the input contains a single integer t (1 \leq t \leq 10^5) denoting the number of test cases, then t test cases follow.The first and only line of each test case contains a non-empty string of lowercase English letters, Orpheus' poem.The sum of the length of Orpheus' poems in all test cases will not exceed 10^5.OutputYou should output t lines, i-th line should contain a single integer, answer to the i-th test case.ExampleInput
7
babba
abaac
codeforces
zeroorez
abcdcba
bbbbbbb
a
Output
1
1
0
1
1
4
0
NoteIn the first test case, we can replace the third character with c and obtain a palindrome-less poem bacba.In the second test case, we can replace the third character with d and obtain a palindrome-less poem abdac.In the third test case, the initial poem already doesn't contain any palindromes, so Orpheus doesn't need to change anything there. | 7
babba
abaac
codeforces
zeroorez
abcdcba
bbbbbbb
a
| 1 1 0 1 1 4 0 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'strings', '*1300'] |
B. Last minute enhancementstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAthenaeus has just finished creating his latest musical composition and will present it tomorrow to the people of Athens. Unfortunately, the melody is rather dull and highly likely won't be met with a warm reception. His song consists of n notes, which we will treat as positive integers. The diversity of a song is the number of different notes it contains. As a patron of music, Euterpe watches over composers and guides them throughout the process of creating new melodies. She decided to help Athenaeus by changing his song to make it more diverse.Being a minor goddess, she cannot arbitrarily change the song. Instead, for each of the n notes in the song, she can either leave it as it is or increase it by 1.Given the song as a sequence of integers describing the notes, find out the maximal, achievable diversity.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 10\,000) — the number of test cases. Then t test cases follow, each one is described in two lines.In the first line of each test case there is a single integer n (1 \leq n \leq 10^5) denoting the length of the song. The next line contains a sequence of n integers x_1, x_2, \ldots, x_n (1 \leq x_1 \leq x_2 \leq \ldots \leq x_n \leq 2 \cdot n), describing the song.The sum of n over all test cases does not exceed 10^5.OutputFor each test case, you should output a single line containing precisely one integer, the maximal diversity of the song, i.e. the maximal possible number of different elements in the final sequence.ExampleInput
5
6
1 2 2 2 5 6
2
4 4
6
1 1 3 4 4 5
1
1
6
1 1 1 2 2 2
Output
5
2
6
1
3
NoteIn the first test case, Euterpe can increase the second, fifth and sixth element to obtain the sequence 1, \underline{3}, 2, 2, \underline{6}, \underline{7}, which has 5 different elements (increased elements are underlined).In the second test case, Euterpe can increase the first element to obtain the sequence \underline{5}, 4, which has 2 different elements.In the third test case, Euterpe can increase the second, fifth and sixth element to obtain the sequence 1, \underline{2}, 3, 4, \underline{5}, \underline{6}, which has 6 different elements. | 5
6
1 2 2 2 5 6
2
4 4
6
1 1 3 4 4 5
1
1
6
1 1 1 2 2 2
| 5 2 6 1 3 | 1 second | 256 megabytes | ['dp', 'greedy', '*800'] |
A. Bovine Dilemmatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArgus was charged with guarding Io, which is not an ordinary cow. Io is quite an explorer, and she wanders off rather frequently, making Argus' life stressful. So the cowherd decided to construct an enclosed pasture for Io.There are n trees growing along the river, where Argus tends Io. For this problem, the river can be viewed as the OX axis of the Cartesian coordinate system, and the n trees as points with the y-coordinate equal 0. There is also another tree growing in the point (0, 1). Argus will tie a rope around three of the trees, creating a triangular pasture. Its exact shape doesn't matter to Io, but its area is crucial to her. There may be many ways for Argus to arrange the fence, but only the ones which result in different areas of the pasture are interesting for Io. Calculate the number of different areas that her pasture may have. Note that the pasture must have nonzero area.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 100) — the number of test cases. Then t test cases follow, each one is described in two lines.In the first line of each test case there is a single integer n (1 \leq n \leq 50) denoting the number of trees growing along the river. Next line contains n distinct integers x_1 < x_2 < \ldots < x_{n - 1} < x_n (1 \leq x_i \leq 50), the x-coordinates of trees growing along the river.OutputIn a single line output an integer, the number of different nonzero areas that triangles with trees as vertices may have.ExampleInput
8
4
1 2 4 5
3
1 3 5
3
2 6 8
2
1 2
1
50
5
3 4 5 6 8
3
1 25 26
6
1 2 4 8 16 32
Output
4
2
3
1
0
5
3
15
NoteIn the first test case, we have 6 non-degenerate triangles with the following areas: 0.5, 0.5, 1, 1.5, 1.5 and 2. The pasture can have 4 different areas, and thus 4 is the answer.In the second test case, we have 3 non-degenerate triangles with the following areas: 1, 1 and 2. The pasture can have 2 different areas, so 2 is the answer.The following two drawings present the situation in the second test case. The blue triangles in the first drawing have area 1. The red triangle in the second drawing has area 2. | 8
4
1 2 4 5
3
1 3 5
3
2 6 8
2
1 2
1
50
5
3 4 5 6 8
3
1 25 26
6
1 2 4 8 16 32
| 4 2 3 1 0 5 3 15 | 1 second | 256 megabytes | ['brute force', 'geometry', 'math', '*800'] |
F. My Beautiful Madnesstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree. We will consider simple paths on it. Let's denote path between vertices a and b as (a, b). Let d-neighborhood of a path be a set of vertices of the tree located at a distance \leq d from at least one vertex of the path (for example, 0-neighborhood of a path is a path itself). Let P be a multiset of the tree paths. Initially, it is empty. You are asked to maintain the following queries: 1 u v — add path (u, v) into P (1 \leq u, v \leq n). 2 u v — delete path (u, v) from P (1 \leq u, v \leq n). Notice that (u, v) equals to (v, u). For example, if P = \{(1, 2), (1, 2)\}, than after query 2 2 1, P = \{(1, 2)\}. 3 d — if intersection of all d-neighborhoods of paths from P is not empty output "Yes", otherwise output "No" (0 \leq d \leq n - 1). InputThe first line contains two integers n and q — the number of vertices in the tree and the number of queries, accordingly (1 \leq n \leq 2 \cdot 10^5, 2 \leq q \leq 2 \cdot 10^5).Each of the following n - 1 lines contains two integers x_i and y_i — indices of vertices connected by i-th edge (1 \le x_i, y_i \le n).The following q lines contain queries in the format described in the statement.It's guaranteed that: for a query 2 u v, path (u, v) (or (v, u)) is present in P, for a query 3 d, P \neq \varnothing, there is at least one query of the third type. OutputFor each query of the third type output answer on a new line.ExamplesInput
1 4
1 1 1
1 1 1
2 1 1
3 0
Output
Yes
Input
5 3
1 2
1 3
3 4
4 5
1 1 2
1 5 5
3 1
Output
No
Input
10 6
1 2
2 3
3 4
4 7
7 10
2 5
5 6
6 8
8 9
1 9 9
1 9 8
1 8 5
3 0
3 1
3 2
Output
No
Yes
Yes
| 1 4
1 1 1
1 1 1
2 1 1
3 0
| Yes | 2 seconds | 512 megabytes | ['data structures', 'trees', '*3500'] |
F. Max Correct Settime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call the set of positive integers S correct if the following two conditions are met: S \subseteq \{1, 2, \dots, n\}; if a \in S and b \in S, then |a-b| \neq x and |a-b| \neq y. For the given values n, x, and y, you have to find the maximum size of the correct set.InputA single line contains three integers n, x and y (1 \le n \le 10^9; 1 \le x, y \le 22). OutputPrint one integer — the maximum size of the correct set.ExamplesInput
10 2 5
Output
5
Input
21 4 6
Output
9
Input
1337 7 7
Output
672
Input
455678451 22 17
Output
221997195
| 10 2 5
| 5 | 4 seconds | 256 megabytes | ['bitmasks', 'dp', 'math', '*3100'] |
E. Plan of Lecturestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIvan is a programming teacher. During the academic year, he plans to give n lectures on n different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the 1-st, 2-nd, ..., n-th lecture — formally, he wants to choose some permutation of integers from 1 to n (let's call this permutation q). q_i is the index of the topic Ivan will explain during the i-th lecture.For each topic (except exactly one), there exists a prerequisite topic (for the topic i, the prerequisite topic is p_i). Ivan cannot give a lecture on a topic before giving a lecture on its prerequisite topic. There exists at least one valid ordering of topics according to these prerequisite constraints.Ordering the topics correctly can help students understand the lectures better. Ivan has k special pairs of topics (x_i, y_i) such that he knows that the students will understand the y_i-th topic better if the lecture on it is conducted right after the lecture on the x_i-th topic. Ivan wants to satisfy the constraints on every such pair, that is, for every i \in [1, k], there should exist some j \in [1, n - 1] such that q_j = x_i and q_{j + 1} = y_i.Now Ivan wants to know if there exists an ordering of topics that satisfies all these constraints, and if at least one exists, find any of them. InputThe first line contains two integers n and k (2 \le n \le 3 \cdot 10^5, 1 \le k \le n - 1) — the number of topics and the number of special pairs of topics, respectively.The second line contains n integers p_1, p_2, ..., p_n (0 \le p_i \le n), where p_i is the prerequisite topic for the topic i (or p_i = 0 if the i-th topic has no prerequisite topics). Exactly one of these integers is 0. At least one ordering of topics such that for every i the p_i-th topic is placed before the i-th topic exists.Then k lines follow, the i-th line contains two integers x_i and y_i (1 \le x_i, y_i \le n; x_i \ne y_i) — the topics from the i-th special pair. All values of x_i are pairwise distinct; similarly, all valus of y_i are pairwise distinct.OutputIf there is no ordering of topics meeting all the constraints, print 0.Otherwise, print n pairwise distinct integers q_1, q_2, ..., q_n (1 \le q_i \le n) — the ordering of topics meeting all of the constraints. If there are multiple answers, print any of them.ExamplesInput
5 2
2 3 0 5 3
1 5
5 4
Output
3 2 1 5 4
Input
5 2
2 3 0 5 3
1 5
5 1
Output
0
Input
5 1
2 3 0 5 3
4 5
Output
0
Input
5 4
2 3 0 5 3
2 1
3 5
5 2
1 4
Output
3 5 2 1 4
| 5 2
2 3 0 5 3
1 5
5 4
| 3 2 1 5 4 | 2 seconds | 512 megabytes | ['constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'implementation', 'sortings', 'trees', '*2400'] |
D. Pairstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have 2n integers 1, 2, \dots, 2n. You have to redistribute these 2n elements into n pairs. After that, you choose x pairs and take minimum elements from them, and from the other n - x pairs, you take maximum elements.Your goal is to obtain the set of numbers \{b_1, b_2, \dots, b_n\} as the result of taking elements from the pairs.What is the number of different x-s (0 \le x \le n) such that it's possible to obtain the set b if for each x you can choose how to distribute numbers into pairs and from which x pairs choose minimum elements?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains the integer n (1 \le n \le 2 \cdot 10^5).The second line of each test case contains n integers b_1, b_2, \dots, b_n (1 \le b_1 < b_2 < \dots < b_n \le 2n) — the set you'd like to get.It's guaranteed that the sum of n over test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print one number — the number of different x-s such that it's possible to obtain the set b.ExampleInput
3
1
1
5
1 4 5 9 10
2
3 4
Output
1
3
1
NoteIn the first test case, x = 1 is the only option: you have one pair (1, 2) and choose the minimum from this pair.In the second test case, there are three possible x-s. If x = 1, then you can form the following pairs: (1, 6), (2, 4), (3, 5), (7, 9), (8, 10). You can take minimum from (1, 6) (equal to 1) and the maximum elements from all other pairs to get set b.If x = 2, you can form pairs (1, 2), (3, 4), (5, 6), (7, 9), (8, 10) and take the minimum elements from (1, 2), (5, 6) and the maximum elements from the other pairs.If x = 3, you can form pairs (1, 3), (4, 6), (5, 7), (2, 9), (8, 10) and take the minimum elements from (1, 3), (4, 6), (5, 7).In the third test case, x = 0 is the only option: you can form pairs (1, 3), (2, 4) and take the maximum elements from both of them. | 3
1
1
5
1 4 5 9 10
2
3 4
| 1 3 1 | 2 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'greedy', 'two pointers', '*1900'] |
C. Busy Robottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a robot that can move along a number line. At time moment 0 it stands at point 0.You give n commands to the robot: at time t_i seconds you command the robot to go to point x_i. Whenever the robot receives a command, it starts moving towards the point x_i with the speed of 1 unit per second, and he stops when he reaches that point. However, while the robot is moving, it ignores all the other commands that you give him.For example, suppose you give three commands to the robot: at time 1 move to point 5, at time 3 move to point 0 and at time 6 move to point 4. Then the robot stands at 0 until time 1, then starts moving towards 5, ignores the second command, reaches 5 at time 6 and immediately starts moving to 4 to execute the third command. At time 7 it reaches 4 and stops there.You call the command i successful, if there is a time moment in the range [t_i, t_{i + 1}] (i. e. after you give this command and before you give another one, both bounds inclusive; we consider t_{n + 1} = +\infty) when the robot is at point x_i. Count the number of successful commands. Note that it is possible that an ignored command is successful.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases. The next lines describe the test cases.The first line of a test case contains a single integer n (1 \le n \le 10^5) — the number of commands.The next n lines describe the commands. The i-th of these lines contains two integers t_i and x_i (1 \le t_i \le 10^9, -10^9 \le x_i \le 10^9) — the time and the point of the i-th command.The commands are ordered by time, that is, t_i < t_{i + 1} for all possible i.The sum of n over test cases does not exceed 10^5.OutputFor each testcase output a single integer — the number of successful commands.ExampleInput
8
3
1 5
3 0
6 4
3
1 5
2 4
10 -5
5
2 -5
3 1
4 1
5 1
6 1
4
3 3
5 -3
9 2
12 0
8
1 1
2 -6
7 2
8 3
12 -9
14 2
18 -1
23 9
5
1 -4
4 -7
6 -1
7 -3
8 -7
2
1 2
2 -2
6
3 10
5 5
8 0
12 -4
14 -7
19 -5
Output
1
2
0
2
1
1
0
2
NoteThe movements of the robot in the first test case are described in the problem statement. Only the last command is successful.In the second test case the second command is successful: the robot passes through target point 4 at time 5. Also, the last command is eventually successful.In the third test case no command is successful, and the robot stops at -5 at time moment 7.Here are the 0-indexed sequences of the positions of the robot in each second for each testcase of the example. After the cut all the positions are equal to the last one: [0, 0, 1, 2, 3, 4, 5, 4, 4, \dots] [0, 0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -5, \dots] [0, 0, 0, -1, -2, -3, -4, -5, -5, \dots] [0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, \dots] [0, 0, 1, 0, -1, -2, -3, -4, -5, -6, -6, -6, -6, -7, -8, -9, -9, -9, -9, -8, -7, -6, -5, -4, -3, -2, -1, -1, \dots] [0, 0, -1, -2, -3, -4, -4, -3, -2, -1, -1, \dots] [0, 0, 1, 2, 2, \dots] [0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -7, \dots] | 8
3
1 5
3 0
6 4
3
1 5
2 4
10 -5
5
2 -5
3 1
4 1
5 1
6 1
4
3 3
5 -3
9 2
12 0
8
1 1
2 -6
7 2
8 3
12 -9
14 2
18 -1
23 9
5
1 -4
4 -7
6 -1
7 -3
8 -7
2
1 2
2 -2
6
3 10
5 5
8 0
12 -4
14 -7
19 -5
| 1 2 0 2 1 1 0 2 | 2 seconds | 256 megabytes | ['implementation', '*1800'] |
B. Find The Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array [a_1, a_2, \dots, a_n] such that 1 \le a_i \le 10^9. Let S be the sum of all elements of the array a.Let's call an array b of n integers beautiful if: 1 \le b_i \le 10^9 for each i from 1 to n; for every pair of adjacent integers from the array (b_i, b_{i + 1}), either b_i divides b_{i + 1}, or b_{i + 1} divides b_i (or both); 2 \sum \limits_{i = 1}^{n} |a_i - b_i| \le S. Your task is to find any beautiful array. It can be shown that at least one beautiful array always exists.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Each test case consists of two lines. The first line contains one integer n (2 \le n \le 50).The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).OutputFor each test case, print the beautiful array b_1, b_2, \dots, b_n (1 \le b_i \le 10^9) on a separate line. It can be shown that at least one beautiful array exists under these circumstances. If there are multiple answers, print any of them.ExampleInput
4
5
1 2 3 4 5
2
4 6
2
1 1000000000
6
3 4 8 1 2 3
Output
3 3 3 3 3
3 6
1 1000000000
4 4 8 1 3 3
| 4
5
1 2 3 4 5
2
4 6
2
1 1000000000
6
3 4 8 1 2 3
| 3 3 3 3 3 3 6 1 1000000000 4 4 8 1 3 3 | 2 seconds | 256 megabytes | ['bitmasks', 'constructive algorithms', 'greedy', '*1400'] |
A. Dungeontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a new computer game in which you have to fight monsters. In a dungeon you are trying to clear, you met three monsters; the first of them has a health points, the second has b health points, and the third has c.To kill the monsters, you can use a cannon that, when fired, deals 1 damage to the selected monster. Every 7-th (i. e. shots with numbers 7, 14, 21 etc.) cannon shot is enhanced and deals 1 damage to all monsters, not just one of them. If some monster's current amount of health points is 0, it can't be targeted by a regular shot and does not receive damage from an enhanced shot.You want to pass the dungeon beautifully, i. e., kill all the monsters with the same enhanced shot (i. e. after some enhanced shot, the health points of each of the monsters should become equal to 0 for the first time). Each shot must hit a monster, i. e. each shot deals damage to at least one monster.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of a single line that contains three integers a, b and c (1 \le a, b, c \le 10^8) — the number of health points each monster has.OutputFor each test case, print YES if you can kill all the monsters with the same enhanced shot. Otherwise, print NO. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).ExampleInput
3
3 2 4
1 1 1
10 1 7
Output
YES
NO
NO
NoteIn the first test case, you can do as follows: 1-th shot to the first monster, 2-th shot to the second monster, 3-th shot to the third monster, 4-th shot to the first monster, 5-th shot to the third monster, 6-th shot to the third monster, and 7-th enhanced shot will kill all the monsters.In the second test case, you can't kill monsters with the same enhanced shot, because the total number of health points of monsters is 3, and you will kill them in the first 3 shots. | 3
3 2 4
1 1 1
10 1 7
| YES NO NO | 2 seconds | 256 megabytes | ['binary search', 'math', '*1100'] |
F. The Treasure of The Segmentstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i — coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 \leq i \leq k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?InputThe first line contains a single integer t (1 \leq t \leq 2 \cdot 10^5) — number of test cases. Then t test cases follow.The first line of each test case contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the number of segments. This is followed by n lines describing the segments.Each segment is described by two integers l and r (1 \leq l \leq r \leq 10^9) — coordinates of the beginning and end of the segment, respectively.It is guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.ExampleInput
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
| 4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
| 0 1 2 0 | 3 seconds | 256 megabytes | ['binary search', 'data structures', 'greedy', '*1800'] |
E2. Close Tuples (hard version)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of this problem. The only difference between the easy and hard versions is the constraints on k and m. In this version of the problem, you need to output the answer by modulo 10^9+7.You are given a sequence a of length n consisting of integers from 1 to n. The sequence may contain duplicates (i.e. some elements can be equal).Find the number of tuples of m elements such that the maximum number in the tuple differs from the minimum by no more than k. Formally, you need to find the number of tuples of m indices i_1 < i_2 < \ldots < i_m, such that\max(a_{i_1}, a_{i_2}, \ldots, a_{i_m}) - \min(a_{i_1}, a_{i_2}, \ldots, a_{i_m}) \le k.For example, if n=4, m=3, k=2, a=[1,2,4,3], then there are two such triples (i=1, j=2, z=4 and i=2, j=3, z=4). If n=4, m=2, k=1, a=[1,1,1,1], then all six possible pairs are suitable.As the result can be very large, you should print the value modulo 10^9 + 7 (the remainder when divided by 10^9 + 7).InputThe first line contains a single integer t (1 \le t \le 2 \cdot 10^5) — the number of test cases. Then t test cases follow.The first line of each test case contains three integers n, m, k (1 \le n \le 2 \cdot 10^5, 1 \le m \le 100, 1 \le k \le n) — the length of the sequence a, number of elements in the tuples and the maximum difference of elements in the tuple.The next line contains n integers a_1, a_2,\ldots, a_n (1 \le a_i \le n) — the sequence a.It is guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputOutput t answers to the given test cases. Each answer is the required number of tuples of m elements modulo 10^9 + 7, such that the maximum value in the tuple differs from the minimum by no more than k.ExampleInput
4
4 3 2
1 2 4 3
4 2 1
1 1 1 1
1 1 1
1
10 4 3
5 6 1 3 2 9 8 1 2 4
Output
2
6
1
20
| 4
4 3 2
1 2 4 3
4 2 1
1 1 1 1
1 1 1
1
10 4 3
5 6 1 3 2 9 8 1 2 4
| 2 6 1 20 | 4 seconds | 256 megabytes | ['binary search', 'combinatorics', 'implementation', 'math', 'sortings', 'two pointers', '*1700'] |
E1. Close Tuples (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of this problem. The only difference between easy and hard versions is the constraints on k and m (in this version k=2 and m=3). Also, in this version of the problem, you DON'T NEED to output the answer by modulo.You are given a sequence a of length n consisting of integers from 1 to n. The sequence may contain duplicates (i.e. some elements can be equal).Find the number of tuples of m = 3 elements such that the maximum number in the tuple differs from the minimum by no more than k = 2. Formally, you need to find the number of triples of indices i < j < z such that\max(a_i, a_j, a_z) - \min(a_i, a_j, a_z) \le 2.For example, if n=4 and a=[1,2,4,3], then there are two such triples (i=1, j=2, z=4 and i=2, j=3, z=4). If n=4 and a=[1,1,1,1], then all four possible triples are suitable.InputThe first line contains a single integer t (1 \le t \le 2 \cdot 10^5) — the number of test cases. Then t test cases follow.The first line of each test case contains an integer n (1 \le n \le 2 \cdot 10^5) — the length of the sequence a.The next line contains n integers a_1, a_2,\ldots, a_n (1 \le a_i \le n) — the sequence a.It is guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputOutput t answers to the given test cases. Each answer is the required number of triples of elements, such that the maximum value in the triple differs from the minimum by no more than 2. Note that in difference to the hard version of the problem, you don't need to output the answer by modulo. You must output the exact value of the answer.ExampleInput
4
4
1 2 4 3
4
1 1 1 1
1
1
10
5 6 1 3 2 9 8 1 2 4
Output
2
4
0
15
| 4
4
1 2 4 3
4
1 1 1 1
1
1
10
5 6 1 3 2 9 8 1 2 4
| 2 4 0 15 | 2 seconds | 256 megabytes | ['binary search', 'combinatorics', 'math', 'sortings', 'two pointers', '*1500'] |
D. Add to Neighbour and Removetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp was given an array of a[1 \dots n] of n integers. He can perform the following operation with the array a no more than n times: Polycarp selects the index i and adds the value a_i to one of his choice of its neighbors. More formally, Polycarp adds the value of a_i to a_{i-1} or to a_{i+1} (if such a neighbor does not exist, then it is impossible to add to it). After adding it, Polycarp removes the i-th element from the a array. During this step the length of a is decreased by 1. The two items above together denote one single operation.For example, if Polycarp has an array a = [3, 1, 6, 6, 2], then it can perform the following sequence of operations with it: Polycarp selects i = 2 and adds the value a_i to (i-1)-th element: a = [4, 6, 6, 2]. Polycarp selects i = 1 and adds the value a_i to (i+1)-th element: a = [10, 6, 2]. Polycarp selects i = 3 and adds the value a_i to (i-1)-th element: a = [10, 8]. Polycarp selects i = 2 and adds the value a_i to (i-1)-th element: a = [18]. Note that Polycarp could stop performing operations at any time.Polycarp wondered how many minimum operations he would need to perform to make all the elements of a equal (i.e., he wants all a_i are equal to each other).InputThe first line contains a single integer t (1 \leq t \leq 3000) — the number of test cases in the test. Then t test cases follow.The first line of each test case contains a single integer n (1 \leq n \leq 3000) — the length of the array. The next line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^5) — array a.It is guaranteed that the sum of n over all test cases does not exceed 3000.OutputFor each test case, output a single number — the minimum number of operations that Polycarp needs to perform so that all elements of the a array are the same (equal).ExampleInput
4
5
3 1 6 6 2
4
1 2 2 1
3
2 2 2
4
6 3 2 1
Output
4
2
0
2
NoteIn the first test case of the example, the answer can be constructed like this (just one way among many other ways):[3, 1, 6, 6, 2] \xrightarrow[]{i=4,~add~to~left} [3, 1, 12, 2] \xrightarrow[]{i=2,~add~to~right} [3, 13, 2] \xrightarrow[]{i=1,~add~to~right} [16, 2] \xrightarrow[]{i=2,~add~to~left} [18]. All elements of the array [18] are the same.In the second test case of the example, the answer can be constructed like this (just one way among other ways):[1, 2, 2, 1] \xrightarrow[]{i=1,~add~to~right} [3, 2, 1] \xrightarrow[]{i=3,~add~to~left} [3, 3]. All elements of the array [3, 3] are the same.In the third test case of the example, Polycarp doesn't need to perform any operations since [2, 2, 2] contains equal (same) elements only.In the fourth test case of the example, the answer can be constructed like this (just one way among other ways):[6, 3, 2, 1] \xrightarrow[]{i=3,~add~to~right} [6, 3, 3] \xrightarrow[]{i=3,~add~to~left} [6, 6]. All elements of the array [6, 6] are the same. | 4
5
3 1 6 6 2
4
1 2 2 1
3
2 2 2
4
6 3 2 1
| 4 2 0 2 | 3 seconds | 256 megabytes | ['greedy', 'math', 'number theory', '*1400'] |
C. Unique Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive number x. Find the smallest positive integer number that has the sum of digits equal to x and all digits are distinct (unique).InputThe first line contains a single positive integer t (1 \le t \le 50) — the number of test cases in the test. Then t test cases follow.Each test case consists of a single integer number x (1 \le x \le 50).OutputOutput t answers to the test cases: if a positive integer number with the sum of digits equal to x and all digits are different exists, print the smallest such number; otherwise print -1. ExampleInput
4
1
5
15
50
Output
1
5
69
-1
| 4
1
5
15
50
| 1 5 69 -1 | 2 seconds | 256 megabytes | ['brute force', 'greedy', 'math', '*900'] |
B. Last Year's Substringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has a string s[1 \dots n] of length n consisting of decimal digits. Polycarp performs the following operation with the string s no more than once (i.e. he can perform operation 0 or 1 time): Polycarp selects two numbers i and j (1 \leq i \leq j \leq n) and removes characters from the s string at the positions i, i+1, i+2, \ldots, j (i.e. removes substring s[i \dots j]). More formally, Polycarp turns the string s into the string s_1 s_2 \ldots s_{i-1} s_{j+1} s_{j+2} \ldots s_{n}. For example, the string s = "20192020" Polycarp can turn into strings: "2020" (in this case (i, j)=(3, 6) or (i, j)=(1, 4)); "2019220" (in this case (i, j)=(6, 6)); "020" (in this case (i, j)=(1, 5)); other operations are also possible, only a few of them are listed above. Polycarp likes the string "2020" very much, so he is wondering if it is possible to turn the string s into a string "2020" in no more than one operation? Note that you can perform zero operations.InputThe first line contains a positive integer t (1 \leq t \leq 1000 ) — number of test cases in the test. Then t test cases follow.The first line of each test case contains an integer n (4 \leq n \leq 200) — length of the string s. The next line contains a string s of length n consisting of decimal digits. It is allowed that the string s starts with digit 0.OutputFor each test case, output on a separate line: "YES" if Polycarp can turn the string s into a string "2020" in no more than one operation (i.e. he can perform 0 or 1 operation); "NO" otherwise. You may print every letter of "YES" and "NO" in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).ExampleInput
6
8
20192020
8
22019020
4
2020
5
20002
6
729040
6
200200
Output
YES
YES
YES
NO
NO
NO
NoteIn the first test case, Polycarp could choose i=3 and j=6.In the second test case, Polycarp could choose i=2 and j=5.In the third test case, Polycarp did not perform any operations with the string. | 6
8
20192020
8
22019020
4
2020
5
20002
6
729040
6
200200
| YES YES YES NO NO NO | 2 seconds | 256 megabytes | ['dp', 'implementation', 'strings', '*800'] |
A. Favorite Sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has a favorite sequence a[1 \dots n] consisting of n integers. He wrote it out on the whiteboard as follows: he wrote the number a_1 to the left side (at the beginning of the whiteboard); he wrote the number a_2 to the right side (at the end of the whiteboard); then as far to the left as possible (but to the right from a_1), he wrote the number a_3; then as far to the right as possible (but to the left from a_2), he wrote the number a_4; Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard. The beginning of the result looks like this (of course, if n \ge 4). For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.InputThe first line contains a single positive integer t (1 \le t \le 300) — the number of test cases in the test. Then t test cases follow.The first line of each test case contains an integer n (1 \le n \le 300) — the length of the sequence written on the whiteboard.The next line contains n integers b_1, b_2,\ldots, b_n (1 \le b_i \le 10^9) — the sequence written on the whiteboard.OutputOutput t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.ExampleInput
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
NoteIn the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:[3] \Rightarrow [3, 1] \Rightarrow [3, 4, 1] \Rightarrow [3, 4, 1, 1] \Rightarrow [3, 4, 5, 1, 1] \Rightarrow [3, 4, 5, 9, 1, 1] \Rightarrow [3, 4, 5, 2, 9, 1, 1]. | 6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
| 3 1 4 1 5 9 2 9 1 2 7 8 2 4 4 3 9 1 7 2 8 7 42 11 7 1 1 1 1 1 1 1 1 | 2 seconds | 256 megabytes | ['implementation', 'two pointers', '*800'] |
F. Mathematical Expressiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBarbara was late for her math class so as a punishment the teacher made her solve the task on a sheet of paper. Barbara looked at the sheet of paper and only saw n numbers a_1, a_2, \ldots, a_n without any mathematical symbols. The teacher explained to Barbara that she has to place the available symbols between the numbers in a way that would make the resulting expression's value as large as possible. To find out which symbols were available the teacher has given Barbara a string s which contained that information. It's easy to notice that Barbara has to place n - 1 symbols between numbers in total. The expression must start with a number and all symbols must be allowed (i.e. included in s). Note that multiplication takes precedence over addition or subtraction, addition and subtraction have the same priority and performed from left to right. Help Barbara and create the required expression!InputThe first line of the input contains a single integer n (1 \le n \le 10^5) — the amount of numbers on the paper.The second line of the input contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 9), where a_i is the i-th element of a.The third line of the input contains the string s (1 \le |s| \le 3) — symbols allowed in the expression. It is guaranteed that the string may only consist of symbols "-", "+" and "*". It is also guaranteed that all symbols in the string are distinct.OutputPrint n numbers separated by n - 1 symbols — a mathematical expression with the greatest result. If there are multiple equally valid results — output any one of them.ExamplesInput
3
2 2 0
+-*
Output
2*2-0
Input
4
2 1 1 2
+*
Output
2+1+1+2
NoteThe following answers also fit the first example: "2+2+0", "2+2-0", "2*2+0". | 3
2 2 0
+-*
| 2*2-0 | 1 second | 256 megabytes | ['constructive algorithms', 'dp', 'greedy', '*2700'] |
E. Water Leveltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn recent years John has very successfully settled at his new job at the office. But John doesn't like to idly sit around while his code is compiling, so he immediately found himself an interesting distraction. The point of his distraction was to maintain a water level in the water cooler used by other zebras. Originally the cooler contained exactly k liters of water. John decided that the amount of water must always be at least l liters of water but no more than r liters. John will stay at the office for exactly t days. He knows that each day exactly x liters of water will be used by his colleagues. At the beginning of each day he can add exactly y liters of water to the cooler, but at any point in time the amount of water in the cooler must be in the range [l, r].Now John wants to find out whether he will be able to maintain the water level at the necessary level for t days. Help him answer this question!InputThe first line of the input contains six integers k, l, r, t, x and y (1 \le l \le k \le r \le 10^{18}; 1 \le t \le 10^{18}; 1 \le x \le 10^6; 1 \le y \le 10^{18}) — initial water level, the required range, the number of days, daily water usage and the exact amount of water that can be added, respectively.OutputPrint "Yes" if John can maintain the water level for t days and "No" otherwise.ExamplesInput
8 1 10 2 6 4
Output
No
Input
8 1 10 2 6 5
Output
Yes
Input
9 1 10 9 2 9
Output
No
Input
20 15 25 3 5 7
Output
Yes
NoteIn the first example, John can't increase the amount of water at the beginning of the first day, since it would exceed the limit r. That is why after the first day the cooler will contain 2 liters of water. The next day John adds 4 liters to the cooler but loses 6 liters, leaving John with 0 liters, which is outside the range [1, 10].In the second example, after the first day John is left with 2 liters of water. At the beginning of the next day he adds 5 liters, then 6 liters get used, leaving John with 1 liter of water which is in range [1, 10].In the third example, after the first day John is left with 7 liters, after the second day — 5 liters, after the fourth — 1 liter. At the beginning of the fifth day John will add 9 liters and lose 2 liters. Meaning, after the fifth day he will have 8 liters left. Then each day the water level will decrease by 2 liters and after the eighth day John will have 2 liters and after the ninth day — 0 liters. 0 is outside range [1, 10], so the answer is "No".In the fourth example, after the first day John is left with 15 liters of water. At the beginning of the second day he adds 7 liters and loses 5, so after the second day he is left with 17 liters. At the beginning of the third day he adds 7 more liters of water and loses 5, so after the third day he is left with 19 liters. 19 is in range [15, 25] so the answer is "Yes". | 8 1 10 2 6 4
| No | 1 second | 256 megabytes | ['brute force', 'graphs', 'greedy', 'implementation', 'math', '*2200'] |
D. Divide and Summarizetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike received an array a of length n as a birthday present and decided to test how pretty it is.An array would pass the i-th prettiness test if there is a way to get an array with a sum of elements totaling s_i, using some number (possibly zero) of slicing operations. An array slicing operation is conducted in the following way: assume mid = \lfloor\frac{max(array) + min(array)}{2}\rfloor, where max and min — are functions that find the maximum and the minimum array elements. In other words, mid is the sum of the maximum and the minimum element of array divided by 2 rounded down. Then the array is split into two parts \mathit{left} and right. The \mathit{left} array contains all elements which are less than or equal mid, and the right array contains all elements which are greater than mid. Elements in \mathit{left} and right keep their relative order from array. During the third step we choose which of the \mathit{left} and right arrays we want to keep. The chosen array replaces the current one and the other is permanently discarded. You need to help Mike find out the results of q prettiness tests.Note that you test the prettiness of the array a, so you start each prettiness test with the primordial (initial) array a. Thus, the first slice (if required) is always performed on the array a.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 100).The first line of each test case contains two integers n and q (1 \le n, q \le 10^5) — the length of the array a and the total number of prettiness tests.The second line of each test case contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^6) — the contents of the array a.Next q lines of each test case contain a single integer s_i (1 \le s_i \le 10^9) — the sum of elements which Mike wants to get in the i-th test.It is guaranteed that the sum of n and the sum of q does not exceed 10^5 (\sum n, \sum q \le 10^5).OutputPrint q lines, each containing either a "Yes" if the corresponding prettiness test is passed and "No" in the opposite case.ExampleInput
2
5 5
1 2 3 4 5
1
8
9
12
6
5 5
3 1 3 1 3
1
2
3
9
11
Output
Yes
No
Yes
No
Yes
No
Yes
No
Yes
Yes
NoteExplanation of the first test case: We can get an array with the sum s_1 = 1 in the following way: 1.1 a = [1, 2, 3, 4, 5], mid = \frac{1+5}{2} = 3, \mathit{left} = [1, 2, 3], right = [4, 5]. We choose to keep the \mathit{left} array. 1.2 a = [1, 2, 3], mid = \frac{1+3}{2} = 2, \mathit{left} = [1, 2], right = [3]. We choose to keep the \mathit{left} array. 1.3 a = [1, 2], mid = \frac{1+2}{2} = 1, \mathit{left} = [1], right = [2]. We choose to keep the \mathit{left} array with the sum equalling 1. It can be demonstrated that an array with the sum s_2 = 8 is impossible to generate. An array with the sum s_3 = 9 can be generated in the following way: 3.1 a = [1, 2, 3, 4, 5], mid = \frac{1+5}{2} = 3, \mathit{left} = [1, 2, 3], right = [4, 5]. We choose to keep the right array with the sum equalling 9. It can be demonstrated that an array with the sum s_4 = 12 is impossible to generate. We can get an array with the sum s_5 = 6 in the following way: 5.1 a = [1, 2, 3, 4, 5], mid = \frac{1+5}{2} = 3, \mathit{left} = [1, 2, 3], right = [4, 5]. We choose to keep the \mathit{left} with the sum equalling 6. Explanation of the second test case: It can be demonstrated that an array with the sum s_1 = 1 is imposssible to generate. We can get an array with the sum s_2 = 2 in the following way: 2.1 a = [3, 1, 3, 1, 3], mid = \frac{1+3}{2} = 2, \mathit{left} = [1, 1], right = [3, 3, 3]. We choose to keep the \mathit{left} array with the sum equalling 2. It can be demonstrated that an array with the sum s_3 = 3 is imposssible to generate. We can get an array with the sum s_4 = 9 in the following way: 4.1 a = [3, 1, 3, 1, 3], mid = \frac{1+3}{2} = 2, \mathit{left} = [1, 1], right = [3, 3, 3]. We choose to keep the right array with the sum equalling 9. We can get an array with the sum s_5 = 11 with zero slicing operations, because array sum is equal to 11. | 2
5 5
1 2 3 4 5
1
8
9
12
6
5 5
3 1 3 1 3
1
2
3
9
11
| Yes No Yes No Yes No Yes No Yes Yes | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'data structures', 'divide and conquer', 'implementation', 'sortings', '*1600'] |
C. Random Eventstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRon is a happy owner of a permutation a of length n.A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data.As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged.You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 100).The first line of each test case contains two integers n and m (1 \le n, m \le 10^5) — the length of the permutation and the number of experiments, respectively.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — contents of the permutation.The following m lines of each test case each contain an integer r_i and a real number p_i (1 \le r_i \le n, 0 \le p_i \le 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places.It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (\sum n, \sum m \le 10^5).OutputFor each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be 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}.ExampleInput
4
4 3
4 3 2 1
1 0.3
3 1
4 0.6
5 3
4 2 1 3 5
3 0.8
4 0.6
5 0.3
6 5
1 3 2 4 5 6
4 0.9
5 0.3
2 0.4
6 0.7
3 0.5
4 2
1 2 3 4
2 0.5
4 0.1
Output
0.600000
0.720000
0.989500
1.000000
NoteExplanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. | 4
4 3
4 3 2 1
1 0.3
3 1
4 0.6
5 3
4 2 1 3 5
3 0.8
4 0.6
5 0.3
6 5
1 3 2 4 5 6
4 0.9
5 0.3
2 0.4
6 0.7
3 0.5
4 2
1 2 3 4
2 0.5
4 0.1
| 0.600000 0.720000 0.989500 1.000000 | 2 seconds | 256 megabytes | ['dp', 'math', 'probabilities', '*1500'] |
B. Find the Sprucetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHolidays are coming up really soon. Rick realized that it's time to think about buying a traditional spruce tree. But Rick doesn't want real trees to get hurt so he decided to find some in an n \times m matrix consisting of "*" and ".". To find every spruce first let's define what a spruce in the matrix is. A set of matrix cells is called a spruce of height k with origin at point (x, y) if: All cells in the set contain an "*". For each 1 \le i \le k all cells with the row number x+i-1 and columns in range [y - i + 1, y + i - 1] must be a part of the set. All other cells cannot belong to the set. Examples of correct and incorrect spruce trees: Now Rick wants to know how many spruces his n \times m matrix contains. Help Rick solve this problem.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 10).The first line of each test case contains two integers n and m (1 \le n, m \le 500) — matrix size.Next n lines of each test case contain m characters c_{i, j} — matrix contents. It is guaranteed that c_{i, j} is either a "." or an "*".It is guaranteed that the sum of n \cdot m over all test cases does not exceed 500^2 (\sum n \cdot m \le 500^2).OutputFor each test case, print single integer — the total number of spruces in the matrix.ExampleInput
4
2 3
.*.
***
2 3
.*.
**.
4 5
.***.
*****
*****
*.*.*
5 7
..*.*..
.*****.
*******
.*****.
..*.*..
Output
5
3
23
34
NoteIn the first test case the first spruce of height 2 has its origin at point (1, 2), the second spruce of height 1 has its origin at point (1, 2), the third spruce of height 1 has its origin at point (2, 1), the fourth spruce of height 1 has its origin at point (2, 2), the fifth spruce of height 1 has its origin at point (2, 3).In the second test case the first spruce of height 1 has its origin at point (1, 2), the second spruce of height 1 has its origin at point (2, 1), the third spruce of height 1 has its origin at point (2, 2). | 4
2 3
.*.
***
2 3
.*.
**.
4 5
.***.
*****
*****
*.*.*
5 7
..*.*..
.*****.
*******
.*****.
..*.*..
| 5 3 23 34 | 1 second | 256 megabytes | ['brute force', 'dp', 'implementation', '*1400'] |
A. String Generationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne fall day Joe got bored because he couldn't find himself something interesting to do. Marty suggested Joe to generate a string of length n to entertain him somehow. It didn't seem particularly difficult, but Joe's generated string had to follow these rules: the string may only contain characters 'a', 'b', or 'c'; the maximum length of a substring of this string that is a palindrome does not exceed k. 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. For example, strings "a", "bc", "abc" are substrings of a string "abc", while strings "ac", "ba", "cba" are not.A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, strings "abccba", "abbba", "aba", "abacaba", "a", and "bacab" are palindromes, while strings "abcbba", "abb", and "ab" are not.Now Joe wants to find any correct string. Help him! It can be proven that the answer always exists under the given constraints.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 10).The only line of each test case contains two integers n and k (1 \le k \le n \le 1\,000) — the required string length and the maximum length of a palindrome substring, respectively.OutputFor each test case, print any string that satisfies the conditions from the problem statement. If there are multiple correct answers, you can print any one of them. It can be proven that the answer always exists under the given constraints.ExampleInput
2
3 2
4 1
Output
aab
acba
NoteIn the first test case of the example, the palindrome substring with the maximum length is "aa". Its length does not exceed 2, so it fits.In the second test case all palindrome substrings have the length one. | 2
3 2
4 1
| aab acba | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*800'] |
B. Move and Turntime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA robot is standing at the origin of the infinite two-dimensional plane. Each second the robot moves exactly 1 meter in one of the four cardinal directions: north, south, west, and east. For the first step the robot can choose any of the four directions, but then at the end of every second it has to turn 90 degrees left or right with respect to the direction it just moved in. For example, if the robot has just moved north or south, the next step it takes has to be either west or east, and vice versa.The robot makes exactly n steps from its starting position according to the rules above. How many different points can the robot arrive to at the end? The final orientation of the robot can be ignored.InputThe only line contains a single integer n (1 \leq n \leq 1000) — the number of steps the robot makes.OutputPrint a single integer — the number of different possible locations after exactly n steps.ExamplesInput
1
Output
4
Input
2
Output
4
Input
3
Output
12
NoteIn the first sample case, the robot will end up 1 meter north, south, west, or east depending on its initial direction.In the second sample case, the robot will always end up \sqrt{2} meters north-west, north-east, south-west, or south-east. | 1
| 4 | 2 seconds | 512 megabytes | ['dp', 'math', '*1300'] |
A. Red-Blue Shuffletime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n cards numbered 1, \ldots, n. The card i has a red digit r_i and a blue digit b_i written on it.We arrange all n cards in random order from left to right, with all permutations of 1, \ldots, n having the same probability. We then read all red digits on the cards from left to right, and obtain an integer R. In the same way, we read all blue digits and obtain an integer B. When reading a number, leading zeros can be ignored. If all digits in a number are zeros, then the number is equal to 0. Below is an illustration of a possible rearrangement of three cards, and how R and B can be found. Two players, Red and Blue, are involved in a bet. Red bets that after the shuffle R > B, and Blue bets that R < B. If in the end R = B, the bet results in a draw, and neither player wins.Determine, which of the two players is more likely (has higher probability) to win the bet, or that their chances are equal. Refer to the Note section for a formal discussion of comparing probabilities.InputThe first line contains a single integer T (1 \leq T \leq 100) — the number of test cases.Descriptions of T test cases follow. Each test case description starts with a line containing a single integer n (1 \leq n \leq 1000) — the number of cards.The following line contains a string of n digits r_1, \ldots, r_n — red digits on cards 1, \ldots, n respectively.The following line contains a string of n digits b_1, \ldots, b_n — blue digits on cards 1, \ldots, n respectively.Note that digits in the same line are not separated with any delimiters.OutputPrint T answers for the test cases in order, one per line.If Red has a strictly higher change to win, print "RED".If Blue has a strictly higher change to win, print "BLUE".If both players are equally likely to win, print "EQUAL".Note that all answers are case-sensitive.ExampleInput
3
3
777
111
3
314
159
5
09281
09281
Output
RED
BLUE
EQUAL
NoteFormally, let n_R be the number of permutations of cards 1, \ldots, n such that the resulting numbers R and B satisfy R > B. Similarly, let n_B be the number of permutations such that R < B. If n_R > n_B, you should print "RED". If n_R < n_B, you should print "BLUE". If n_R = n_B, print "EQUAL".In the first sample case, R = 777 and B = 111 regardless of the card order, thus Red always wins.In the second sample case, there are two card orders when Red wins, and four card orders when Blue wins: order 1, 2, 3: 314 > 159; order 1, 3, 2: 341 > 195; order 2, 1, 3: 134 < 519; order 2, 3, 1: 143 < 591; order 3, 1, 2: 431 < 915; order 3, 2, 1: 413 < 951.Since R < B is more frequent, the answer is "BLUE".In the third sample case, R = B regardless of the card order, thus the bet is always a draw, and both Red and Blue have zero chance to win. | 3
3
777
111
3
314
159
5
09281
09281
| RED BLUE EQUAL | 2 seconds | 512 megabytes | ['math', 'probabilities', '*800'] |
F. Range Diameter Sumtime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree with n vertices numbered 1, \ldots, n. A tree is a connected simple graph without cycles.Let \mathrm{dist}(u, v) be the number of edges in the unique simple path connecting vertices u and v.Let \mathrm{diam}(l, r) = \max \mathrm{dist}(u, v) over all pairs u, v such that l \leq u, v \leq r.Compute \sum_{1 \leq l \leq r \leq n} \mathrm{diam}(l, r).InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the number of vertices in the tree.The next n - 1 lines describe the tree edges. Each of these lines contains two integers u, v (1 \leq u, v \leq n) — endpoint indices of the respective tree edge. It is guaranteed that the edge list indeed describes a tree.OutputPrint a single integer — \sum_{1 \leq l \leq r \leq n} \mathrm{diam}(l, r).ExamplesInput
4
1 2
2 4
3 2
Output
10
Input
10
1 8
2 9
5 6
4 8
4 2
7 9
3 6
10 4
3 9
Output
224
| 4
1 2
2 4
3 2
| 10 | 7 seconds | 512 megabytes | ['data structures', 'trees', '*3500'] |
E. Nim Shortcutstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAfter your debut mobile game "Nim" blew up, you decided to make a sequel called "Nim 2". This game will expand on the trusted Nim game formula, adding the much awaited second heap! In the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a player can take any positive number of stones from either one of the heaps. A player who is unable to move loses the game.To make the game easier to playtest, you've introduced developer shortcuts. There are n shortcut positions (x_1, y_1), \ldots, (x_n, y_n). These change the game as follows: suppose that before a player's turn the first and second heap contain x and y stones respectively. If the pair (x, y) is equal to one of the pairs (x_i, y_i), then the player about to move loses instantly, otherwise they are able to make moves as normal. Note that in the above explanation the two heaps and all pairs are ordered, that is, x must refer to the size of the first heap, and y must refer to the size of the second heap.The game release was followed by too much celebration, and next thing you know is developer shortcuts made their way to the next official update of the game! Players now complain that the AI opponent has become unbeatable at certain stages of the game. You now have to write a program to figure out which of the given initial positions can be won by the starting player, assuming both players act optimally.InputThe first line contains two integers n and m (1 \leq n, m \leq 10^5) — the number of shortcut positions, and the number of initial positions that need to be evaluated.The following n lines describe shortcut positions. The i-th of these lines contains two integers x_i, y_i (0 \leq x_i, y_i \leq 10^9). It is guaranteed that all shortcut positions are distinct.The following m lines describe initial positions. The i-th of these lines contains two integers a_i, b_i (0 \leq a_i, b_i \leq 10^9) — the number of stones in the first and second heap respectively. It is guaranteed that all initial positions are distinct. However, initial positions are not necessarily distinct from shortcut positions.OutputFor each initial position, on a separate line print "WIN" if the starting player is able to win from this position, and "LOSE" otherwise.ExampleInput
3 5
3 0
0 1
2 2
0 0
1 1
2 2
3 3
5 4
Output
LOSE
WIN
LOSE
WIN
LOSE
| 3 5
3 0
0 1
2 2
0 0
1 1
2 2
3 3
5 4
| LOSE WIN LOSE WIN LOSE | 2 seconds | 512 megabytes | ['data structures', 'games', '*3100'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.