problem_statement
stringlengths 147
8.53k
| input
stringlengths 1
771
| output
stringlengths 1
592
⌀ | time_limit
stringclasses 32
values | memory_limit
stringclasses 21
values | tags
stringlengths 6
168
|
---|---|---|---|---|---|
D. Misha and Applestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSchoolboy Misha got tired of doing sports programming, so he decided to quit everything and go to the magical forest to sell magic apples.His friend Danya came to the magical forest to visit Misha. What was his surprise when he found out that Misha found a lot of friends there, the same former sports programmers. And all of them, like Misha, have their own shop where they sell magic apples. To support his friends, who have changed their lives so drastically, he decided to buy up their entire assortment.The buying process works as follows: in total there are n stalls, numbered with integers from 1 to n, and m kinds of magic apples, numbered with integers from 1 to m. Each shop sells some number of kinds of apples. Danya visits all the shops in order of increasing number, starting with the first one. Upon entering the shop he buys one magic apple of each kind sold in that shop and puts them in his backpack.However, magical apples wouldn't be magical if they were all right. The point is that when two apples of the same type end up together in the backpack, all of the apples in it magically disappear. Importantly, the disappearance happens after Danya has put the apples in the backpack and left the shop.Upon returning home, Danya realized that somewhere in the forest he had managed to lose his backpack. Unfortunately, for some shops Danya had forgotten what assortment of apples there was. Remembering only for some shops, what kinds of magical apples were sold in them, he wants to know what is the maximum number of apples he could have in his backpack after all his purchases at best.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 2 \cdot 10^5) —the number of test cases. The description of test cases follows.The first line contains two integers n and m (1 \leq n, m \leq 2 \cdot 10^5) —the number of stalls and kinds of apples.Each of the following n lines describes the assortment of the next stall in the format described below.Each line starts with an integer k_i (0 \le k_i \le 2 \cdot 10^5). This is followed by k_i of different integers a_{ij} (1 \le a_{ij} \le m) —the kinds of apples sold in the i-th stall. If k_i = 0, then Danya does not remember what assortment was in that shop, and the set of apple kinds can be anything (including empty).It is guaranteed that the sum of all k_i over all test cases does not exceed 2 \cdot 10^5 and the sum of n over all test cases does not exceed 2 \cdot 10^5OutputFor each test case, output a single integer — the maximum number of apples that could be in Dani's backpack after visiting all the shops at best.ExampleInput
43 42 1 22 4 12 1 24 42 1 22 3 401 12 5005 303 1 2 32 3 101 3Output
2
1
5
3
NoteIn the first test case, Danya remembers all the shops, so the process will be deterministic. He will take two apples at the first shop and two more at the second, but after he puts them in his backpack, they will disappear. So at the end there will only be 2 apples left, which he will take at the third shop.In the second test case, if the third shop is empty, then after visiting the fourth shop all the apples will disappear. In any other case the apples will disappear after the third shop, and in the fourth shop Dan can take one apple, so the answer is 1.In the third test case, the first shop may sell all kinds of apples, and the second shop may sell nothing. Then all 5 apples will be left at the end. | 43 42 1 22 4 12 1 24 42 1 22 3 401 12 5005 303 1 2 32 3 101 3 | 2 1 5 3 | 1 second | 256 megabytes | ['brute force', 'data structures', 'dp', 'two pointers', '*2800'] |
C. The Fox and the Complete Tree Traversaltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe fox Yae climbed the tree of the Sacred Sakura. A tree is a connected undirected graph that does not contain cycles.The fox uses her magical powers to move around the tree. Yae can jump from vertex v to another vertex u if and only if the distance between these vertices does not exceed 2. In other words, in one jump Yae can jump from vertex v to vertex u if vertices v and u are connected by an edge, or if there exists such vertex w that vertices v and w are connected by an edge, and also vertices u and w are connected by an edge.After Yae was able to get the sakura petal, she wondered if there was a cyclic route in the tree v_1, v_2, \ldots, v_n such that: the fox can jump from vertex v_i to vertex v_{i + 1}, the fox can jump from vertex v_n to vertex v_1, all v_i are pairwise distinct. Help the fox determine if the required traversal exists.InputThe first line contains one integer n (2 \le n \le 2 \cdot 10^5) —the number of vertices of the tree.Each of the following n - 1 lines contains two integers u and v (1 \le u, v \le n, u \ne v) — vertices connected by an edge. It is guaranteed that these edges form a tree.OutputOn the first line, print "Yes" (without quotes) if the required route of the tree exists, or "No" (without quotes) otherwise.If the required tree traversal exists, on the second line print n integers of different integers v_1, v_2, \ldots, v_n (1 \le v_i \le n) — the vertices of the tree in traversal order.If there are several correct traversals, output any of them.ExamplesInput
5
1 2
1 3
3 4
3 5
Output
Yes
4 5 1 2 3
Input
3
1 2
1 3
Output
Yes
1 2 3
Input
15
1 2
1 3
2 4
2 5
3 6
3 7
4 8
4 9
5 10
5 11
6 12
6 13
7 14
7 15
Output
No
NoteThe tree from the first example is shown below. The bold arrows indicate the fox's route. In the second example, any sequence of three different vertices is a correct route, because the fox can jump from any vertex to any vertex.The tree from the third example is shown below. It can be shown that there is no required route for it. | 5
1 2
1 3
3 4
3 5
| Yes 4 5 1 2 3 | 1 second | 256 megabytes | ['constructive algorithms', 'dp', 'implementation', 'math', 'trees', '*2400'] |
B. The Butchertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton plays his favorite game "Defense of The Ancients 2" for his favorite hero — The Butcher. Now he wants to make his own dinner. To do this he will take a rectangle of height h and width w, then make a vertical or horizontal cut so that both resulting parts have integer sides. After that, he will put one of the parts in the box and cut the other again, and so on.More formally, a rectangle of size h \times w can be cut into two parts of sizes x \times w and (h - x) \times w, where x is an integer from 1 to (h - 1), or into two parts of sizes h \times y and h \times (w - y), where y is an integer from 1 to (w - 1).He will repeat this operation n - 1 times, and then put the remaining rectangle into the box too. Thus, the box will contain n rectangles, of which n - 1 rectangles were put in the box as a result of the cuts, and the n-th rectangle is the one that the Butcher has left after all n - 1 cuts.Unfortunately, Butcher forgot the numbers h and w, but he still has n rectangles mixed in random order. Note that Butcher didn't rotate the rectangles, but only shuffled them. Now he wants to know all possible pairs (h, w) from which this set of rectangles can be obtained. And you have to help him do it!It is guaranteed that there exists at least one pair (h, w) from which this set of rectangles can be obtained.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of rectangles obtained.The i-th of the next n lines contains two integers a_i and b_i (1 \le a_i, b_i \le 10^6) — the height and width of the i-th rectangle.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, on the first line output a single integer m — the number of pairs (h, w) denoting the sizes of rectangles from which the given rectangles can be obtained. Two rectangles are considered different if they have different heights or widths.On each of the following m lines print output integers h_i and w_i — the height and width of the rectangle from which the given rectangles can be obtained. You can output the rectangles in any order.ExampleInput
431 23 51 331 11 11 1110 1043 25 52 28 7Output
1
4 5
2
1 3
3 1
1
10 10
1
13 7
NoteIn the first test case, Butcher could only have a rectangle of size 4 \times 5. Then the cuts could look like this (first the green cut was made, then the red one): In the second test case, Butcher could have either a rectangle of 1 \times 3 or 3 \times 1. The cuts would have looked like this (first the green cut was made, then the red cut): In the third test case, Butcher did not make any cuts, so the rectangle is 10 \times 10. | 431 23 51 331 11 11 1110 1043 25 52 28 7 | 1 4 5 2 1 3 3 1 1 10 10 1 13 7 | 2 seconds | 256 megabytes | ['geometry', 'greedy', 'implementation', 'sortings', 'two pointers', '*1900'] |
A. Constructive Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you know, any problem that does not require the use of complex data structures is considered constructive. You are offered to solve one of such problems.You are given an array a of n non-negative integers. You are allowed to perform the following operation exactly once: choose some non-empty subsegment a_l, a_{l+1}, \ldots, a_r of the array a and a non-negative integer k, and assign value k to all elements of the array on the chosen subsegment.The task is to find out whether \operatorname{MEX}(a) can be increased by exactly one by performing such an operation. In other words, if before the operation \operatorname{MEX}(a) = m held, then after the operation it must hold that \operatorname{MEX}(a) = m + 1.Recall that \operatorname{MEX} of a set of integers c_1, c_2, \ldots, c_k is defined as the smallest non-negative integer x which does not occur in the set c.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 50\,000) — 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 200\,000) — the number of elements of array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — elements of array a.It is guaranteed that the sum n over all test cases does not exceed 200\,000.OutputFor each test case, print "Yes" if you can increase \operatorname{MEX}(a) by exactly one by performing the operation from the statement exactly once, otherwise print "No".You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput
431 2 140 2 2 043 2 0 210Output
Yes
Yes
No
No
NoteIn the first test case, \operatorname{MEX}(a) = 0. If you set all elements of a to 0, then \operatorname{MEX} of the resulting array will be 1, and thus will increase by one.In the second test case, \operatorname{MEX}(a) = 1. If we assign a value of 1 to the elements of a on a subsegment from 2 to 3, we get an array [0, 1, 1, 0] for which \operatorname{MEX} is 2, and thus is increased by one compared to the original.It can be shown that in the third and fourth test cases it is impossible to perform an operation so that the value of \operatorname{MEX}(a) increases by exactly one. | 431 2 140 2 2 043 2 0 210 | Yes Yes No No | 1 second | 256 megabytes | ['brute force', 'greedy', '*1300'] |
B. Indivisibletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given a positive integer n.Find a permutation a_1, a_2, \dots, a_n such that for any 1 \leq l < r \leq n, the sum a_l + a_{l+1} + \dots + a_r is not divisible by r-l+1.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).InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line of each test case contain a single integer n (1 \leq n \leq 100) — the size of the desired permutation.OutputFor each test case, if there is no such permutation print -1.Otherwise, print n distinct integers p_1, p_{2}, \dots, p_n (1 \leq p_i \leq n) — a permutation satisfying the condition described in the statement.If there are multiple solutions, print any.ExampleInput
3
1
2
3
Output
1
1 2
-1
NoteIn the first example, there are no valid pairs of l < r, meaning that the condition is true for all such pairs.In the second example, the only valid pair is l=1 and r=2, for which a_1 + a_2 = 1+2=3 is not divisible by r-l+1=2.in the third example, for l=1 and r=3 the sum a_1+a_2+a_3 is always 6, which is divisible by 3. | 3
1
2
3
| 1 1 2 -1 | 1 second | 256 megabytes | ['constructive algorithms', '*900'] |
A. Politicstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a debate club with n members, including yourself (member 1), there are k opinions to be discussed in sequence. During each discussion, members express their agreement or disagreement with the opinion. Let's define Y as the number of members who agree and N as the number of members who disagree. After each discussion, members leave the club based on the following criteria: If more members agree than disagree (Y > N), all members who disagreed leave the club. If more members disagree than agree (Y < N), all members who agreed leave the club. If there is a tie (Y = N), all members leave the club. As the club president, your goal is to stay in the club and maximize the number of members remaining after the meeting. You have access to each member's stance on all k opinions before the meeting starts, and you can expel any number of members (excluding yourself) before the meeting begins.Determine the maximum number of members, including yourself, who can remain in the club after the meeting. You don't need to provide the specific expulsion strategy but only the maximum number of members that can stay. Ensure that you remain in the club after the meeting as well.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). Description of the test cases follows.The first line of each test case contains two positive integers n and k (1 \le n, k \le 100) — the number of members and the number of discussions.The i-th of the following n lines contains a string t_i of length k. The j-th character in the string t_i indicates whether the i-th member agrees or disagrees with the j-th opinion if they are present during that discussion. A "+" symbol means the member agrees, while a "-" symbol means the member disagrees.It is guaranteed that the sum of n \cdot k over all test cases does not exceed 5 \cdot 10^4.OutputFor each test case, output the maximum number of members, including yourself, who can remain in the club after the meeting.ExampleInput
52 2+++-1 3+-+4 1+--+5 4+++++--+++-++-++++++4 2++-----+Output
1
1
2
2
1
NoteFor convenience, we will analyze the examples based on who actually attended the meeting (i. e. was not expelled) rather than who was expelled.Example 1:Only the first member could have attended the meeting, otherwise both members would have left after the second opinion is discussed.Example 2:There is only a single member that attends the meeting and stays till the end.Example 3:The club has 4 members and only one opinion will be discussed during the meeting. Let's analyze the possible outcomes based on the participants in the meeting: If only the first member attends, they'll be the only one left after the meeting. If the first member attends with the second or third member, they will be a tie in the discussion, making them both leave. If the first member attends with the second and third members, the first member will be in the minority and will leave after the discussion, which contradicts the statement. If the first and fourth members attend, they will agree during the discussion and both remain till the end. If the first, second, and fourth members attend, the second member will be in the minority during the discussion, and only the first and fourth members will remain at the end. The same happens if the second member is replaced by the third member. If all four members attend, there will be a tie during the discussion, making everyone leave. The maximum number of members remaining after the meeting is 2.Example 4:The club has 5 members and 4 opinions will be discussed during the meeting.One way to achieve the maximum number of members is if only the first, third, and fifth members attend the meeting. In this case, they all agree during the first two discussions, after which the third member is in the minority during the third discussion. Then, the first and fifth members agree in the last discussion, and those two members stay till the end of the meeting.Example 5:The club has 4 members and 2 opinions will be discussed.If the first three members attend the meeting, the first member will be in the minority during the first discussion and will leave the club. After that, the second and third members will both disagree with the second opinion, and they both will stay till the end of the meeting. In this way, there will be 2 members left after the meeting, but it is an invalid outcome, as it forces the first member to leave. Therefore, the maximum number of 1 member is achieved if only the first member attends the meeting. | 52 2+++-1 3+-+4 1+--+5 4+++++--+++-++-++++++4 2++-----+ | 1 1 2 2 1 | 1 second | 256 megabytes | ['greedy', 'implementation', '*800'] |
F. Entangled Substringstime limit per test2 secondsmemory limit per test256 mebibytesinputstandard inputoutputstandard outputQuantum entanglement is when two particles link together in a certain way no matter how far apart they are in space.You are given a string s. A pair of its non-empty substrings (a, b) is called entangled if there is a (possibly empty) link string c such that: Every occurrence of a in s is immediately followed by cb; Every occurrence of b in s is immediately preceded by ac. In other words, a and b occur in s only as substrings of acb. Compute the total number of entangled pairs of substrings of s.A string a is a substring of a string b if a can be obtained from b by the deletion of several (possibly zero or all) characters from the beginning and several (possibly zero or all) characters from the end.InputThe first and only line contains a string s of lowercase English letters (1 \leq |s| \leq 10^5) — the string for which you should count pairs of entangled substrings.OutputOutput a single integer, the number of entangled pairs of substrings of s.ExamplesInput
abba
Output
1
Input
abacaba
Output
0
Input
abcabcabcabc
Output
5
Input
adamant
Output
82
NoteIn the first example, the only entangled pair is (ab,ba). For this pair, the corresponding link string c is empty, as they only occur as substrings of the whole string abba, which doesn't have any characters between ab and ba.In the second example, there are no entangled pairs.In the third example, the entangled pairs are (a,b), (b,c), (a,c), (a,bc), and (ab,c). For most pairs, the corresponding link string c is empty, except for the pair (a,c), for which the link string c is b, as a and c only occur as substrings of the string abc. | abba
| 1 | 2 seconds | 256 mebibytes | ['string suffix structures', 'strings', '*3500'] |
E. Half-sumtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given a multiset of non-negative integers \{a_1, a_2, \dots, a_n\}.In one step you take two elements x and y of the multiset, remove them and insert their mean value \frac{x + y}{2} back into the multiset.You repeat the step described above until you are left with only two numbers A and B. What is the maximum possible value of their absolute difference |A-B|?Since the answer is not an integer number, output it modulo 10^9+7.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 10^6) — the size of the multiset.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — the elements of the multiset.It is guaranteed that the sum of n over all test cases does not exceed 10^6.OutputFor each test case, output a single integer, the answer to the problem modulo 10^9+7.Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output an integer x such that 0 \le x < M and x \cdot q \equiv p \pmod{M}.ExampleInput
527 341 2 10 1131 2 3664 32 64 16 64 041 1 1 1Output
4
9
500000005
59
0
NoteIn the first case, you can't do any operations, so the answer is |7-3|=4.In the second case, one of the optimal sequence of operations: Substitute 1 and 2 with 1.5; Substitute 10 and 11 with 10.5; The difference between 1.5 and 10.5 is 9. In the third case, the exact answer is \frac{3}{2}, and 500\,000\,005 \cdot 2 \equiv 3 \pmod{10^9+7}. | 527 341 2 10 1131 2 3664 32 64 16 64 041 1 1 1 | 4 9 500000005 59 0 | 4 seconds | 256 megabytes | ['brute force', 'divide and conquer', 'greedy', '*3400'] |
D. Toy Machinetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a toy machine with toys arranged in two rows of n cells each (n is odd). Initial state for n=9. Initially, n-2 toys are placed in the non-corner cells of the top row. The bottom row is initially empty, and its leftmost, rightmost, and central cells are blocked. There are 4 buttons to control the toy machine: left, right, up, and down marked by the letters L, R, U, and D correspondingly.When pressing L, R, U, or D, all the toys will be moved simultaneously in the corresponding direction and will only stop if they push into another toy, the wall or a blocked cell. Your goal is to move the k-th toy into the leftmost cell of the top row. The toys are numbered from 1 to n-2 from left to right. Given n and k, find a solution that uses at most 1\,000\,000 button presses.To test out the toy machine, a web page is available that lets you play the game in real time. InputThe first and only line contains two integers, n and k (5 \le n \le 100\,000, n is odd, 1 \le k \le n-2) — the number of cells in a row, and the index of the toy that has to be moved to the leftmost cell of the top row.OutputOn a single line, output a description of the button presses as a string of at most 1\,000\,000 characters. The string should only contain the characters L, R, U, and D. The i-th character in the string is the i-th button that is pressed. After all the button presses are performed, the k-th toy should be in the leftmost cell of the top row.If there are multiple solutions, print any. The number of button presses does not have to be minimized.ExamplesInput
5 1
Output
RDL
Input
7 2
Output
RDL
NoteIn the first example, there will be 5-2 = 3 toys. The first toy needs to end up in the leftmost cell of the top row. The moves RDL will achieve this, see the picture for a better understanding. Another possible solution would be to do one button press L. Visualization of the moves for the first example. | 5 1
| RDL | 1 second | 256 megabytes | ['constructive algorithms', 'games', 'implementation', '*2700'] |
C. Similar Polynomialstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA polynomial A(x) of degree d is an expression of the form A(x) = a_0 + a_1 x + a_2 x^2 + \dots + a_d x^d, where a_i are integers, and a_d \neq 0. Two polynomials A(x) and B(x) are called similar if there is an integer s such that for any integer x it holds that B(x) \equiv A(x+s) \pmod{10^9+7}. For two similar polynomials A(x) and B(x) of degree d, you're given their values in the points x=0,1,\dots, d modulo 10^9+7.Find a value s such that B(x) \equiv A(x+s) \pmod{10^9+7} for all integers x.InputThe first line contains a single integer d (1 \le d \le 2\,500\,000).The second line contains d+1 integers A(0), A(1), \ldots, A(d) (0 \le A(i) < 10^9+7) — the values of the polynomial A(x).The third line contains d+1 integers B(0), B(1), \ldots, B(d) (0 \le B(i) < 10^9+7) — the values of the polynomial B(x).It is guaranteed that A(x) and B(x) are similar and that the leading coefficients (i.e., the coefficients in front of x^d) of A(x) and B(x) are not divisible by 10^9+7.OutputPrint a single integer s (0 \leq s < 10^9+7) such that B(x) \equiv A(x+s) \pmod{10^9+7} for all integers x.If there are multiple solutions, print any.ExamplesInput
1
1000000006 0
2 3
Output
3
Input
2
1 4 9
100 121 144
Output
9
NoteIn the first example, A(x) \equiv x-1 \pmod{10^9+7} and B(x)\equiv x+2 \pmod{10^9+7}. They're similar because B(x) \equiv A(x+3) \pmod{10^9+7}.In the second example, A(x) \equiv (x+1)^2 \pmod{10^9+7} and B(x) \equiv (x+10)^2 \pmod{10^9+7}, hence B(x) \equiv A(x+9) \pmod{10^9+7}. | 1
1000000006 0
2 3
| 3 | 4 seconds | 256 megabytes | ['combinatorics', 'math', '*2400'] |
B. Fish Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a simple undirected graph with n nodes and m edges. Note that the graph is not necessarily connected. The nodes are labeled from 1 to n.We define a graph to be a Fish Graph if it contains a simple cycle with a special node u belonging to the cycle. Apart from the edges in the cycle, the graph should have exactly 2 extra edges. Both edges should connect to node u, but they should not be connected to any other node of the cycle. Determine if the graph contains a subgraph that is a Fish Graph, and if so, find any such subgraph.In this problem, we define a subgraph as a graph obtained by taking any subset of the edges of the original graph. Visualization of example 1. The red edges form one possible subgraph that is a Fish Graph. InputThe first line of input contains the integer t (1 \leq t \leq 1000), the number of test cases. The description of test cases follows.The first line of each test case contains two integers, n and m (1 \le n, m \le 2\,000) — the number of nodes and the number of edges.Each of the next m lines contains the description of an edge. Each line contains two integers u_i and v_i (1 \leq u_i, v_i \leq n, u_i\neq v_i) — an edge connects node u_i to node v_i.It is guaranteed that no two edges connect the same unordered pair of nodes.Furthermore, it is guaranteed that the sum of n and the sum of m over all test cases both do not exceed 2\,000.OutputFor each testcase, output "YES" if the graph contains a subgraph that is a Fish Graph, otherwise print "NO". If the answer is "YES", on the following lines output a description of the subgraph.The first line of the description contains one integer k — the number of edges of the subgraph. On the next k lines, output the edges of the chosen subgraph. Each of the k lines should contains two integers u and v (1\le u, v\le n, u\neq v) — the edge between u and v belongs to the subgraph. The order in which u and v are printed does not matter, as long as the two nodes are connected by an edge in the original graph. The order in which you print the edges does not matter, as long as the resulting subgraph is a fish graph.If there are multiple solutions, print any.ExampleInput
37 81 22 33 44 14 54 64 26 77 76 71 22 33 44 11 33 54 41 33 44 11 2Output
YES
6
5 4
6 4
4 3
1 4
2 1
3 2
YES
5
5 3
2 3
3 1
4 3
1 4
NO
NoteIn the first example, a possible valid subgraph contains the cycle 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1. The special node of this cycle is node 4. The two extra edges 4 - 5 and 4 - 6 are both connected to 4, completing the Fish Graph.In the second example, a possible valid subgraph contains the cycle 1 \rightarrow 3 \rightarrow 4 \rightarrow 1. The special node of this cycle is node 3. The two extra edges 3 - 2 and 3 - 5 are both connected to 3, completing the Fish Graph.In the last example, it can be proven that there is no valid subgraph. | 37 81 22 33 44 14 54 64 26 77 76 71 22 33 44 11 33 54 41 33 44 11 2 | YES 6 5 4 6 4 4 3 1 4 2 1 3 2 YES 5 5 3 2 3 3 1 4 3 1 4 NO | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'dfs and similar', 'graphs', '*1900'] |
A. Almost Increasing Subsequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence is almost-increasing if it does not contain three consecutive elements x, y, z such that x\ge y\ge z.You are given an array a_1, a_2, \dots, a_n and q queries.Each query consists of two integers 1\le l\le r\le n. For each query, find the length of the longest almost-increasing subsequence of the subarray a_l, a_{l+1}, \dots, a_r. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements.InputThe first line of input contains two integers, n and q (1 \leq n, q \leq 200\,000) — the length of the array a and the number of queries.The second line contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^9) — the values of the array a.Each of the next q lines contains the description of a query. Each line contains two integers l and r (1 \leq l \leq r \leq n) — the query is about the subarray a_l, a_{l+1}, \dots, a_r.OutputFor each of the q queries, print a line containing the length of the longest almost-increasing subsequence of the subarray a_l, a_{l+1}, \dots, a_r.ExampleInput
9 8
1 2 4 3 3 5 6 2 1
1 3
1 4
2 5
6 6
3 7
7 8
1 8
8 8
Output
3
4
3
1
4
2
7
1
NoteIn the first query, the subarray is a_1, a_2, a_3 = [1,2,4]. The whole subarray is almost-increasing, so the answer is 3.In the second query, the subarray is a_1, a_2, a_3,a_4 = [1,2,4,3]. The whole subarray is a almost-increasing, because there are no three consecutive elements such that x \geq y \geq z. So the answer is 4.In the third query, the subarray is a_2, a_3, a_4, a_5 = [2, 4, 3, 3]. The whole subarray is not almost-increasing, because the last three elements satisfy 4 \geq 3 \geq 3. An almost-increasing subsequence of length 3 can be found (for example taking a_2,a_3,a_5 = [2,4,3] ). So the answer is 3. | 9 8
1 2 4 3 3 5 6 2 1
1 3
1 4
2 5
6 6
3 7
7 8
1 8
8 8
| 3 4 3 1 4 2 7 1 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'greedy', '*1500'] |
B. Grid Reconstructiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a 2 \times n grid, where n is an even integer. You may place the integers 1, 2, \ldots, 2n on the grid, using each integer exactly once.A path is a sequence of cells achieved by starting at (1, 1), then repeatedly walking either downwards or to the right, and stopping when (2, n) is reached. The path should not extend beyond the grid.The cost of a path is the alternating sum of the numbers written on the cells in a path. That is, let the numbers written on the cells be a_1, a_2, \ldots, a_k (in the order that it is visited), the cost of the path is a_1 - a_2 + a_3 - a_4 + \ldots = \sum_{i=1}^k a_i \cdot (-1)^{i+1}.Construct a way to place the integers 1, 2, \ldots, 2n on the grid, such that the minimum cost over all paths from (1, 1) to (2, n) is maximized. If there are multiple such grids that result in the maximum value, output any of them.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases. The description of test cases follows.The first and the only line of each test case contains a single integer n (2 \leq n \leq 10^5, n is even) — the number of the columns in the grid.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output 2 lines, each containing n integers — the desired grid. If there are multiple solutions, output any of them.ExampleInput
3246Output
3 2
1 4
8 2 6 4
1 5 3 7
11 5 9 1 7 3
6 10 2 8 4 12
NoteIn the first test case, there are only two paths from cell (1, 1) to cell (2, 2). Their costs are 3-1+4=6 and 3-2+4=5. Then the minimum cost is 5, which is the maximum possible value.In the second test case, there are four paths from cell (1, 1) to cell (2, 4). Their costs are 8-1+5-3+7=16, 8-2+5-3+7=15, 8-2+6-3+7=16, and 8-2+6-4+7=15. Then the minimum value is 15, which is the maximum possible value. | 3246 | 3 2 1 4 8 2 6 4 1 5 3 7 11 5 9 1 7 3 6 10 2 8 4 12 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*1000'] |
A. Ian Visits Marytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIan and Mary are frogs living on lattice points of the Cartesian coordinate plane, with Ian living on (0,0) and Mary living on (a,b). Ian would like to visit Mary by jumping around the Cartesian coordinate plane. Every second, he jumps from his current position (x_p, y_p) to another lattice point (x_q, y_q), such that no lattice point other than (x_p, y_p) and (x_q, y_q) lies on the segment between point (x_p, y_p) and point (x_q, y_q). As Ian wants to meet Mary as soon as possible, he wants to jump towards point (a,b) using at most 2 jumps. Unfortunately, Ian is not good at maths. Can you help him?A lattice point is defined as a point with both the x-coordinate and y-coordinate being integers.InputThe first line contains a single integer t (1 \le t \le 500) — the number of test cases. The description of test cases follows.The first and only line of each test case contains two integers a and b (1\le a,b\le 10^9) — the coordinates of the lattice point where Mary lives.OutputFor each test case, print an integer n (1 \le n \le 2) on the first line, denoting the number of jumps Ian uses in order to meet Mary. Note that you do not need to minimize the number of jumps.On the i-th line of the next n lines, print two integers 0 \le x_i,y_i \le 10^9 separated by a space, denoting Ian's location (x_i,y_i) after the i-th jump. x_n = a, y_n = b must hold.Ian's initial location and his locations after each of the n jumps need not be distinct.If there are multiple solutions, output any.ExampleInput
83 44 43 62 21 17 32022 20231000000000 1000000000Output
1
3 4
2
3 2
4 4
2
5 3
3 6
2
1 0
2 2
1
1 1
1
7 3
1
2022 2023
2
69420420 469696969
1000000000 1000000000
NoteIn the first test case:(0,0) \to (3,4)In the second test case:(0,0) \to (3,2) \to (4,4)In the third test case:(0,0) \to (5,3) \to (3,6) | 83 44 43 62 21 17 32022 20231000000000 1000000000 | 1 3 4 2 3 2 4 4 2 5 3 3 6 2 1 0 2 2 1 1 1 1 7 3 1 2022 2023 2 69420420 469696969 1000000000 1000000000 | 1 second | 256 megabytes | ['constructive algorithms', 'geometry', 'number theory', '*800'] |
F. OH NO1 (-2-3-4)time limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph with n vertices and 3m edges. The graph may contain multi-edges, but does not contain self-loops. The graph satisfies the following property: the given edges can be divided into m groups of 3, such that each group is a triangle.A triangle is defined as three edges (a,b), (b,c) and (c,a) for some three distinct vertices a,b,c (1 \leq a,b,c \leq n).Initially, each vertex v has a non-negative integer weight a_v. For every edge (u,v) in the graph, you should perform the following operation exactly once: Choose an integer x between 1 and 4. Then increase both a_u and a_v by x. After performing all operations, the following requirement should be satisfied: if u and v are connected by an edge, then a_u \ne a_v.It can be proven this is always possible under the constraints of the task. Output a way to do so, by outputting the choice of x for each edge. It is easy to see that the order of operations does not matter. If there are multiple valid answers, output any. InputThe first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers n and m (3 \le n \le 10^6, 1 \le m \le 4 \cdot 10^5) — denoting the graph have n vertices and 3m edges.The second line of each test case contains n integers a_1,a_2,\ldots,a_n (0 \leq a_i \leq 10^6) — the initial weights of each vertex. Then m lines follow. The i-th line contains three integers a_i, b_i, c_i (1 \leq a_i < b_i < c_i \leq n) — denotes that three edges (a_i,b_i), (b_i,c_i) and (c_i,a_i). Note that the graph may contain multi-edges: a pair (x,y) may appear in multiple triangles.It is guaranteed that the sum of n over all test cases does not exceed 10^6 and the sum of m over all test cases does not exceed 4 \cdot 10^5.OutputFor each test case, output m lines of 3 integers each.The i-th line should contains three integers e_{ab},e_{bc},e_{ca} (1 \leq e_{ab}, e_{bc} , e_{ca} \leq 4), denoting the choice of value x for edges (a_i, b_i), (b_i,c_i) and (c_i, a_i) respectively.ExampleInput
44 10 0 0 01 2 35 20 0 0 0 01 2 31 4 54 43 4 5 61 2 31 2 41 3 42 3 45 40 1000000 412 412 4121 2 31 4 52 4 53 4 5Output
2 1 3
2 3 3
4 3 3
3 1 2
2 2 3
2 3 4
3 1 1
2 3 4
1 2 4
4 4 3
4 1 1NoteIn the first test case, the initial weights are [0,0,0,0]. We have added values as follows: Added 2 to vertices 1 and 2 Added 1 to vertices 2 and 3 Added 3 to vertices 3 and 1 The final weights are [5,3,4,0]. The output is valid because a_1 \neq a_2, a_1 \neq a_3, a_2 \neq a_3, and that all chosen values are between 1 and 4.In the second test case, the initial weights are [0,0,0,0,0]. The weights after the operations are [12,5,6,7,6]. The output is valid because a_1 \neq a_2, a_1 \neq a_3, a_2 \neq a_3, and that a_1 \neq a_4, a_1 \neq a_5, a_4 \neq a_5, and that all chosen values are between 1 and 4.In the third test case, the initial weights are [3,4,5,6]. The weights after the operations are [19,16,17,20], and all final weights are distinct, which means no two adjacent vertices have the same weight. | 44 10 0 0 01 2 35 20 0 0 0 01 2 31 4 54 43 4 5 61 2 31 2 41 3 42 3 45 40 1000000 412 412 4121 2 31 4 52 4 53 4 5 | 2 1 3 2 3 3 4 3 3 3 1 2 2 2 3 2 3 4 3 1 1 2 3 4 1 2 4 4 4 3 4 1 1 | 4 seconds | 512 megabytes | ['constructive algorithms', 'graphs', 'math', '*3500'] |
E. Bosco and Particletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBosco is studying the behaviour of particles. He decided to investigate on the peculiar behaviour of the so-called "four-one-two" particle. He does the following:There is a line of length n+1, where the topmost point is position 0 and bottommost is position n+1. The particle is initially (at time t=0) at position 0 and heading downwards. The particle moves at the speed of 1 unit per second. There are n oscillators at positions 1,2,\ldots,n.Each oscillator can be described by a binary string. The initial state of each oscillator is the first character of its binary string. When the particle hits with an oscillator, the particle reverses its direction if its current state is \texttt{1} and continues to move at the same direction if its current state is \texttt{0}, and that oscillator moves on to the next state (the next state of the last state is defined as the first state). Additionally, the particle always reverses its direction when it is at position 0 or n+1 at time t > 0.Bosco would like to know the cycle length of the movement of particle. The cycle length is defined as the minimum value of c such that for any time t \ge 0, the position of the particle at time t is same as the position of the particle at time t+c. It can be proved that such value c always exists. As he realises the answer might be too large, he asks you to output your answer modulo 998244353.InputThe first line contains an integer n (1\le n\le10^6) — the number of oscillators.The i-th of the next n line contains a binary string s_i (1\le\left|s_i\right|\le10^6) — the binary string, that contains only characters \texttt{0} and \texttt{1}, describing the oscillator at position i.It is guaranteed that the sum of all |s_i| does not exceed 10^6.OutputOutput a single integer integer — the cycle length of the movement of the particle, modulo 998244353.ExamplesInput
1
00
Output
4
Input
2
01
010
Output
16
Input
4
0101
000
1
01
Output
12
Input
4
01010
0001
11
0001
Output
120
NoteIn the first sample, the only oscillator at position 1 always has state \texttt{0}. At time moments 0,1,2,3 positions the particle are 0,1,2,1 respectively. Then the same positions will be repeated, so c=4.Animation for the second sample: here or a smoother animation. | 1
00
| 4 | 2 seconds | 256 megabytes | ['dp', 'math', 'number theory', 'strings', '*3100'] |
D. XOR Countingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven two positive integers n and m. Find the sum of all possible values of a_1\bigoplus a_2\bigoplus\ldots\bigoplus a_m, where a_1,a_2,\ldots,a_m are non-negative integers such that a_1+a_2+\ldots+a_m=n.Note that all possible values a_1\bigoplus a_2\bigoplus\ldots\bigoplus a_m should be counted in the sum exactly once.As the answer may be too large, output your answer modulo 998244353.Here, \bigoplus denotes the bitwise XOR operation.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows.The first and only line of each test case contains two integers n and m (0\le n\le 10^{18}, 1\le m\le 10^5) — the sum and the number of integers in the set, respectively.OutputFor each test case, output the sum of all possible values of a_1\bigoplus a_2\bigoplus\ldots\bigoplus a_m among all non-negative integers a_1,a_2,\ldots,a_m with a_1+a_2+\ldots+a_m=n. As the answer may be too large, output your answer modulo 998244353.ExampleInput
769 15 20 10420 6912 2673 341000000000000000000 10Output
69
6
0
44310
42
1369
216734648
NoteFor the first test case, we must have a_1=69, so it's the only possible value of a_1, therefore our answer is 69.For the second test case, (a_1,a_2) can be (0,5), (1,4), (2,3), (3,2), (4,1) or (5,0), in which a_1\bigoplus a_2 are 5,5,1,1,5,5 respectively. So a_1\bigoplus a_2 can be 1 or 5, therefore our answer is 1+5=6.For the third test case, a_1,a_2,\ldots,a_{10} must be all 0, so a_1\bigoplus a_2\bigoplus\ldots\bigoplus a_{10}=0. Therefore our answer is 0. | 769 15 20 10420 6912 2673 341000000000000000000 10 | 69 6 0 44310 42 1369 216734648 | 2 seconds | 256 megabytes | ['bitmasks', 'combinatorics', 'dp', 'math', '*2600'] |
C. Betweentime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n, as well as m pairs of integers (a_i,b_i), where 1\leq a_i , b_i \leq n, a_i \ne b_i.You want to construct a sequence satisfying the following requirements: All elements in the sequence are integers between 1 and n. There is exactly one element with value 1 in the sequence. For each i (1 \le i \le m), between any two elements (on different positions) in the sequence with value a_i, there is at least one element with value b_i. The sequence constructed has the maximum length among all possible sequences satisfying the above properties. Sometimes, it is possible that such a sequence can be arbitrarily long, in which case you should output "INFINITE". Otherwise, you should output "FINITE" and the sequence itself. If there are multiple possible constructions that yield the maximum length, output any.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 300) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers n and m (1 \le n \le 1500, 0 \le m \le 5000) — the maximum possible value of the element of the sequence and the number of pairs.The i-th of the next m lines contain two integers a_i and b_i (1 \le a_i , b_i \le n, a_i \ne b_i).(a_i, b_i) \ne (a_j, b_j) for all 1 \le i < j \le m.It is guaranteed that sum of n over all test cases doesn't exceed 1500 and the sum of m over all test cases doesn't exceed 5000.OutputFor each test case, on the first line output "INFINITE" if the sequence can be arbitrarily long, and "FINITE" otherwise.If you have outputted "FINITE", then your output should be followed by 2 lines.The first line contains an integer s, the maximum length of the sequence.The second line contains s integers, each are between 1 and n inclusive, representing the elements of the sequence.If there are multiple sequences with the maximum length, output any of them.It can be shown that, for all test cases with answer "FINITE", then under the constraints, the maximum possible sum of sequence lengths of those test cases does not exceed 2\cdot10^6.ExampleInput
53 23 12 11 02 02 21 22 15 52 13 14 24 55 1Output
FINITE
5
2 3 1 2 3
FINITE
1
1
INFINITE
FINITE
3
2 1 2
FINITE
10
4 2 3 5 4 1 3 2 5 4 NoteIn the first test case, there is an element 1 between two elements with value 3 and an element 1 between two elements with value 2. It can be shown that there is no suitable sequences of length more than 5.In the second case, [1] is the only possible sequence because there should be exactly one element with value 1 in the sequence.In the third case, we can get an arbitrary long sequence like 1, 2, 2, 2, \ldots. | 53 23 12 11 02 02 21 22 15 52 13 14 24 55 1 | FINITE 5 2 3 1 2 3 FINITE 1 1 INFINITE FINITE 3 2 1 2 FINITE 10 4 2 3 5 4 1 3 2 5 4 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', 'greedy', '*2200'] |
B. Sum Graphtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.There is a hidden permutation p_1, p_2, \dots, p_n. Consider an undirected graph with n nodes only with no edges. You can make two types of queries: Specify an integer x satisfying 2 \le x \le 2n. For all integers i (1 \le i \le n) such that 1 \le x-i \le n, an edge between node i and node x-i will be added. Query the number of edges in the shortest path between node p_i and node p_j. As the answer to this question you will get the number of edges in the shortest path if such a path exists, or -1 if there is no such path. Note that you can make both types of queries in any order.Within 2n queries (including type 1 and type 2), guess two possible permutations, at least one of which is p_1, p_2, \dots, p_n. You get accepted if at least one of the permutations is correct. You are allowed to guess the same permutation twice.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).InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 10^3) — the length of the permutation.It is guaranteed that the sum of n over all test cases does not exceed 10^3.InteractionThe interaction for each test case begins by reading the integer n.Then, make at most 2n queries: If you want to make a type 1 query, output "+ x". x must be an integer between 2 and 2n inclusive. After doing that read 1 or -2. If you read 1 your query was valid, otherwise it was invalid or you exceed the limit of queries, and your program must terminate immediately to receive a Wrong Answer verdict. If you want to make a type 2 query, output "? i j". i and j must be integers between 1 and n inclusive. After that, read in a single integer r (-1 \le r \le n) — the answer to your query. If you receive the integer −2 instead of an answer, it means your program has made an invalid query, or has exceeded the limit of queries. Your program must terminate immediately to receive a Wrong Answer verdict. At any point of the interaction, if you want to guess two permutations, output "! p_{1,1} p_{1,2} \dots p_{1,n} p_{2,1} p_{2,2} \dots p_{2,n}". Note that you should output the two permutations on the same line, and no exclamation mark is needed to separate the two permutations. After doing that read 1 or -2. If you read 1 your answer was correct, otherwise it was incorrect and your program must terminate immediately to receive a Wrong Answer verdict. After that, move on to the next test case, or terminate the program if there are none. Note that reporting the answer does not count as a query.Note that even if you output a correct permutation, the second permutation should be a permutation and not an arbitrary array.At any point, if you continue interaction after reading in the integer -2, you can get an arbitrary verdict because your solution will continue to read from a closed stream.After printing a query or the answer do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.Interactor is non-adaptive. This means that all permutations are fixed before the interaction starts.HacksTo make a hack, use the following format.The first line should contain a single integer t (1 \le t \le 100) — the number of test cases.The first line of each test case should contain a single integer n (2 \le n \le 10^3) — the length of the permutation.The second line of each test case should contain n distinct integers p_1, p_2, \ldots, p_n (1 \le p_i \le n) — the hidden permutation.The sum of n over all test cases should not exceed 10^3.ExampleInput
2
6
1
1
1
1
1
2
-1
1
2
1
Output
+ 12
+ 2
+ 3
? 1 3
+ 5
? 1 5
? 4 5
! 1 4 2 5 3 6 1 2 3 4 5 6
! 1 2 2 1
NoteIn the first test case, n=6 and the hidden permutation p = [1,4,2,5,3,6].Firstly, make a type 1 query on x=12, 2, 3 respectively. This adds four edges to the graph in total: An edge that connects node 6 and node 6. An edge that connects node 1 and node 1. An edge that connects node 1 and node 2. An edge that connects node 2 and node 1. Since all of these queries are valid, the interactor returns 1 after each of them.Then, query the number of edges in the shortest path between node p_1 = 1 and p_3 = 2, which is equal to 1.Then, make a type 1 query on x=5. This adds four edges to the graph in total: An edge that connects node 1 and node 4. An edge that connects node 2 and node 3. An edge that connects node 3 and node 2. An edge that connects node 4 and node 1. Since this query is valid, the interactor returns 1.Then, query the number of edges in the shortest path between node p_1 = 1 and p_5 = 3, which is equal to 2.Then, query the number of edges in the shortest path between node p_4 = 5 and p_5 = 3. Such a path doesn't exist, therefore the interactor returns -1.Afterwards, due to some magic, two possible permutations that can be p are determined: the first permutation is [1,4,2,5,3,6] and the second permutation is [1,2,3,4,5,6]. Since the first permutation is equal to the hidden permutation, this test case is solved correctly. In total, 7 queries are used, which is within the limit of 2 \cdot 6 = 12 queries.Since the answer is correct, the interactor returns 1.In the second test case, n=2 and the hidden permutation is p = [2,1].Since there are only 2! = 2 possible permutations, no queries are needed. It is sufficient to just output the two permutations, [1,2] and [2,1]. In total, 0 queries are used, which is within the limit of 2 \cdot 2 = 4 queries.Since the answer is correct, the interactor returns 1. | 2
6
1
1
1
1
1
2
-1
1
2
1
| + 12 + 2 + 3 ? 1 3 + 5 ? 1 5 ? 4 5 ! 1 4 2 5 3 6 1 2 3 4 5 6 ! 1 2 2 1 | 3 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'graphs', 'implementation', 'interactive', 'shortest paths', 'trees', '*2000'] |
A. Ian and Array Sortingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo thank Ian, Mary gifted an array a of length n to Ian. To make himself look smart, he wants to make the array in non-decreasing order by doing the following finitely many times: he chooses two adjacent elements a_i and a_{i+1} (1\le i\le n-1), and increases both of them by 1 or decreases both of them by 1. Note that, the elements of the array can become negative.As a smart person, you notice that, there are some arrays such that Ian cannot make it become non-decreasing order! Therefore, you decide to write a program to determine if it is possible to make the array in non-decreasing order.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. The description of test cases follows.The first line of each test case consists of a single integer n (2\le n\le 3\cdot10^5) — the number of elements in the array.The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1\le a_i\le 10^9) — the elements of the array a.It is guaranteed that the sum of n over all test cases does not exceed 3\cdot10^5. OutputFor each test case, output "YES" if there exists a sequence of operations which make the array non-decreasing, else output "NO".You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).ExampleInput
531 3 222 141 3 5 742 1 4 355 4 3 2 1Output
YES
NO
YES
NO
YES
NoteFor the first test case, we can increase a_2 and a_3 both by 1. The array is now [1, 4, 3].Then we can decrease a_1 and a_2 both by 1. The array is now [0, 3, 3], which is sorted in non-decreasing order. So the answer is "YES".For the second test case, no matter how Ian perform the operations, a_1 will always be larger than a_2. So the answer is "NO" and Ian cannot pretend to be smart.For the third test case, the array is already in non-decreasing order, so Ian does not need to do anything. | 531 3 222 141 3 5 742 1 4 355 4 3 2 1 | YES NO YES NO YES | 1 second | 256 megabytes | ['greedy', 'math', '*1300'] |
F. Communication Towerstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n communication towers, numbered from 1 to n, and m bidirectional wires between them. Each tower has a certain set of frequencies that it accepts, the i-th of them accepts frequencies from l_i to r_i.Let's say that a tower b is accessible from a tower a, if there exists a frequency x and a sequence of towers a=v_1, v_2, \dots, v_k=b, where consecutive towers in the sequence are directly connected by a wire, and each of them accepts frequency x. Note that accessibility is not transitive, i. e if b is accessible from a and c is accessible from b, then c may not be accessible from a.Your task is to determine the towers that are accessible from the 1-st tower.InputThe first line contains two integers n and m (1 \le n \le 2 \cdot 10^5; 0 \le m \le 4 \cdot 10^5) — the number of communication towers and the number of wires, respectively.Then n lines follows, the i-th of them contains two integers l_i and r_i (1 \le l_i \le r_i \le 2 \cdot 10^5) — the boundaries of the acceptable frequencies for the i-th tower.Then m lines follows, the i-th of them contains two integers v_i and u_i (1 \le v_i, u_i \le n; v_i \ne u_i) — the i-th wire that connects towers v_i and u_i. There are no two wires connecting the same pair of towers. OutputIn a single line, print distinct integers from 1 to n in ascending order — the indices of the communication towers that are accessible from the 1-st tower.ExamplesInput
6 5
3 5
1 2
2 4
2 3
3 3
4 6
1 3
6 1
3 5
3 6
2 3
Output
1 3 5 6 Input
3 1
2 3
1 4
1 1
1 3
Output
1 Input
5 5
1 3
2 3
2 2
3 5
2 4
1 2
2 3
3 4
4 1
4 5
Output
1 2 3 4 5 | 6 5
3 5
1 2
2 4
2 3
3 3
4 6
1 3
6 1
3 5
3 6
2 3
| 1 3 5 6 | 4 seconds | 512 megabytes | ['brute force', 'divide and conquer', 'dsu', '*2700'] |
E. Chain Chipstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph consisting of n vertices and n-1 edges. The i-th edge has weight a_i; it connects the vertices i and i+1.Initially, each vertex contains a chip. Each chip has an integer written on it; the integer written on the chip in the i-th vertex is i.In one operation, you can choose a chip (if there are multiple chips in a single vertex, you may choose any one of them) and move it along one of the edges of the graph. The cost of this operation is equal to the weight of the edge.The cost of the graph is the minimum cost of a sequence of such operations that meets the following condition: after all operations are performed, each vertex contains exactly one chip, and the integer on each chip is not equal to the index of the vertex where that chip is located. You are given q queries of the form: k x — change the weight of the k-th edge (the one which connects the vertices k and k+1) to x. After each query, print the cost of the graph. Note that you don't actually move any chips; when you compute the cost, the chips are on their initial positions.InputThe first line contains one integer n (2 \le n \le 2 \cdot 10^5).The second line contains n-1 integers a_1, a_2, \dots, a_{n-1} (1 \le a_i \le 10^9).The third line contains one integer q (1 \le q \le 2 \cdot 10^5).Then q lines follow. The i-th of them contains two integers k and x (1 \le k \le n-1; 1 \le x \le 10^9) for the i-th query.OutputFor each query, print one integer — the cost of the graph after the query is performed.ExampleInput
10
12 6 12 15 20 8 17 12 15
8
4 10
7 3
6 14
9 9
2 10
3 5
4 11
7 11
Output
126
108
120
108
112
98
98
114
| 10
12 6 12 15 20 8 17 12 15
8
4 10
7 3
6 14
9 9
2 10
3 5
4 11
7 11
| 126 108 120 108 112 98 98 114 | 3 seconds | 512 megabytes | ['data structures', 'dp', 'matrices', '*2300'] |
D. Balancing Weaponstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a job in a game studio that developed an online shooter, and your first big task is to help to balance weapons. The game has n weapons: the i-th gun has an integer fire rate f_i and an integer damage per bullet d_i. The i-th gun's total firepower is equal to p_i = f_i \cdot d_i.You have to modify the values d_i of some guns in such a way that the new values d_i will still be integers, and the firepower of all guns will become balanced. Given an integer k, the guns are said to be balanced if \max\limits_{1 \le i \le n}{p_i} - \min\limits_{1 \le i \le n}{p_i} \le k.Since gamers that play your game don't like big changes, you need to change the values d_i for the minimum possible number of guns. What is the minimum number of guns for which you have to change these values to make the guns balanced?Note that the new values d_i must be integers greater than 0.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 3000; 0 \le k \le 1500) — the number of guns to balance, and the maximum allowed gap between the most and the least powerful weapons.The second line contains n integers f_1, f_2, \dots, f_n (1 \le f_i \le 2000), where f_i is the fire rate of the i-th gun.The third line contains n integers d_1, d_2, \dots, d_n (1 \le d_i \le 10^9), where d_i is the damage per bullet of the i-th gun.It's guaranteed that the sum of n over all test cases doesn't exceed 3000.OutputFor each test case, print the minimum number of guns which damage d_i you have to change in order to make the guns balanced.Note that the new values d_i must be integers greater than 0.ExampleInput
54 26 3 13 71 2 1 23 2100 101 102100 99 985 01 12 4 4 312 1 3 3 42 501000 101000000000 13 51 19 1149 4 72Output
2
3
0
1
2
NoteIn the first test case, you can set d_1 = 2 and d_2 = 4. You'll get an array d = [2, 4, 1, 2], and the values of firepower will be p = [12, 12, 13, 14]. The guns are balanced, since 14 - 12 \le 2.In the second test case, you have to change the value d_i for all three guns. For example, you can set d = [5151, 5100, 5050].In the third test case, all guns are already balanced, so you don't have to change anything. | 54 26 3 13 71 2 1 23 2100 101 102100 99 985 01 12 4 4 312 1 3 3 42 501000 101000000000 13 51 19 1149 4 72 | 2 3 0 1 2 | 3 seconds | 256 megabytes | ['binary search', 'brute force', 'data structures', 'math', 'two pointers', '*2500'] |
C. Search in Paralleltime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSuppose you have n boxes. The i-th box contains infinitely many balls of color i. Sometimes you need to get a ball with some specific color; but you're too lazy to do it yourself.You have bought two robots to retrieve the balls for you. Now you have to program them. In order to program the robots, you have to construct two lists [a_1, a_2, \dots, a_k] and [b_1, b_2, \dots, b_{n-k}], where the list a represents the boxes assigned to the first robot, and the list b represents the boxes assigned to the second robot. Every integer from 1 to n must be present in exactly one of these lists.When you request a ball with color x, the robots work as follows. Each robot looks through the boxes that were assigned to that robot, in the order they appear in the list. The first robot spends s_1 seconds analyzing the contents of a box; the second robot spends s_2. As soon as one of the robots finds the box with balls of color x (and analyzes its contents), the search ends. The search time is the number of seconds from the beginning of the search until one of the robots finishes analyzing the contents of the x-th box. If a robot analyzes the contents of all boxes assigned to it, it stops searching.For example, suppose s_1 = 2, s_2 = 3, a = [4, 1, 5, 3, 7], b = [2, 6]. If you request a ball with color 3, the following happens: initially, the first robot starts analyzing the box 4, and the second robot starts analyzing the box 2; at the end of the 2-nd second, the first robot finishes analyzing the box 4. It is not the box you need, so the robot continues with the box 1; at the end of the 3-rd second, the second robot finishes analyzing the box 2. It is not the box you need, so the robot continues with the box 6; at the end of the 4-th second, the first robot finishes analyzing the box 1. It is not the box you need, so the robot continues with the box 5; at the end of the 6-th second, the first robot finishes analyzing the box 5. It is not the box you need, so the robot continues with the box 3. At the same time, the second robot finishes analyzing the box 6. It is not the box you need, and the second robot has analyzed all the boxes in its list, so that robot stops searching; at the end of the 8-th second, the first robot finishes analyzing the box 3. It is the box you need, so the search ends; so, the search time is 8 seconds. You know that you are going to request a ball of color 1 r_1 times, a ball of color 2 r_2 times, and so on. You want to construct the lists a and b for the robots in such a way that the total search time over all requests is the minimum possible.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 three integers n, s_1, s_2 (2 \le n \le 2 \cdot 10^5; 1 \le s_1, s_2 \le 10); the second line contains n integers r_1, r_2, \dots, r_n (1 \le r_i \le 10^6). Additional constraint on the input: the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print two lines. The first line should contain the list a, the second line — the list b. Each list has to be printed as follows: first, print the number of elements in it, and then the elements themselves.If there are multiple answers, you may print any of them.ExampleInput
37 3 18 6 4 4 4 1 75 1 101 1 1 1 18 1 14 5 6 8 1 7 3 2Output
2 5 6
5 1 7 2 4 3
5 4 3 5 2 1
0
4 4 2 7 5
4 6 3 1 8
| 37 3 18 6 4 4 4 1 75 1 101 1 1 1 18 1 14 5 6 8 1 7 3 2 | 2 5 6 5 1 7 2 4 3 5 4 3 5 2 1 0 4 4 2 7 5 4 6 3 1 8 | 2 seconds | 512 megabytes | ['constructive algorithms', 'greedy', 'sortings', '*1500'] |
B. Long Legstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA robot is placed in a cell (0, 0) of an infinite grid. This robot has adjustable length legs. Initially, its legs have length 1.Let the robot currently be in the cell (x, y) and have legs of length m. In one move, it can perform one of the following three actions: jump into the cell (x + m, y); jump into the cell (x, y + m); increase the length of the legs by 1, i. e. set it to m + 1. What's the smallest number of moves robot has to make to reach a cell (a, b)?InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.The only line of each test case contains two integers a and b (1 \le a, b \le 10^9) — the ending cell.OutputFor each test case, print a single integer — the smallest number of moves the robot is required to make to reach a cell (a, b) from a cell (0, 0).ExampleInput
31 11 68 4Output
2
5
6
NoteIn the first testcase, the robot can first jump to (0, 1), then to (1, 1). If it ever increases the length of its legs, it will only be able to jump past (1, 1).In the second testcase, the robot can jump to (1, 0), then increase the length of its length to 2 and jump three times to reach (1, 6).In the third testcase, the robot can increase the length of its legs three times to make it 4. Then jump to (0, 4). Then jump twice to reach (8, 4). | 31 11 68 4 | 2 5 6 | 2 seconds | 256 megabytes | ['brute force', 'math', '*1700'] |
A. Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Berland, there are two types of coins, having denominations of 2 and k burles.Your task is to determine whether it is possible to represent n burles in coins, i. e. whether there exist non-negative integers x and y such that 2 \cdot x + k \cdot y = n.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The only line of each test case contains two integers n and k (1 \le k \le n \le 10^{18}; k \ne 2).OutputFor each test case, print YES if it is possible to represent n burles in coins; otherwise, print NO. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).ExampleInput
45 36 17 48 8Output
YES
YES
NO
YES
NoteIn the first test case, you can take one coin with denomination 2 and one coin with denomination k = 3.In the second test case, you can take three coins with denomination 2. Alternatively, you can take six coins with denomination k = 1.In the third test case, there is no way to represent 7 burles.In the fourth test case, you can take one coin with denomination k = 8. | 45 36 17 48 8 | YES YES NO YES | 2 seconds | 256 megabytes | ['implementation', 'math', '*800'] |
J. Unmysterious Languagetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an unmysterious language. You should make a submission in this language, and the judge will read your submission to determine whether it is accepted.You can only submit in the Mysterious Language we have provided. You can view the judge's response by clicking the submission ID on the "My Submissions" page.ExampleInput
Output
| 1 second | 256 megabytes | ['*special problem', 'constructive algorithms', 'strings'] |
||
I. Mountain Climbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe first line of input contains t (1 \leq t \leq 25) — the number of test cases.The only line of each test case contains a single string s (1 \leq |s| \leq 100) consisting only of lowercase English letters.OutputFor each test case, print YES or NO.ExampleInput
23bigflashingclumpiunderpasspassundertranquilizingpoleandrejdumplingbocchiryonijikakitasingingsongsalperentoxicpiearibucketpotatoflamestormscarletsmaisakurajimamisakamikotoninfiasylveonpikachumewheniseearulhiiarulOutput
YES
NO
YES
YES
YES
NO
YES
NO
YES
YES
YES
YES
YES
YES
NO
NO
NO
YES
NO
NO
NO
NO
NO
| 23bigflashingclumpiunderpasspassundertranquilizingpoleandrejdumplingbocchiryonijikakitasingingsongsalperentoxicpiearibucketpotatoflamestormscarletsmaisakurajimamisakamikotoninfiasylveonpikachumewheniseearulhiiarul | YES NO YES YES YES NO YES NO YES YES YES YES YES YES NO NO NO YES NO NO NO NO NO | 1 second | 256 megabytes | ['*special problem'] |
H. Expected Twisttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.There is an array a_1, a_2, \dots, a_n of n integers hidden from you. Your task is to find the smallest element of the array.To do this, you can ask several queries. In each query, you can pick two integers l and r (1 \leq l \leq r \leq n). In return, you will be given the value of \max(a_l, a_{l+1}, \dots, a_r). In other words, you will be told the maximum value of the subarray from a_l to a_r.Find the minimum of the array. You can ask at most \mathbf{624} queries.It is guaranteed that the values a_1, a_2, \dots, a_n are chosen uniformly at random between 0 and 2^{32}-1 (inclusive).InteractionBegin the interaction by reading an integer n (1 \le n \le 10^4) on a separate line.To ask a query, print a line in the form \texttt{?}\;\;l\;\;r (1 \le l \le r \le n). Then you should read a single line containing the answer to your query.After you have determined the answer, print a line in the form \texttt{!}\;\;x where x is the minimum value.After printing a query do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages. Answer \texttt{-1} means that you made an invalid query. Exit immediately after receiving \texttt{-1} and you will see Wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.ExampleInput
3
1295320727
984617979
1295320727
167316954Output
? 1 3
? 1 1
? 2 2
? 3 3
! 167316954 | 3
1295320727
984617979
1295320727
167316954 | ? 1 3 ? 1 1 ? 2 2 ? 3 3 ! 167316954 | 3 seconds | 256 megabytes | ['*special problem', 'interactive'] |
G. Colour Visiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output ExampleInput
11RROutput
YES
| 11RR | YES | 1 second | 256 megabytes | ['*special problem', 'implementation'] |
E. Not a Geometry Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe only line of input contains three integers x, y, z (-1000 \le x, y, z \le 1000).OutputOutput one real number — the answer.Your answer is considered correct if its absolute or relative error does not exceed 10^6. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a-b|}{\max(1,|b|)} \le 10^6.ExamplesInput
1 1 1
Output
1.7320508075688772
Input
1 -2 -2
Output
21.727922061357855
Input
998 244 353
Output
-0.0006269592476489029
Input
0 0 0
Output
1792283455048516.3
| 1 1 1
| 1.7320508075688772 | 1 second | 256 megabytes | ['*special problem', '*special problem', 'constructive algorithms', 'geometry', 'math'] |
D. Trivial Conjecturetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputf(n) = \left\{ \begin{array}{ll} \frac{n}{2} & n \equiv 0 \pmod{2}\\ 3n+1 & n \equiv 1 \pmod{2}\\ \end{array} \right.Find an integer n so that none of the first k terms of the sequence n, f(n), f(f(n)), f(f(f(n))), \dots are equal to 1.InputThe only line contains an integer k (1 \leq k \leq \min(\textbf{[REDACTED]}, 10^{18})).OutputOutput a single integer n such that none of the first k terms of the sequence n, f(n), f(f(n)), f(f(f(n))), \dots are equal to 1.Integer n should have at most 10^3 digits.ExamplesInput
1
Output
5Input
5
Output
6NoteIn the first test, the sequence created with n = 5 looks like 5, 16, 8, 4, 2, 1, 4, \dots, and none of the first k=1 terms are equal to 1.In the second test, the sequence created with n = 6 looks like 6, 3, 10, 5, 16, 8, 4, \dots, and none of the first k=5 terms are equal to 1. | 1
| 5 | 1 second | 256 megabytes | ['*special problem', 'constructive algorithms', 'math', 'number theory'] |
C. Digitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe first line contains a single integer t (1 \le t \le 32) — the number of test cases.Each test case contains n lines. The i-th line contains an integer a_i (1 \le a_i \le 9).The sum of n over all test cases doesn't exceed 155.OutputFor each test case, print one integer — the answer.ExampleInput
3
2
1
4
7
1
2
3
5
Output
8
7
30
| 3
2
1
4
7
1
2
3
5
| 8 7 30 | 1 second | 256 megabytes | ['*special problem'] |
B. Was it Rated?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe only line of the input contains a single integer n (1 \leq n \leq 25).ExamplesInput
1
Output
YES
Input
15
Output
NO
| 1
| YES | 1 second | 256 megabytes | ['*special problem', '*special problem', '*special problem', 'brute force', 'implementation'] |
G2. Vlad and the Nice Paths (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is hard version of the problem, it differs from the easy one only by constraints on n and k.Vlad found a row of n tiles and the integer k. The tiles are indexed from left to right and the i-th tile has the color c_i. After a little thought, he decided what to do with it.You can start from any tile and jump to any number of tiles right, forming the path p. Let's call the path p of length m nice if: p can be divided into blocks of length exactly k, that is, m is divisible by k; c_{p_1} = c_{p_2} = \ldots = c_{p_k}; c_{p_{k+1}} = c_{p_{k+2}} = \ldots = c_{p_{2k}}; \ldots c_{p_{m-k+1}} = c_{p_{m-k+2}} = \ldots = c_{p_{m}}; Your task is to find the number of nice paths of maximum length. Since this number may be too large, print it modulo 10^9 + 7.InputThe first line of each test contains the integer t (1 \le t \le 10^4) — the number of test cases in the test.The first line of each test case contains two integers n and k (1 \le k \le n \le 5000) — the number of tiles in a row and the length of the block.The second line of each test case contains n integers c_1, c_2, c_3, \dots, c_n (1 \le c_i \le n) — tile colors.It is guaranteed that the sum of n^2 over all test cases does not exceed 25 \cdot 10^6.OutputPrint t numbers, each of which is the answer to the corresponding test case — the number of nice paths of maximum length modulo 10^9 + 7.ExampleInput
55 21 2 3 4 57 21 3 1 3 3 1 311 41 1 1 1 1 1 1 1 1 1 15 21 1 2 2 25 11 2 3 4 5Output
1
4
165
3
1
NoteIn the first sample, it is impossible to make a nice path with a length greater than 0.In the second sample, we are interested in the following paths: 1 \rightarrow 3 \rightarrow 4 \rightarrow 5 2 \rightarrow 4 \rightarrow 5 \rightarrow 7 1 \rightarrow 3 \rightarrow 5 \rightarrow 7 1 \rightarrow 3 \rightarrow 4 \rightarrow 7 In the third example, any path of length 8 is nice. | 55 21 2 3 4 57 21 3 1 3 3 1 311 41 1 1 1 1 1 1 1 1 1 15 21 1 2 2 25 11 2 3 4 5 | 1 4 165 3 1 | 3 seconds | 512 megabytes | ['binary search', 'combinatorics', 'data structures', 'dp', 'math', 'two pointers', '*2200'] |
G1. Vlad and the Nice Paths (easy version)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem, it differs from the hard one only by constraints on n and k.Vlad found a row of n tiles and the integer k. The tiles are indexed from left to right and the i-th tile has the color c_i. After a little thought, he decided what to do with it.You can start from any tile and jump to any number of tiles right, forming the path p. Let's call the path p of length m nice if: p can be divided into blocks of length exactly k, that is, m is divisible by k; c_{p_1} = c_{p_2} = \ldots = c_{p_k}; c_{p_{k+1}} = c_{p_{k+2}} = \ldots = c_{p_{2k}}; \ldots c_{p_{m-k+1}} = c_{p_{m-k+2}} = \ldots = c_{p_{m}}; Your task is to find the number of nice paths of maximum length. Since this number may be too large, print it modulo 10^9 + 7.InputThe first line of each test contains the integer t (1 \le t \le 10^4) — the number of test cases in the test.The first line of each test case contains two integers n and k (1 \le k \le n \le 100) — the number of tiles in a row and the length of the block.The second line of each test case contains n integers c_1, c_2, c_3, \dots, c_n (1 \le c_i \le n) — tile colors.It is guaranteed that the sum of n^3 over all test cases does not exceed 5 \cdot 10^6.OutputPrint t numbers, each of which is the answer to the corresponding test case — the number of nice paths of maximum length modulo 10^9 + 7.ExampleInput
55 21 2 3 4 57 21 3 1 3 3 1 311 41 1 1 1 1 1 1 1 1 1 15 21 1 2 2 25 11 2 3 4 5Output
1
4
165
3
1
NoteIn the first sample, it is impossible to make a nice path with a length greater than 0.In the second sample, we are interested in the following paths: 1 \rightarrow 3 \rightarrow 4 \rightarrow 5 2 \rightarrow 4 \rightarrow 5 \rightarrow 7 1 \rightarrow 3 \rightarrow 5 \rightarrow 7 1 \rightarrow 3 \rightarrow 4 \rightarrow 7 In the third example, any path of length 8 is nice. | 55 21 2 3 4 57 21 3 1 3 3 1 311 41 1 1 1 1 1 1 1 1 1 15 21 1 2 2 25 11 2 3 4 5 | 1 4 165 3 1 | 5 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', '*2100'] |
F. Is It Flower?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVlad found a flowerbed with graphs in his yard and decided to take one for himself. Later he found out that in addition to the usual graphs, k-flowers also grew on that flowerbed. A graph is called a k-flower if it consists of a simple cycle of length k, through each vertex of which passes its own simple cycle of length k and these cycles do not intersect at the vertices. For example, 3-flower looks like this: Note that 1-flower and 2-flower do not exist, since at least 3 vertices are needed to form a cycle.Vlad really liked the structure of the k-flowers and now he wants to find out if he was lucky to take one of them from the flowerbed.InputThe first line of input contains the single integer t (1 \le t \le 10^4) — the number of test cases in the test.The descriptions of the cases follow. An empty string is written before each case.The first line of each case contains two integers n and m (2 \le n \le 2 \cdot 10^5, 1 \le m \le \min(2 \cdot 10^5, \frac{n \cdot (n-1)}{2})) — the number of vertices and edges in the graph, respectively.The next m lines contain two integers each u and v (1 \le u, v \le n, u \ne v) — numbers of vertices connected by an edge. It is guaranteed that the graph does not contain multiple edges and self-loops.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5. It is also guaranteed for the sum of m over all test cases.OutputOutput t lines, each of which is the answer to the corresponding test case. As an answer, output "YES" if Vlad's graph is a k-flower for some k, and "NO" otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExamplesInput
59 121 23 12 31 64 16 43 83 55 89 72 97 28 121 23 12 31 64 16 43 83 55 88 72 87 24 31 24 23 16 86 36 45 35 23 23 12 12 45 72 42 53 43 54 14 51 5Output
YES
NO
NO
NO
NO
Input
42 11 28 91 28 48 26 46 54 73 23 72 59 122 92 86 96 86 56 19 89 39 18 38 75 73 31 21 32 3Output
NO
NO
NO
NO
| 59 121 23 12 31 64 16 43 83 55 89 72 97 28 121 23 12 31 64 16 43 83 55 88 72 87 24 31 24 23 16 86 36 45 35 23 23 12 12 45 72 42 53 43 54 14 51 5 | YES NO NO NO NO | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'implementation', '*2100'] |
E. Living Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Japan, the number 4 reads like death, so Bob decided to build a live sequence. Living sequence a contains all natural numbers that do not contain the digit 4. a = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, \ldots].For example, the number 1235 is part of the sequence a, but the numbers 4321, 443 are not part of the sequence a.Bob realized that he does not know how to quickly search for a particular number by the position k in the sequence, so he asks for your help.For example, if Bob wants to find the number at position k = 4 (indexing from 1), you need to answer a_k = 5.InputThe first line of input data contains a single integer t (1 \le t \le 10^4) — the number of test cases.In the only line of each test case, there is a single integer k (1 \le k \le 10^{12}) — the position Bob is interested in.OutputFor each test case, print on a separate line the number a_k in indexing with 1.ExampleInput
735221010012345827264634912Output
3
6
25
11
121
18937
2932285320890
| 735221010012345827264634912 | 3 6 25 11 121 18937 2932285320890 | 1 second | 256 megabytes | ['binary search', 'dp', 'math', 'number theory', '*1500'] |
D. Umka and a Long Flighttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe girl Umka loves to travel and participate in math olympiads. One day she was flying by plane to the next olympiad and out of boredom explored a huge checkered sheet of paper.Denote the n-th Fibonacci number as F_n = \begin{cases} 1, & n = 0; \\ 1, & n = 1; \\ F_{n-2} + F_{n-1}, & n \ge 2. \end{cases}A checkered rectangle with a height of F_n and a width of F_{n+1} is called a Fibonacci rectangle of order n.Umka has a Fibonacci rectangle of order n. Someone colored a cell in it at the intersection of the row x and the column y.It is necessary to cut this rectangle exactly into n+1 squares in such way that the painted cell was in a square with a side of 1; there was at most one pair of squares with equal sides; the side of each square was equal to a Fibonacci number. Will Umka be able to cut this rectangle in that way?InputThe first line contains an integer t (1 \le t \le 2 \cdot 10^5) — number of test cases.For each test case the integers n, x, y are given (1 \le n \le 44, 1 \le x \le F_n, 1 \le y \le F_{n+1}) — the order of the Fibonacci rectangle and the coordinates of the colored cell.OutputFor each test case, print "YES" if the answer is positive, and "NO" otherwise.You can print "YES" and "NO" in any case (for example, the strings "yEs", "yes" and "Yes" will be recognized as a positive answer).ExampleInput
121 1 12 1 23 1 43 3 24 4 64 3 35 6 55 4 125 2 124 2 11 1 244 758465880 1277583853Output
YES
NO
YES
YES
YES
NO
YES
NO
NO
YES
YES
NO
Note The first, third and fourth test cases. | 121 1 12 1 23 1 43 3 24 4 64 3 35 6 55 4 125 2 124 2 11 1 244 758465880 1277583853 | YES NO YES YES YES NO YES NO NO YES YES NO | 3 seconds | 256 megabytes | ['constructive algorithms', 'implementation', 'math', '*1600'] |
C. Restore the Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKristina had an array a of length n consisting of non-negative integers.She built a new array b of length n-1, such that b_i = \max(a_i, a_{i+1}) (1 \le i \le n-1).For example, suppose Kristina had an array a = [3, 0, 4, 0, 5] of length 5. Then she did the following: Calculated b_1 = \max(a_1, a_2) = \max(3, 0) = 3; Calculated b_2 = \max(a_2, a_3) = \max(0, 4) = 4; Calculated b_3 = \max(a_3, a_4) = \max(4, 0) = 4; Calculated b_4 = \max(a_4, a_5) = \max(0, 5) = 5. As a result, she got an array b = [3, 4, 4, 5] of length 4.You only know the array b. Find any matching array a that Kristina may have originally had.InputThe first line of input data contains a single integer t (1 \le t \le 10^4) — the number of test cases.The description of the test cases follows.The first line of each test case contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of elements in the array a that Kristina originally had.The second line of each test case contains exactly n-1 non-negative integer — elements of array b (0 \le b_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5, and that array b was built correctly from some array a.OutputFor each test case on a separate line, print exactly n non-negative integers — the elements of the array a that Kristina originally had.If there are several possible answers — output any of them.ExampleInput
1153 4 4 542 2 150 0 0 060 3 4 4 321043 3 354 2 5 543 3 342 1 034 468 1 3 5 10Output
3 0 4 0 5
2 2 1 1
0 0 0 0 0
0 0 3 4 3 3
10 10
3 3 3 1
4 2 2 5 5
3 3 3 3
2 1 0 0
2 4 4
8 1 1 3 5 10NoteThe first test case is explained in the problem statement.In the second test case, we can get array b = [2, 2, 1] from the array a = [2, 2, 1, 1]: b_1 = \max(a_1, a_2) = \max(2, 2) = 2; b_2 = \max(a_2, a_3) = \max(2, 1) = 2; b_3 = \max(a_3, a_4) = \max(1, 1) = 1. In the third test case, all elements of the array b are zeros. Since each b_i is the maximum of two adjacent elements of array a, array a can only consist entirely of zeros.In the fourth test case, we can get array b = [0, 3, 4, 4, 3] from the array a = [0, 0, 3, 4, 3, 3] : b_1 = \max(a_1, a_2) = \max(0, 0) = 0; b_2 = \max(a_2, a_3) = \max(0, 3) = 3; b_3 = \max(a_3, a_4) = \max(3, 4) = 4; b_4 = \max(a_4, a_5) = \max(4, 3) = 4; b_5 = \max(a_5, a_6) = \max(3, 3) = 3. | 1153 4 4 542 2 150 0 0 060 3 4 4 321043 3 354 2 5 543 3 342 1 034 468 1 3 5 10 | 3 0 4 0 5 2 2 1 1 0 0 0 0 0 0 0 3 4 3 3 10 10 3 3 3 1 4 2 2 5 5 3 3 3 3 2 1 0 0 2 4 4 8 1 1 3 5 10 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*1100'] |
B. Conveyor Beltstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConveyor matrix m_n is matrix of size n \times n, where n is an even number. The matrix consists of concentric ribbons moving clockwise.In other words, the conveyor matrix for n = 2 is simply a matrix 2 \times 2, whose cells form a cycle of length 4 clockwise. For any natural k \ge 2, the matrix m_{2k} is obtained by adding to the matrix m_{2k - 2} an outer layer forming a clockwise cycle. The conveyor matrix 8 \times 8. You are standing in a cell with coordinates x_1, y_1 and you want to get into a cell with coordinates x_2, y_2. A cell has coordinates x, y if it is located at the intersection of the xth row and the yth column.Standing on some cell, every second you will move to the cell next in the direction of movement of the tape on which you are. You can also move to a neighboring cell by spending one unit of energy. Movements happen instantly and you can make an unlimited number of them at any time.Your task is to find the minimum amount of energy that will have to be spent to get from the cell with coordinates x_1, y_1 to the cell with coordinates x_2, y_2.For example, n=8 initially you are in a cell with coordinates 1,3 and you want to get into a cell with coordinates 6, 4. You can immediately make 2 movements, once you are in a cell with coordinates 3, 3, and then after 8 seconds you will be in the right cell.InputThe first line contains an integer t (1 \le t \le 2 \cdot 10^5) — the number of test cases.The descriptions of the test cases follow.The description of each test case consists of one string containing five integers n, x_1, y_1, x_2 and y_2 (1 \le x_1, y_1, x_2, y_2 \le n \le 10^9) — matrix size and the coordinates of the start and end cells. It is guaranteed that the number n is even.OutputFor each test case, print one integer in a separate line — the minimum amount of energy that will have to be spent to get from the cell with coordinates x_1, y_1 to the cell with coordinates x_2, y_2.ExampleInput
52 1 1 2 24 1 4 3 38 1 3 4 6100 10 20 50 1001000000000 123456789 987654321 998244353 500000004Output
0
1
2
9
10590032
| 52 1 1 2 24 1 4 3 38 1 3 4 6100 10 20 50 1001000000000 123456789 987654321 998244353 500000004 | 0 1 2 9 10590032 | 3 seconds | 256 megabytes | ['implementation', 'math', '*1000'] |
A. Insert Digittime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a positive number of length n and one additional digit.You can insert this digit anywhere in the number, including at the beginning or at the end.Your task is to make the result as large as possible.For example, you have the number 76543, and the additional digit is 4. Then the maximum number you can get is 765443, and it can be obtained in two ways — by inserting a digit after the 3th or after the 4th digit of the number.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The descriptions of the test cases follow.The first line of the description of each test case contains two integers n and d (1 \le n \le 2 \cdot 10^5; 0 \le d \le 9) — the length of the number and an additional digit, respectively.The second line of the description of each test case contains a string consisting of n digits — the number that you have initially. It is guaranteed that the number does not contain leading zeros.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 string consisting of n + 1 digits — the maximum possible number that can be obtained.ExampleInput
115 4765431 012 5443 66665 6135795 89753119 498765432101234567895 7737378 1200000007 0705895912 1828127127732Output
765443
10
544
6666
613579
987531
98765443210123456789
773737
210000000
70589590
8281271277321
| 115 4765431 012 5443 66665 6135795 89753119 498765432101234567895 7737378 1200000007 0705895912 1828127127732 | 765443 10 544 6666 613579 987531 98765443210123456789 773737 210000000 70589590 8281271277321 | 2 seconds | 256 megabytes | ['greedy', 'math', 'strings', '*800'] |
H. Last Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a multiset S. Initially, S = \{1,2,3, \ldots, n\}.You will perform the following operation n-1 times. Choose the largest number S_{\text{max}} in S and the smallest number S_{\text{min}} in S. Remove the two numbers from S, and add S_{\text{max}} - S_{\text{min}} into S. It's easy to show that there will be exactly one number left after n-1 operations. Output that number.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^5) — the number of test cases. Their description follows.For each test case, one single line contains a single integer n (2 \le n \le 10^9) — the initial size of the multiset S.OutputFor each test case, output an integer denoting the only number left after n-1 operations.ExampleInput
524715177567Output
1
2
2
4
33914
NoteWe show how the multiset S changes for n=4. Operation 1: S=\{1,2,3,4\}, remove 4, 1, add 3. Operation 2: S=\{2,3,3\}, remove 3, 2, add 1. Operation 3: S=\{1,3\}, remove 3, 1, add 2. Final: S = \{2\}.Thus, the answer for n = 4 is 2. | 524715177567 | 1 2 2 4 33914 | 2 seconds | 256 megabytes | ['combinatorics', 'math', '*2900'] |
G. The Maximum Prefixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're going to generate an array a with a length of at most n, where each a_{i} equals either 1 or -1.You generate this array in the following way. First, you choose some integer k (1\le k \le n), which decides the length of a. Then, for each i (1\le i \le k), you set a_{i} = 1 with probability p_{i}, otherwise set a_{i} = -1 (with probability 1 - p_{i}). After the array is generated, you calculate s_{i} = a_{1} + a_{2} + a_{3}+ \ldots + a_{i}. Specially, s_{0} = 0. Then you let S equal to \displaystyle \max_{i=0}^{k}{s_{i}}. That is, S is the maximum prefix sum of the array a.You are given n+1 integers h_{0} , h_{1}, \ldots ,h_{n}. The score of an array a with maximum prefix sum S is h_{S}. Now, for each k, you want to know the expected score for an array of length k modulo 10^9+7.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 5000) — the number of test cases. Their description follows.The first line contains an integer n (1\le n \le 5000).Then for the following n lines, each line contains two integers x_{i} and y_{i} (0 \le x_{i} < 10^9 + 7, 1\le y_{i} < 10^9 + 7, x_{i} \le y_{i}), indicating p_{i} = \frac{x_{i}}{y_{i}}.The next line contains n+1 integers h_{0},h_{1}, \ldots, h_{n} (0 \le h_{i} < 10^9 + 7).It is guaranteed that the sum of n over all test cases does not exceed 5000.OutputFor each test case, output n integers in one single line, the i-th of which denotes the expected score for an array of length i, modulo 10^9 + 7.Formally, let M = 10^9 + 7. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.ExampleInput
421 21 21 2 331 31 45 51 1 1 132 54 60 24 3 2 155 65 71 61 34 79 0 4 5 2 4Output
500000005 750000007
1 1 1
200000005 333333339 333333339
500000005 880952391 801587311 781746041 789304620
NoteIn the first test case, if we choose k=1, there are 2 possible arrays with equal probabilities: [1] and [-1]. The S values for them are 1 and 0. So the expected score is \frac{1}{2}h_{0} + \frac{1}{2}h_{1} = \frac{3}{2}. If we choose k=2, there are 4 possible arrays with equal probabilities: [1,1], [1,-1], [-1,1], [-1,-1], and the S values for them are 2,1,0,0. So the expected score is \frac{1}{2}h_{0} + \frac{1}{4}h_{1} + \frac{1}{4}h_{2} = \frac{7}{4}.In the second test case, no matter what the S value is, the score is always 1, so the expected score is always 1. | 421 21 21 2 331 31 45 51 1 1 132 54 60 24 3 2 155 65 71 61 34 79 0 4 5 2 4 | 500000005 750000007 1 1 1 200000005 333333339 333333339 500000005 880952391 801587311 781746041 789304620 | 1 second | 256 megabytes | ['dp', '*3200'] |
F. M-treetime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA rooted tree is called good if every vertex of the tree either is a leaf (a vertex with no children) or has exactly m children.For a good tree, each leaf u has a positive integer c_{u} written on it, and we define the value of the leaf as c_{u} + \mathrm{dep}_{u}, where \mathrm{dep}_{u} represents the number of edges of the path from vertex u to the root (also known as the depth of u). The value of a good tree is the maximum value of all its leaves.Now, you are given an array of n integers a_{1}, a_{2}, \ldots, a_{n}, which are the integers that should be written on the leaves. You need to construct a good tree with n leaves and write the integers from the array a to all the leaves. Formally, you should assign each leaf u an index b_{u}, where b is a permutation of length n, and represent that the integer written on leaf u is c_u = a_{b_{u}}. Under these constraints, you need to minimize the value of the good tree.You have q queries. Each query gives you x, y and changes a_{x} to y, and after that, you should output the minimum value of a good tree based on the current array a. 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).InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Their description follows.The first line contains three integers n, m, and q (1\le n,q \le 2 \cdot 10^5, 2\le m \le 2\cdot 10^5, n \equiv 1 \pmod {m - 1}) — the number of the leaves, the constant m, and the number of queries.The second line contains n integers a_{1},a_{2}, \ldots, a_{n} (1 \le a_{i} \le n) — the initial array.For the following q lines, each line contains two integers x and y (1\le x,y\le n), representing a query changing a_{x} to y.It is guaranteed that both the sum of n and the sum of q do not exceed 2\cdot 10^5.OutputFor each test case, output q integers in one line, the i-th of which is the minimum tree value after the i-th change.ExampleInput
35 3 33 3 4 4 51 42 43 55 2 43 3 4 4 51 42 53 54 57 3 41 2 2 3 3 3 41 42 15 56 6Output
6 6 6
7 7 7 8
6 6 6 7
NoteIn the first test case, after the first query, the current array a is [4,3,4,4,5]. We can construct such a good tree: The first number inside a vertex is its index (in this problem, the indices do not matter, but help to understand the figure). If a vertex is a leaf, the second number inside the vertex is the integer written on it.We can tell that \mathrm{dep}_{3}=\mathrm{dep}_{4}=1,\mathrm{dep}_{5}=\mathrm{dep}_{6}=\mathrm{dep}_{7}=2 and the value of the tree, which is the maximum value over all leaves, is 5+1=6. The value of leaves 5, 6, 7 is also equal to 6. It can be shown that this tree has the minimum value over all valid trees. | 35 3 33 3 4 4 51 42 43 55 2 43 3 4 4 51 42 53 54 57 3 41 2 2 3 3 3 41 42 15 56 6 | 6 6 6 7 7 7 8 6 6 6 7 | 2.5 seconds | 256 megabytes | ['data structures', 'math', 'sortings', 'trees', '*2800'] |
E. Monsterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an undirected graph with n vertices and m edges. Initially, for each vertex i, there is a monster with danger a_{i} on that vertex. For a monster with danger a_{i}, you can defeat it if and only if you have defeated at least a_{i} other monsters before.Now you want to defeat all the monsters. First, you choose some vertex s and defeat the monster on that vertex (since you haven't defeated any monsters before, a_{s} has to be 0). Then, you can move through the edges. If you want to move from vertex u to vertex v, then the following must hold: either the monster on vertex v has been defeated before, or you can defeat it now. For the second case, you defeat the monster on vertex v and reach vertex v.You can pass the vertices and the edges any number of times. Determine whether you can defeat all the monsters or not.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Their description follows.The first line of each test case contains two integers n, m (1 \le n, m \le 2 \cdot 10^5) — the number of vertices and edges in the graph respectively. The second line of each test case contains n integers a_{1}, a_{2}, \ldots, a_{n} (0 \le a_{i} \le n) — the dangers of monsters on corresponding vertices.For the following m lines, each line contains two integers u, v (1 \le u, v \le n), describing an edge connecting vertex u and vertex v. It is guaranteed that there are no multi-edges or self-loops in the graph.It is guaranteed that both the sum of n and the sum of m over all test cases do not exceed 2 \cdot 10^5.OutputFor each test case, output "YES" if you can defeat all the monsters, or "NO" otherwise.You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput
54 32 1 0 31 22 33 46 60 1 2 3 0 11 22 33 44 54 65 64 30 1 2 01 22 31 34 61 1 1 01 23 24 32 44 11 35 50 1 3 2 01 22 33 44 53 5Output
YES
YES
NO
YES
NO
NoteIn the first test case, you can start at vertex 3 and defeat the monster on it, before you go to vertices 2, 1 in this order, defeating the monsters on them as well. Then you return to vertex 3, and go to vertex 4, defeating the monster on it.In the third test case, there is no path to vertex 4 if you start at vertex 1. Also, there is no path to vertices 1, 2, and 3 if you start at vertex 4. | 54 32 1 0 31 22 33 46 60 1 2 3 0 11 22 33 44 54 65 64 30 1 2 01 22 31 34 61 1 1 01 23 24 32 44 11 35 50 1 3 2 01 22 33 44 53 5 | YES YES NO YES NO | 2 seconds | 256 megabytes | ['brute force', 'data structures', 'dfs and similar', 'dsu', 'graphs', 'greedy', '*2100'] |
D. Climbing the Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe snails are climbing a tree. The tree height is h meters, and snails start at position 0.Each snail has two attributes a and b (a > b). Starting from the 1-st day, one snail climbs the tree like this: during the daylight hours of the day, he climbs up a meters; during the night, the snail rests, and he slides down b meters. If on the n-th day, the snail reaches position h for the first time (that is, the top of the tree), he will finish climbing, and we say that the snail spends n days climbing the tree. Note that on the last day of climbing, the snail doesn't necessarily climb up a meters, in case his distance to the top is smaller than a.Unfortunately, you don't know the exact tree height h at first, but you know that h is a positive integer. There are q events of two kinds. Event of type 1: a snail with attributes a, b comes and claims that he spent n days climbing the tree. If this message contradicts previously adopted information (i. e. there is no tree for which all previously adopted statements and this one are true), ignore it. Otherwise, adopt it. Event of type 2: a snail with attributes a, b comes and asks you how many days he will spend if he climbs the tree. You can only give the answer based on the information you have adopted so far. If you cannot determine the answer precisely, report that. You need to deal with all the events in order.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Then follows their description.The first line of each test case contains one integer q (1\le q \le 2\cdot 10^5) — the number of events.For the following q lines, the first integer of each line is either 1 or 2, denoting the event type.If the event type is 1, then three integers a, b, and n (1\le a,b,n \le 10^9, a>b) follow.If the event type is 2, then two integers a and b (1\le a,b \le 10^9, a>b) follow.It is guaranteed that the sum of q over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, output q integers in one line, one for each event, in order. Specifically, for each event of type 1, if you adopt the message, output 1; if you ignore it, output 0; for each event of type 2, output an integer denoting the number of days that the snail will spend. If you cannot determine it, output -1. ExampleInput
531 3 2 52 4 12 3 231 6 5 12 3 12 6 231 4 2 21 2 1 32 10 291 7 3 61 2 1 82 5 11 10 9 71 8 1 21 10 5 81 10 7 72 7 41 9 4 291 2 1 61 8 5 61 4 2 72 9 11 5 1 41 5 2 71 7 1 91 9 1 42 10 8Output
1 2 5
1 -1 1
1 0 1
1 0 -1 0 0 0 1 8 0
1 0 0 1 0 0 0 0 1
NoteIn the first test case, we can determine h=7 through the first message, so we know the second snail and the third snail need to spend 2 and 5 days respectively to reach the top.Let's show how the second snail climbs: During the daylight hours of the 1st day: climbs up 4 meters, now at position 4. During the night of the 1st day: slides down 1 meters, now at position 3. During the daylight hours of the 2nd day: climbs up 4 meters, now at position 7 (reaches the top). In the third test case, the second snail's message contradicts the first snail's, because the second snail says he spent 3 days, and he can climb at most 1+1+2=4 meters in the first 3 days. However, the first snail only needs 1 day to climb 4 meters. | 531 3 2 52 4 12 3 231 6 5 12 3 12 6 231 4 2 21 2 1 32 10 291 7 3 61 2 1 82 5 11 10 9 71 8 1 21 10 5 81 10 7 72 7 41 9 4 291 2 1 61 8 5 61 4 2 72 9 11 5 1 41 5 2 71 7 1 91 9 1 42 10 8 | 1 2 5 1 -1 1 1 0 1 1 0 -1 0 0 0 1 8 0 1 0 0 1 0 0 0 0 1 | 2 seconds | 256 megabytes | ['binary search', 'math', '*1700'] |
C. Make It Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an integer array a of length n. There are two kinds of operations you can make. Remove an integer from a. This operation costs c. Insert an arbitrary positive integer x to any position of a (to the front, to the back, or between any two consecutive elements). This operation costs d.You want to make the final array a permutation of any positive length. Please output the minimum cost of doing that. Note that you can make the array empty during the operations, but the final array must contain at least one integer.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).InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Their description follows.The first line of each test case contains three integers n, c, d (1 \le n \le 10^5, 1 \le c,d \le 10^9).The second line of each test case contains n integers a_{1}, a_{2}, \ldots, a_{n} (1 \le a_{i} \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output in one line the minimum cost to make the final array a permutation.ExampleInput
83 3 31 2 35 1 51 2 3 5 65 2 31 1 1 3 35 1 102 4 6 8 106 2 87 3 5 4 4 84 10 11 2 6 74 3 32 5 8 72 1000000000 11000000000 1Output
0
2
8
14
20
3
12
999999998
NoteIn the first test case, the array is already a permutation, so there's no need for operations.In the second test case, we can remove numbers 5, 6 to get the permutation [1,2,3] in cost 2. Note that we can also get a permutation by inserting a number 4, but it costs 5.In the third test case, we can just remove all the numbers except for the first number 1. It costs 8, and the final array is [1], which is a permutation of length 1.In the fourth test case, we can remove all the numbers except for 2, and insert a number 1 to the first position. It costs 4+10=14, and the final array is [1,2], which is a permutation of length 2. | 83 3 31 2 35 1 51 2 3 5 65 2 31 1 1 3 35 1 102 4 6 8 106 2 87 3 5 4 4 84 10 11 2 6 74 3 32 5 8 72 1000000000 11000000000 1 | 0 2 8 14 20 3 12 999999998 | 1 second | 256 megabytes | ['brute force', 'greedy', 'sortings', '*1300'] |
B. Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is about candy. Initially, you only have 1 candy, and you want to have exactly n candies.You can use the two following spells in any order at most 40 times in total. Assume you have x candies now. If you use the first spell, then x candies become 2x-1 candies. Assume you have x candies now. If you use the second spell, then x candies become 2x+1 candies. Construct a sequence of spells, such that after using them in order, you will have exactly n candies, or determine it's impossible.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Their description follows.Each test case contains one line with a single integer n (2 \le n \le 10^9) — the required final number of candies.OutputFor each test case, output the following.If it's possible to eventually have n candies within 40 spells, in the first line print an integer m (1 \le m \le 40), representing the total number of spells you use.In the second print m integers a_{1}, a_{2}, \ldots, a_{m} (a_{i} is 1 or 2) separated by spaces, where a_{i} = 1 means that you use the first spell in the i-th step, while a_{i} = 2 means that you use the second spell in the i-th step.Note that you do not have to minimize m, and if there are multiple solutions, you may output any one of them.If it's impossible, output -1 in one line.ExampleInput
423717Output
-1
1
2
2
2 2
4
2 1 1 1
NoteFor n=3, you can just use the second spell once, and then have 2 \cdot 1 + 1 = 3 candies.For n=7, you can use the second spell twice. After the first step, you will have 3 candies. And after the second step, you will have 2 \cdot 3 + 1 = 7 candies. | 423717 | -1 1 2 2 2 2 4 2 1 1 1 | 1 second | 256 megabytes | ['constructive algorithms', 'math', 'number theory', '*800'] |
A. Beautiful Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of m integers a_{1}, a_{2}, \ldots, a_{m} is good, if and only if there exists at least one i (1 \le i \le m) such that a_{i} = i. For example, [3,2,3] is a good sequence, since a_{2} = 2, a_{3} = 3, while [3,1,1] is not a good sequence, since there is no i such that a_{i} = i.A sequence a is beautiful, if and only if there exists at least one subsequence of a satisfying that this subsequence is good. For example, [4,3,2] is a beautiful sequence, since its subsequence [4,2] is good, while [5,3,4] is not a beautiful sequence.A sequence b is a subsequence of a sequence a if b can be obtained from a by the deletion of several (possibly, zero or all) elements. Now you are given a sequence, check whether it is beautiful or not.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 500) — the number of test cases. Their description follows.The first line of each test case contains an integer n (1 \le n \le 100) — the length of the given sequence.The second line of each test case contains n integers a_{1}, a_{2}, \ldots, a_{n} (1 \le a_{i} \le 10^9), representing the sequence.OutputFor each test case, output "YES" or "NO"(without quotes) in one line, representing whether the given sequence is beautiful.You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput
733 2 142 4 3 552 3 5 5 623 152 4 5 2 345 6 7 866 5 4 3 2 1Output
YES
YES
NO
YES
YES
NO
YES
NoteIn the first test case, the good subsequence is b=[3,2], where b_{2} = 2.In the second test case, the good subsequence is b=[2,4,3], where b_{3} = 3.In the fourth test case, the good subsequence is b=[1], where b_{1} = 1.In the fifth test case, the good subsequence is b=[2,2], where b_{2} = 2. | 733 2 142 4 3 552 3 5 5 623 152 4 5 2 345 6 7 866 5 4 3 2 1 | YES YES NO YES YES NO YES | 1 second | 256 megabytes | ['brute force', 'greedy', '*800'] |
G. Predictiontime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider a tournament with n participants. The rating of the i-th participant is a_i.The tournament will be organized as follows. First of all, organizers will assign each participant an index from 1 to n. All indices will be unique. Let p_i be the participant who gets the index i.Then, n-1 games will be held. In the first game, participants p_1 and p_2 will play. In the second game, the winner of the first game will play against p_3. In the third game, the winner of the second game will play against p_4, and so on — in the last game, the winner of the (n-2)-th game will play against p_n.Monocarp wants to predict the results of all n-1 games (of course, he will do the prediction only after the indices of the participants are assigned). He knows for sure that, when two participants with ratings x and y play, and |x - y| > k, the participant with the higher rating wins. But if |x - y| \le k, any of the two participants may win.Among all n! ways to assign the indices to participants, calculate the number of ways to do this so that Monocarp can predict the results of all n-1 games. Since the answer can be large, print it modulo 998244353.InputThe first line contains two integers n and k (2 \le n \le 10^6; 0 \le k \le 10^9).The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_1 \le a_2 \le \dots \le a_n \le 10^9).OutputPrint one integer — the number of ways to assign the indices to the participants so that Monocarp can predict the results of all n-1 games.ExamplesInput
4 3
7 12 17 21
Output
24
Input
3 7
4 9 28
Output
4
Input
4 1
1 2 3 4
Output
0
Input
4 1
1 2 2 4
Output
12
Input
16 30
8 12 15 27 39 44 49 50 51 53 58 58 59 67 68 100
Output
527461297
NoteIn the first example, a match with any pair of players can be predicted by Monocarp, so all 24 ways to assign indices should be counted.In the second example, suitable ways are [1, 3, 2], [2, 3, 1], [3, 1, 2] and [3, 2, 1]. | 4 3
7 12 17 21
| 24 | 4 seconds | 512 megabytes | ['combinatorics', 'dp', 'math', '*2800'] |
F. Traveling in Berlandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in Berland, arranged in a circle and numbered from 1 to n in clockwise order.You want to travel all over Berland, starting in some city, visiting all the other cities and returning to the starting city. Unfortunately, you can only drive along the Berland Ring Highway, which connects all n cities. The road was designed by a very titled and respectable minister, so it is one-directional — it can only be traversed clockwise, only from the city i to the city (i \bmod n) + 1 (i.e. from 1 to 2, from 2 in 3, ..., from n to 1).The fuel tank of your car holds up to k liters of fuel. To drive from the i-th city to the next one, a_i liters of fuel are needed (and are consumed in the process).Every city has a fuel station; a liter of fuel in the i-th city costs b_i burles. Refueling between cities is not allowed; if fuel has run out between cities, then your journey is considered incomplete.For each city, calculate the minimum cost of the journey if you start and finish it in that city.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 (3 \le n \le 2 \cdot 10^5; 1 \le k \le 10^9) — the number of cities and the volume of fuel tank, respectively.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le k).The third line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 2).The sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print n integers, where the i-th of them is equal to the minimum cost of the journey if you start and finish in the i-th city.ExampleInput
43 53 4 41 2 25 71 3 2 5 12 1 1 1 24 31 2 1 32 2 2 23 22 2 21 2 1Output
17 19 17
13 12 12 12 14
14 14 14 14
8 8 8
| 43 53 4 41 2 25 71 3 2 5 12 1 1 1 24 31 2 1 32 2 2 23 22 2 21 2 1 | 17 19 17 13 12 12 12 14 14 14 14 14 8 8 8 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'graphs', 'greedy', 'implementation', '*2500'] |
E. Two Tankstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are two water tanks, the first one fits a liters of water, the second one fits b liters of water. The first tank has c (0 \le c \le a) liters of water initially, the second tank has d (0 \le d \le b) liters of water initially.You want to perform n operations on them. The i-th operation is specified by a single non-zero integer v_i. If v_i > 0, then you try to pour v_i liters of water from the first tank into the second one. If v_i < 0, you try to pour -v_i liters of water from the second tank to the first one.When you try to pour x liters of water from the tank that has y liters currently available to the tank that can fit z more liters of water, the operation only moves \min(x, y, z) liters of water.For all pairs of the initial volumes of water (c, d) such that 0 \le c \le a and 0 \le d \le b, calculate the volume of water in the first tank after all operations are performed.InputThe first line contains three integers n, a and b (1 \le n \le 10^4; 1 \le a, b \le 1000) — the number of operations and the capacities of the tanks, respectively.The second line contains n integers v_1, v_2, \dots, v_n (-1000 \le v_i \le 1000; v_i \neq 0) — the volume of water you try to pour in each operation.OutputFor all pairs of the initial volumes of water (c, d) such that 0 \le c \le a and 0 \le d \le b, calculate the volume of water in the first tank after all operations are performed.Print a + 1 lines, each line should contain b + 1 integers. The j-th value in the i-th line should be equal to the answer for c = i - 1 and d = j - 1.ExamplesInput
3 4 4
-2 1 2
Output
0 0 0 0 0
0 0 0 0 1
0 0 1 1 2
0 1 1 2 3
1 1 2 3 4
Input
3 9 5
1 -2 2
Output
0 0 0 0 0 0
0 0 0 0 0 1
0 1 1 1 1 2
1 2 2 2 2 3
2 3 3 3 3 4
3 4 4 4 4 5
4 5 5 5 5 6
5 6 6 6 6 7
6 7 7 7 7 8
7 7 7 7 8 9
NoteConsider c = 3 and d = 2 from the first example: The first operation tries to move 2 liters of water from the second tank to the first one, the second tank has 2 liters available, the first tank can fit 1 more liter. Thus, \min(2, 2, 1) = 1 liter is moved, the first tank now contains 4 liters, the second tank now contains 1 liter. The second operation tries to move 1 liter of water from the first tank to the second one. \min(1, 4, 3) = 1 liter is moved, the first tank now contains 3 liters, the second tank now contains 2 liter. The third operation tries to move 2 liter of water from the first tank to the second one. \min(2, 3, 2) = 2 liters are moved, the first tank now contains 1 liter, the second tank now contains 4 liters. There's 1 liter of water in the first tank at the end. Thus, the third value in the fourth row is 1. | 3 4 4
-2 1 2
| 0 0 0 0 0 0 0 0 0 1 0 0 1 1 2 0 1 1 2 3 1 1 2 3 4 | 2 seconds | 256 megabytes | ['binary search', 'dp', 'implementation', 'math', '*2400'] |
D. Binary String Sortingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string s consisting of only characters 0 and/or 1.You can perform several operations on this string (possibly zero). There are two types of operations: choose two consecutive elements and swap them. In order to perform this operation, you pay 10^{12} coins; choose any element from the string and remove it. In order to perform this operation, you pay 10^{12}+1 coins. Your task is to calculate the minimum number of coins required to sort the string s in non-decreasing order (i. e. transform s so that s_1 \le s_2 \le \dots \le s_m, where m is the length of the string after applying all operations). An empty string is also considered sorted in non-decreasing order.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The only line of each test case contains the string s (1 \le |s| \le 3 \cdot 10^5), consisting of only characters 0 and/or 1.The sum of lengths of all given strings doesn't exceed 3 \cdot 10^5.OutputFor each test case, print a single integer — the minimum number of coins required to sort the string s in non-decreasing order.ExampleInput
61000010100101101100110111111Output
1000000000001
0
1000000000000
2000000000001
2000000000002
0
NoteIn the first example, you have to remove the 1-st element, so the string becomes equal to 00.In the second example, the string is already sorted.In the third example, you have to swap the 2-nd and the 3-rd elements, so the string becomes equal to 0011.In the fourth example, you have to swap the 3-rd and the 4-th elements, so the string becomes equal to 00011101, and then remove the 7-th element, so the string becomes equal to 0001111.In the fifth example, you have to remove the 1-st element, so the string becomes equal to 001101, and then remove the 5-th element, so the string becomes equal to 00111.In the sixth example, the string is already sorted. | 61000010100101101100110111111 | 1000000000001 0 1000000000000 2000000000001 2000000000002 0 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', '*1800'] |
C. Sum on Subarraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputFor an array a = [a_1, a_2, \dots, a_n], let's denote its subarray a[l, r] as the array [a_l, a_{l+1}, \dots, a_r].For example, the array a = [1, -3, 1] has 6 non-empty subarrays: a[1,1] = [1]; a[1,2] = [1,-3]; a[1,3] = [1,-3,1]; a[2,2] = [-3]; a[2,3] = [-3,1]; a[3,3] = [1]. You are given two integers n and k. Construct an array a consisting of n integers such that: all elements of a are from -1000 to 1000; a has exactly k subarrays with positive sums; the rest \dfrac{(n+1) \cdot n}{2}-k subarrays of a have negative sums. InputThe first line contains one integer t (1 \le t \le 5000) — the number of test cases.Each test case consists of one line containing two integers n and k (2 \le n \le 30; 0 \le k \le \dfrac{(n+1) \cdot n}{2}).OutputFor each test case, print n integers — the elements of the array meeting the constraints. It can be shown that the answer always exists. If there are multiple answers, print any of them.ExampleInput
43 22 02 24 6Output
1 -3 1
-13 -42
-13 42
-3 -4 10 -2
| 43 22 02 24 6 | 1 -3 1 -13 -42 -13 42 -3 -4 10 -2 | 2 seconds | 512 megabytes | ['constructive algorithms', 'greedy', 'math', '*1500'] |
B. Points on Planetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a two-dimensional plane, and you need to place n chips on it. You can place a chip only at a point with integer coordinates. The cost of placing a chip at the point (x, y) is equal to |x| + |y| (where |a| is the absolute value of a).The cost of placing n chips is equal to the maximum among the costs of each chip.You need to place n chips on the plane in such a way that the Euclidean distance between each pair of chips is strictly greater than 1, and the cost is the minimum possible.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Next t cases follow.The first and only line of each test case contains one integer n (1 \le n \le 10^{18}) — the number of chips you need to place.OutputFor each test case, print a single integer — the minimum cost to place n chips if the distance between each pair of chips must be strictly greater than 1.ExampleInput
4135975461057789971042Output
0
1
2
987654321
NoteIn the first test case, you can place the only chip at point (0, 0) with total cost equal to 0 + 0 = 0.In the second test case, you can, for example, place chips at points (-1, 0), (0, 1) and (1, 0) with costs |-1| + |0| = 1, |0| + |1| = 1 and |0| + |1| = 1. Distance between each pair of chips is greater than 1 (for example, distance between (-1, 0) and (0, 1) is equal to \sqrt{2}). The total cost is equal to \max(1, 1, 1) = 1.In the third test case, you can, for example, place chips at points (-1, -1), (-1, 1), (1, 1), (0, 0) and (0, 2). The total cost is equal to \max(2, 2, 2, 0, 2) = 2. | 4135975461057789971042 | 0 1 2 987654321 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'math', '*1000'] |
A. Garlandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a garland consisting of 4 colored light bulbs, the color of the i-th light bulb is s_i.Initially, all the light bulbs are turned off. Your task is to turn all the light bulbs on. You can perform the following operation any number of times: select a light bulb and switch its state (turn it on if it was off, and turn it off if it was on). The only restriction on the above operation is that you can apply the operation to a light bulb only if the previous operation was applied to a light bulb of a different color (the first operation can be applied to any light bulb).Calculate the minimum number of operations to turn all the light bulbs on, or report that this is impossible.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The single line of each test case contains s — a sequence of 4 characters, where each character is a decimal digit. The i-th character denotes the color of the i-th light bulb.OutputFor each test case, print one integer — the minimum number of operations to turn all the light bulbs on. If it is impossible to turn all the bulbs on, print -1.ExampleInput
3954600003313Output
4
-1
6
NoteIn the first example, all the colors are different, so you can just turn all the bulbs on in 4 operations.In the second example, it is impossible to turn all the bulbs on, because after you switch one light bulb, it is impossible to turn the others on.In the third example, you can proceed as follows: turn the first light bulb on, turn the third light bulb on, turn the fourth light bulb on, turn the third light bulb off, turn the second light bulb on, turn the third light bulb on. | 3954600003313 | 4 -1 6 | 2 seconds | 256 megabytes | ['implementation', '*800'] |
E3. Minibuses on Venus (hard version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference between the three versions is the constraints on n and k. You can make hacks only if all versions of the problem are solved.Maxim is a minibus driver on Venus.To ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting of n digits. However, as we know, the residents of Venus use a numeral system with base k, rather than the decimal system. Therefore, the ticket number can be considered as a sequence of n integers from 0 to k-1, inclusive.The residents of Venus consider a ticket to be lucky if there is a digit on it that is equal to the sum of the remaining digits, modulo k. For example, if k=10, then the ticket 7135 is lucky because 7 + 1 + 5 \equiv 3 \pmod{10}. On the other hand, the ticket 7136 is not lucky because no digit is equal to the sum of the others modulo 10.Once, while on a trip, Maxim wondered: how many lucky tickets exist? At the same time, Maxim understands that this number can be very large, so he is interested only in the answer modulo some prime number m. InputThe only line of the input contains three integers n, k and m (1 \le n \le 10^{18}, 1 \le k \le 2000, 10^8 \le m \le 10^9 + 7, m is a prime number) — the number of digits on the ticket, the base of the numeral system on Venus, and the module for answer calculation.OutputPrint one integer — the number of lucky tickets modulo m, i. e. the remainder after dividing the answer by m.ExamplesInput
3 2 1000000007
Output
4
Input
3 4 1000000007
Output
28
NoteIn the first example, there are only four lucky tickets: 000, 011, 101, and 110. | 3 2 1000000007
| 4 | 3 seconds | 256 megabytes | ['brute force', 'combinatorics', 'dp', 'math', '*2800'] |
E2. Minibuses on Venus (medium version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the medium version of the problem. The only difference between the three versions is the constraints on n and k. You can make hacks only if all versions of the problem are solved.Maxim is a minibus driver on Venus.To ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting of n digits. However, as we know, the residents of Venus use a numeral system with base k, rather than the decimal system. Therefore, the ticket number can be considered as a sequence of n integers from 0 to k-1, inclusive.The residents of Venus consider a ticket to be lucky if there is a digit on it that is equal to the sum of the remaining digits, modulo k. For example, if k=10, then the ticket 7135 is lucky because 7 + 1 + 5 \equiv 3 \pmod{10}. On the other hand, the ticket 7136 is not lucky because no digit is equal to the sum of the others modulo 10.Once, while on a trip, Maxim wondered: how many lucky tickets exist? At the same time, Maxim understands that this number can be very large, so he is interested only in the answer modulo some prime number m. InputThe only line of the input contains three integers n, k and m (1 \le n \le 10^{18}, 1 \le k \le 100, 10^8 \le m \le 10^9 + 7, m is a prime number) — the number of digits on the ticket, the base of the numeral system on Venus, and the module for answer calculation.OutputPrint one integer — the number of lucky tickets modulo m, i. e. the remainder after dividing the answer by m.ExamplesInput
3 2 1000000007
Output
4
Input
3 4 1000000007
Output
28
NoteIn the first example, there are only four lucky tickets: 000, 011, 101, and 110. | 3 2 1000000007
| 4 | 3 seconds | 256 megabytes | ['combinatorics', 'divide and conquer', 'dp', 'matrices', '*2500'] |
E1. Minibuses on Venus (easy version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference between the three versions is the constraints on n and k. You can make hacks only if all versions of the problem are solved.Maxim is a minibus driver on Venus.To ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting of n digits. However, as we know, the residents of Venus use a numeral system with base k, rather than the decimal system. Therefore, the ticket number can be considered as a sequence of n integers from 0 to k-1, inclusive.The residents of Venus consider a ticket to be lucky if there is a digit on it that is equal to the sum of the remaining digits, modulo k. For example, if k=10, then the ticket 7135 is lucky because 7 + 1 + 5 \equiv 3 \pmod{10}. On the other hand, the ticket 7136 is not lucky because no digit is equal to the sum of the others modulo 10.Once, while on a trip, Maxim wondered: how many lucky tickets exist? At the same time, Maxim understands that this number can be very large, so he is interested only in the answer modulo some prime number m. InputThe only line of the input contains three integers n, k and m (1 \le n \le 100, 1 \le k \le 30, 10^8 \le m \le 10^9 + 7, m is a prime number) — the number of digits on the ticket, the base of the numeral system on Venus, and the module for answer calculation.OutputPrint one integer — the number of lucky tickets modulo m, i. e. the remainder after dividing the answer by m.ExamplesInput
3 2 1000000007
Output
4
Input
3 4 1000000007
Output
28
NoteIn the first example, there are only four lucky tickets: 000, 011, 101, and 110. | 3 2 1000000007
| 4 | 3 seconds | 256 megabytes | ['combinatorics', 'divide and conquer', 'dp', '*2200'] |
D. Petya, Petya, Petr, and Palindromestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya and his friend, the robot Petya++, have a common friend — the cyborg Petr#. Sometimes Petr# comes to the friends for a cup of tea and tells them interesting problems.Today, Petr# told them the following problem.A palindrome is a sequence that reads the same from left to right as from right to left. For example, [38, 12, 8, 12, 38], [1], and [3, 8, 8, 3] are palindromes.Let's call the palindromicity of a sequence a_1, a_2, \dots, a_n the minimum count of elements that need to be replaced to make this sequence a palindrome. For example, the palindromicity of the sequence [38, 12, 8, 38, 38] is 1 since it is sufficient to replace the number 38 at the fourth position with the number 12. And the palindromicity of the sequence [3, 3, 5, 5, 5] is two since you can replace the first two threes with fives, and the resulting sequence [5, 5, 5, 5, 5] is a palindrome.Given a sequence a of length n, and an odd integer k, you need to find the sum of palindromicity of all subarrays of length k, i. e., the sum of the palindromicity values for the sequences a_i, a_{i+1}, \dots, a_{i+k-1} for all i from 1 to n-k+1.The students quickly solved the problem. Can you do it too? InputThe first line of the input contains two integers n and k (1 \le n \le 2 \cdot 10^5, 1 \le k \le n, k is odd) — the length of the sequence and the length of subarrays for which it is necessary to determine whether they are palindromes.The second line of the input contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 2 \cdot 10^5) — the sequence itself.OutputOutput a single integer — the total palindromicity of all subarrays of length k.ExamplesInput
8 5
1 2 8 2 5 2 8 6
Output
4
Input
9 9
1 2 3 4 5 4 3 2 1
Output
0
NoteIn the first example, the palindromicity of the subarray [1, 2, 8, 2, 5] is 1, the palindromicity of the string [2, 8, 2, 5, 2] is also 1, the palindromicity of the string [8, 2, 5, 2, 8] is 0, and the palindromicity of the string [2, 5, 2, 8, 6] is 2. The total palindromicity is 1+1+0+2 = 4.In the second example, the only substring of length 9 coincides with the entire string, and its palindromicity is 0, so the answer is also 0. | 8 5
1 2 8 2 5 2 8 6
| 4 | 1.5 seconds | 256 megabytes | ['binary search', 'brute force', 'data structures', 'two pointers', '*2100'] |
C. Unlucky Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem, unlike problem A, you need to look for unluckiest number, not the luckiest one.Note that the constraints of this problem differ from such in problem A.Olympus City recently launched the production of personal starships. Now everyone on Mars can buy one and fly to other planets inexpensively.Each starship has a number —some positive integer x. Let's define the luckiness of a number x as the difference between the largest and smallest digits of that number. For example, 142857 has 8 as its largest digit and 1 as its smallest digit, so its luckiness is 8-1=7. And the number 111 has all digits equal to 1, so its luckiness is zero.Hateehc is a famous Martian blogger who often flies to different corners of the solar system. To release interesting videos even faster, he decided to buy himself a starship. When he came to the store, he saw starships with numbers from l to r inclusively. While in the store, Hateehc wanted to find a starship with the unluckiest number.Since there are a lot of starships in the store, and Hateehc can't program, you have to help the blogger and write a program that answers his question. InputThe first line contains an integer t (1 \le t \le 600) —the number of test cases.Each of the following t lines contains a description of the test case. The description consists of two integers l, r (1 \le l \le r \le 10^{18}) — the largest and smallest numbers of the starships in the store.OutputPrint t lines, one line for each test case, containing the unluckiest starship number in the store.If there are several ways to choose the unluckiest number, output any of them.ExampleInput
559 6342 4948 5390 901 100Output
63
44
53
90
1
NoteLet's look at two test examples: the luckiness of the number 59 is 9 - 5 = 4; the luckiness of 60 equals 6 - 0 = 6; the luckiness of 61 equals 6 - 1 = 5; the luckiness of 62 equals 6 - 2 = 4; the luckiness of 63 is 6 - 3 = 3. So the unluckiest number is 63.In the fifth test case, the unluckiest numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, so you are allowed to choose any of them. | 559 6342 4948 5390 901 100 | 63 44 53 90 1 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'greedy', 'implementation', '*1900'] |
B. Playing in a Casinotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output Galaxy Luck, a well-known casino in the entire solar system, introduces a new card game.In this game, there is a deck that consists of n cards. Each card has m numbers written on it. Each of the n players receives exactly one card from the deck.Then all players play with each other in pairs, and each pair of players plays exactly once. Thus, if there are, for example, four players in total, then six games are played: the first against the second, the first against the third, the first against the fourth, the second against the third, the second against the fourth and the third against the fourth.Each of these games determines the winner in some way, but the rules are quite complicated, so we will not describe them here. All that matters is how many chips are paid out to the winner. Let the first player's card have the numbers a_1, a_2, \dots, a_m, and the second player's card — b_1, b_2, \dots, b_m. Then the winner of the game gets |a_1 - b_1| + |a_2 - b_2| + \dots + |a_m - b_m| chips from the total pot, where |x| denotes the absolute value of x.To determine the size of the total pot, it is necessary to calculate the winners' total winnings for all games. Since there can be many cards in a deck and many players, you have been assigned to write a program that does all the necessary calculations.InputEach test consists of several test cases. The first line contains one integer t (1 \le t \le 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and m (1 \le n \cdot m \le 3\cdot 10^5) — the number of cards in the deck and the count of numbers on the one card.Each of the following n lines of the test case set contains m integers c_{i,j} (1 \le c_{i,j} \le 10^6) — a description of the i-th card.It is guaranteed that the total n \cdot m in all tests does not exceed 3 \cdot 10^5.OutputFor each test case, print one number — the total amount of winnings from all games.ExampleInput
33 51 4 2 8 57 9 2 1 43 8 5 3 11 44 15 1 104 31 2 33 2 11 2 14 2 7Output
50
0
31
NoteConsider the first test case.In the game between the first and second player, the winner receives |1-7| + |4-9| + |2-2| + |8-1| + |5-4| = 19 chips.In the game between the first and third player, the winner receives |1-3| + |4-8| + |2-5| + |8-3| + |5-1| = 18 in chips.In the game between the second and third player, the winner receives |7-3| + |9-8| + |2-5| + |1-3| + |4-1| = 13 chips.The total is 19 + 18 + 13 = 50 chips. | 33 51 4 2 8 57 9 2 1 43 8 5 3 11 44 15 1 104 31 2 33 2 11 2 14 2 7 | 50 0 31 | 2 seconds | 256 megabytes | ['math', 'sortings', '*1200'] |
A. Lucky Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOlympus City recently launched the production of personal starships. Now everyone on Mars can buy one and fly to other planets inexpensively.Each starship has a number —some positive integer x. Let's define the luckiness of a number x as the difference between the largest and smallest digits of that number. For example, 142857 has 8 as its largest digit and 1 as its smallest digit, so its luckiness is 8-1=7. And the number 111 has all digits equal to 1, so its luckiness is zero.Hateehc is a famous Martian blogger who often flies to different corners of the solar system. To release interesting videos even faster, he decided to buy himself a starship. When he came to the store, he saw starships with numbers from l to r inclusively. While in the store, Hateehc wanted to find a starship with the luckiest number.Since there are a lot of starships in the store, and Hateehc can't program, you have to help the blogger and write a program that answers his question. InputThe first line contains an integer t (1 \le t \le 10\,000) —the number of test cases.Each of the following t lines contains a description of the test case. The description consists of two integers l and r (1 \le l \le r \le 10^6) — the largest and smallest numbers of the starships in the store.OutputPrint t lines, one line for each test case, containing the luckiest starship number in the store.If there are several ways to choose the luckiest number, output any of them.ExampleInput
559 6342 4915 1553 571 100Output
60
49
15
57
90
NoteLet's look at two test examples: the luckiness of the number 59 is 9 - 5 = 4; the luckiness of 60 equals 6 - 0 = 6; the luckiness of 61 equals 6 - 1 = 5; the luckiness of 62 equals 6 - 2 = 4; the luckiness of 63 is 6 - 3 = 3. Thus, the luckiest number is 60.In the fifth test example, the luckiest number is 90. | 559 6342 4915 1553 571 100 | 60 49 15 57 90 | 1 second | 256 megabytes | ['brute force', 'implementation', '*900'] |
G2. Subsequence Addition (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the two versions is that in this version, the constraints are higher.Initially, array a contains just the number 1. You can perform several operations in order to change the array. In an operation, you can select some subsequence^{\dagger} of a and add into a an element equal to the sum of all elements of the subsequence. You are given a final array c. Check if c can be obtained from the initial array a by performing some number (possibly 0) of operations on the initial array.^{\dagger} A sequence b is a subsequence of a sequence a if b can be obtained from a by the deletion of several (possibly zero, but not all) elements. In other words, select k (1 \leq k \leq |a|) distinct indices i_1, i_2, \dots, i_k and insert anywhere into a a new element with the value equal to a_{i_1} + a_{i_2} + \dots + a_{i_k}.InputThe first line of the input contains an integer t (1 \leq t \leq 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the number of elements the final array c should have.The second line of each test case contains n space-separated integers c_i (1 \leq c_i \leq 2 \cdot 10^5) — the elements of the final array c that should be obtained from the initial 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 "YES" (without quotes) if such a sequence of operations exists, and "NO" (without quotes) otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput
6111255 1 3 2 157 1 5 2 131 1 151 1 4 2 1Output
YES
NO
YES
NO
YES
YES
NoteFor the first test case, the initial array a is already equal to [1], so the answer is "YES".For the second test case, performing any amount of operations will change a to an array of size at least two which doesn't only have the element 2, thus obtaining the array [2] is impossible and the answer is "NO".For the third test case, we can perform the following operations in order to obtain the final given array c: Initially, a = [1]. By choosing the subsequence [1], and inserting 1 in the array, a changes to [1, 1]. By choosing the subsequence [1, 1], and inserting 1+1=2 in the middle of the array, a changes to [1, 2, 1]. By choosing the subsequence [1, 2], and inserting 1+2=3 after the first 1 of the array, a changes to [1, 3, 2, 1]. By choosing the subsequence [1, 3, 1] and inserting 1+3+1=5 at the beginning of the array, a changes to [5, 1, 3, 2, 1] (which is the array we needed to obtain). | 6111255 1 3 2 157 1 5 2 131 1 151 1 4 2 1 | YES NO YES NO YES YES | 2 seconds | 256 megabytes | ['bitmasks', 'dp', 'greedy', 'implementation', 'sortings', '*1100'] |
G1. Subsequence Addition (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the two versions is that in this version, the constraints are lower.Initially, array a contains just the number 1. You can perform several operations in order to change the array. In an operation, you can select some subsequence^{\dagger} of a and add into a an element equal to the sum of all elements of the subsequence. You are given a final array c. Check if c can be obtained from the initial array a by performing some number (possibly 0) of operations on the initial array.^{\dagger} A sequence b is a subsequence of a sequence a if b can be obtained from a by the deletion of several (possibly zero, but not all) elements. In other words, select k (1 \leq k \leq |a|) distinct indices i_1, i_2, \dots, i_k and insert anywhere into a a new element with the value equal to a_{i_1} + a_{i_2} + \dots + a_{i_k}.InputThe first line of the input contains an integer t (1 \leq t \leq 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 5000) — the number of elements the final array c should have.The second line of each test case contains n space-separated integers c_i (1 \leq c_i \leq 5000) — the elements of the final array c that should be obtained from the initial array a.It is guaranteed that the sum of n over all test cases does not exceed 5000.OutputFor each test case, output "YES" (without quotes) if such a sequence of operations exists, and "NO" (without quotes) otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput
6111255 1 3 2 157 1 5 2 131 1 151 1 4 2 1Output
YES
NO
YES
NO
YES
YES
NoteFor the first test case, the initial array a is already equal to [1], so the answer is "YES".For the second test case, performing any amount of operations will change a to an array of size at least two which doesn't only have the element 2, thus obtaining the array [2] is impossible and the answer is "NO".For the third test case, we can perform the following operations in order to obtain the final given array c: Initially, a = [1]. By choosing the subsequence [1], and inserting 1 in the array, a changes to [1, 1]. By choosing the subsequence [1, 1], and inserting 1+1=2 in the middle of the array, a changes to [1, 2, 1]. By choosing the subsequence [1, 2], and inserting 1+2=3 after the first 1 of the array, a changes to [1, 3, 2, 1]. By choosing the subsequence [1, 3, 1] and inserting 1+3+1=5 at the beginning of the array, a changes to [5, 1, 3, 2, 1] (which is the array we needed to obtain). | 6111255 1 3 2 157 1 5 2 131 1 151 1 4 2 1 | YES NO YES NO YES YES | 2 seconds | 256 megabytes | ['brute force', 'data structures', 'dp', 'greedy', 'implementation', 'sortings', '*1100'] |
F. Bouncy Balltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a room that can be represented by a n \times m grid. There is a ball at position (i_1, j_1) (the intersection of row i_1 and column j_1), and it starts going diagonally in one of the four directions: The ball is going down and right, denoted by \texttt{DR}; it means that after a step, the ball's location goes from (i, j) to (i+1, j+1). The ball is going down and left, denoted by \texttt{DL}; it means that after a step, the ball's location goes from (i, j) to (i+1, j-1). The ball is going up and right, denoted by \texttt{UR}; it means that after a step, the ball's location goes from (i, j) to (i-1, j+1). The ball is going up and left, denoted by \texttt{UL}; it means that after a step, the ball's location goes from (i, j) to (i-1, j-1). After each step, the ball maintains its direction unless it hits a wall (that is, the direction takes it out of the room's bounds in the next step). In this case, the ball's direction gets flipped along the axis of the wall; if the ball hits a corner, both directions get flipped. Any instance of this is called a bounce. The ball never stops moving. In the above example, the ball starts at (1, 7) and goes \texttt{DL} until it reaches the bottom wall, then it bounces and continues in the direction \texttt{UL}. After reaching the left wall, the ball bounces and continues to go in the direction \texttt{UR}. When the ball reaches the upper wall, it bounces and continues in the direction \texttt{DR}. After reaching the bottom-right corner, it bounces once and continues in direction \texttt{UL}, and so on.Your task is to find how many bounces the ball will go through until it reaches cell (i_2, j_2) in the room, or report that it never reaches cell (i_2, j_2) by printing -1.Note that the ball first goes in a cell and only after that bounces if it needs to.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 six integers and a string n, m, i_1, j_1, i_2, j_2, d (2 \leq n, m \leq 25000; 1 \leq i_1, i_2 \leq n; 1 \leq j_1, j_2 \leq m; d \in\{ \texttt{DR}, \texttt{DL}, \texttt{UR}, \texttt{UL}\}) — the dimensions of the grid, the starting coordinates of the ball, the coordinates of the final cell and the starting direction of the ball.It is guaranteed that the sum of n \cdot m over all test cases does not exceed 5 \cdot 10^4.OutputFor each test case, output a single integer — the number of bounces the ball does until it reaches cell (i_2, j_2) for the first time, or -1 if the ball never reaches the final cell.ExampleInput
65 7 1 7 2 4 DL5 7 1 7 3 2 DL3 3 1 3 2 2 UR2 4 2 1 2 2 DR4 3 1 1 1 3 UL6 4 1 2 3 4 DROutput
3
-1
1
-1
4
0
| 65 7 1 7 2 4 DL5 7 1 7 3 2 DL3 3 1 3 2 2 UR2 4 2 1 2 2 DR4 3 1 1 1 3 UL6 4 1 2 3 4 DR | 3 -1 1 -1 4 0 | 1 second | 256 megabytes | ['brute force', 'dfs and similar', 'implementation', '*1700'] |
E. Interviewtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. If you are unsure how interactive problems work, then it is recommended to read the guide for participants.Before the last stage of the exam, the director conducted an interview. He gave Gon n piles of stones, the i-th pile having a_i stones.Each stone is identical and weighs 1 grams, except for one special stone that is part of an unknown pile and weighs 2 grams. A picture of the first test case. Pile 2 has the special stone. The piles have weights of 1,3,3,4,5, respectively. Gon can only ask the director questions of one kind: he can choose k piles, and the director will tell him the total weight of the piles chosen. More formally, Gon can choose an integer k (1 \leq k \leq n) and k unique piles p_1, p_2, \dots, p_k (1 \leq p_i \leq n), and the director will return the total weight m_{p_1} + m_{p_2} + \dots + m_{p_k}, where m_i denotes the weight of pile i. Gon is tasked with finding the pile that contains the special stone. However, the director is busy. Help Gon find this pile in at most \mathbf{30} queries.InputThe input data contains several test cases. The first line contains one integer t (1 \leq t \leq 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the number of piles.The second line of each test case contains n integers a_i (1 \leq a_i \leq 10^4) — the number of stones in each pile.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.After reading the input for each test case, proceed with the interaction as follows.InteractionYou can perform the operation at most \mathbf{30} times to guess the pile. To make a guess, print a line with the following format: \texttt{?}\ k \ p_1 \ p_2 \ p_3 \ ... \ p_{k-1}\ p_k (1 \leq k \leq n; 1 \leq p_i \leq n; all p_i are distinct) — the indices of the piles. After each operation, you should read a line containing a single integer x — the sum of weights of the chosen piles. (Formally, x = m_{p_1} + m_{p_2} + \dots + m_{p_k}.)When you know the index of the pile with the special stone, print one line in the following format: \texttt{!}\ m (1 \leq m \leq n).After that, move on to the next test case, or terminate the program if there are no more test cases remaining.If your program performs more than 30 operations for one test case or makes an invalid query, you may receive a Wrong Answer verdict.After you print a query or the answer, please remember to output the end of the line and flush the output. Otherwise, you may get Idleness limit exceeded or some other verdict. To do this, use the following: 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. It is additionally recommended to read the interactive problems guide for participants.HacksTo make a hack, use the following format.The first line should contain a single integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case should contain two integers n, m (1 \leq n \leq 2 \cdot 10^5) – the number of piles and the pile with the special stone.The second line of each test case should contain n integers a_i (1 \leq a_i \leq 10^4) — the number of stones in each pile.Note that the interactor is not adaptive, meaning that the answer is known before the participant asks the queries and doesn't depend on the queries asked by the participant.ExampleInput
2
5
1 2 3 4 5
11
6
3
7
1 2 3 5 3 4 2
12
6
Output
? 4 1 2 3 4
? 2 2 3
? 1 2
! 2
? 4 2 3 5 6
? 2 1 4
! 7
NoteIn the first test case, the stone with weight two is located in pile 2, as shown in the picture. We perform the following interaction: \texttt{? 4 1 2 3 4} — ask the total weight of piles 1, 2, 3, and 4. The total weight we receive back is 1+3+3+4=11. \texttt{? 2 2 3} — ask the total weight of piles 2 and 3. The total weight we receive back is 3+3=6. \texttt{? 1 2} — ask the total weight of pile 2. The total weight we receive back is 3. \texttt{! 2} — we have figured out that pile 2 contains the special stone, so we output it and move on to the next test case. In the second test case, the stone with weight two is located on index 7. We perform the following interaction: \texttt{? 4 2 3 5 6} — ask the total weight of piles 2, 3, 5, and 6. The total weight we receive back is 2+3+3+4=12. \texttt{? 2 1 4} — ask the total weight of piles 1 and 4. The total weight we receive back is 1+5=6. \texttt{! 7} — we have somehow figured out that pile 7 contains the special stone, so we output it and end the interaction. | 2
5
1 2 3 4 5
11
6
3
7
1 2 3 5 3 4 2
12
6
| ? 4 1 2 3 4 ? 2 2 3 ? 1 2 ! 2 ? 4 2 3 5 6 ? 2 1 4 ! 7 | 2 seconds | 256 megabytes | ['binary search', 'implementation', 'interactive', '*1300'] |
D. Odd Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a_1, a_2, \dots, a_n. Answer q queries of the following form: If we change all elements in the range a_l, a_{l+1}, \dots, a_r of the array to k, will the sum of the entire array be odd? Note that queries are independent and do not affect future queries.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case consists of 2 integers n and q (1 \le n \le 2 \cdot 10^5; 1 \le q \le 2 \cdot 10^5) — the length of the array and the number of queries.The second line of each test case consists of n integers a_i (1 \le a_i \le 10^9) — the array a.The next q lines of each test case consists of 3 integers l,r,k (1 \le l \le r \le n; 1 \le k \le 10^9) — the queries.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5, and the sum of q doesn't exceed 2 \cdot 10^5.OutputFor each query, output "YES" if the sum of the entire array becomes odd, and "NO" otherwise.You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput
25 52 2 1 3 22 3 32 3 41 5 51 4 92 4 310 51 1 1 1 1 1 1 1 1 13 8 132 5 103 8 101 10 21 9 100Output
YES
YES
YES
NO
YES
NO
NO
NO
NO
YES
NoteFor the first test case: If the elements in the range (2, 3) would get set to 3 the array would become \{2, 3, 3, 3, 2\}, the sum would be 2+3+3+3+2 = 13 which is odd, so the answer is "YES". If the elements in the range (2, 3) would get set to 4 the array would become \{2, 4, 4, 3, 2\}, the sum would be 2+4+4+3+2 = 15 which is odd, so the answer is "YES". If the elements in the range (1, 5) would get set to 5 the array would become \{5, 5, 5, 5, 5\}, the sum would be 5+5+5+5+5 = 25 which is odd, so the answer is "YES". If the elements in the range (1, 4) would get set to 9 the array would become \{9, 9, 9, 9, 2\}, the sum would be 9+9+9+9+2 = 38 which is even, so the answer is "NO". If the elements in the range (2, 4) would get set to 3 the array would become \{2, 3, 3, 3, 2\}, the sum would be 2+3+3+3+2 = 13 which is odd, so the answer is "YES". | 25 52 2 1 3 22 3 32 3 41 5 51 4 92 4 310 51 1 1 1 1 1 1 1 1 13 8 132 5 103 8 101 10 21 9 100 | YES YES YES NO YES NO NO NO NO YES | 2 seconds | 256 megabytes | ['data structures', 'implementation', '*900'] |
C. Find and Replacetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of lowercase Latin characters. In an operation, you can take a character and replace all occurrences of this character with \texttt{0} or replace all occurrences of this character with \texttt{1}.Is it possible to perform some number of moves so that the resulting string is an alternating binary string^{\dagger}? For example, consider the string \texttt{abacaba}. You can perform the following moves: Replace \texttt{a} with \texttt{0}. Now the string is \color{red}{\texttt{0}}\texttt{b}\color{red}{\texttt{0}}\texttt{c}\color{red}{\texttt{0}}\texttt{b}\color{red}{\texttt{0}}. Replace \texttt{b} with \texttt{1}. Now the string is {\texttt{0}}\color{red}{\texttt{1}}{\texttt{0}}\texttt{c}{\texttt{0}}\color{red}{\texttt{1}}{\texttt{0}}. Replace \texttt{c} with \texttt{1}. Now the string is {\texttt{0}}{\texttt{1}}{\texttt{0}}\color{red}{\texttt{1}}{\texttt{0}}{\texttt{1}}{\texttt{0}}. This is an alternating binary string. ^{\dagger}An alternating binary string is a string of \texttt{0}s and \texttt{1}s such that no two adjacent bits are equal. For example, \texttt{01010101}, \texttt{101}, \texttt{1} are alternating binary strings, but \texttt{0110}, \texttt{0a0a0}, \texttt{10100} are not.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 2000) — the length of the string s.The second line of each test case contains a string consisting of n lowercase Latin characters — the string s.OutputFor each test case, output "YES" (without quotes) if you can make the string into an alternating binary string, and "NO" (without quotes) otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput
87abacaba2aa1y4bkpt6ninfia6banana10codeforces8testcaseOutput
YES
NO
YES
YES
NO
YES
NO
NO
NoteThe first test case is explained in the statement.In the second test case, the only possible binary strings you can make are \texttt{00} and \texttt{11}, neither of which are alternating.In the third test case, you can make \texttt{1}, which is an alternating binary string. | 87abacaba2aa1y4bkpt6ninfia6banana10codeforces8testcase | YES NO YES YES NO YES NO NO | 1 second | 256 megabytes | ['greedy', 'implementation', 'strings', '*800'] |
B. Grab the Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMihai and Bianca are playing with bags of candies. They have a row a of n bags of candies. The i-th bag has a_i candies. The bags are given to the players in the order from the first bag to the n-th bag. If a bag has an even number of candies, Mihai grabs the bag. Otherwise, Bianca grabs the bag. Once a bag is grabbed, the number of candies in it gets added to the total number of candies of the player that took it. Mihai wants to show off, so he wants to reorder the array so that at any moment (except at the start when they both have no candies), Mihai will have strictly more candies than Bianca. Help Mihai find out if such a reordering exists.InputThe first line of the input contains an integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 100) — the number of bags in the array.The second line of each test case contains n space-separated integers a_i (1 \leq a_i \leq 100) — the number of candies in each bag.OutputFor each test case, output "YES" (without quotes) if such a reordering exists, and "NO" (without quotes) otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput
341 2 3 441 1 1 231 4 3Output
YES
NO
NO
NoteIn the first test case, Mihai can reorder the array as follows: [4, 1, 2, 3]. Then the process proceeds as follows: the first bag has 4 candies, which is even, so Mihai takes it — Mihai has 4 candies, and Bianca has 0. the second bag has 1 candies, which is odd, so Bianca takes it — Mihai has 4 candies, and Bianca has 1. the third bag has 2 candies, which is even, so Mihai takes it — Mihai has 6 candies, and Bianca has 1. the fourth bag has 3 candies, which is odd, so Bianca takes it — Mihai has 6 candies, and Bianca has 4. Since Mihai always has more candies than Bianca, this reordering works. | 341 2 3 441 1 1 231 4 3 | YES NO NO | 1 second | 256 megabytes | ['greedy', '*800'] |
A. Plus or Minustime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a, b, and c such that exactly one of these two equations is true: a+b=c a-b=c Output + if the first equation is true, and - otherwise.InputThe first line contains a single integer t (1 \leq t \leq 162) — the number of test cases.The description of each test case consists of three integers a, b, c (1 \leq a, b \leq 9, -8 \leq c \leq 18). The additional constraint on the input: it will be generated so that exactly one of the two equations will be true.OutputFor each test case, output either + or - on a new line, representing the correct equation.ExampleInput
111 2 33 2 12 9 -73 4 71 1 21 1 03 3 69 9 189 9 01 9 -81 9 10Output
+
-
-
+
+
-
+
+
-
-
+
NoteIn the first test case, 1+2=3.In the second test case, 3-2=1.In the third test case, 2-9=-7. Note that c can be negative. | 111 2 33 2 12 9 -73 4 71 1 21 1 03 3 69 9 189 9 01 9 -81 9 10 | + - - + + - + + - - + | 1 second | 256 megabytes | ['implementation', '*800'] |
F2. GCD Master (hard version)time limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference between the two versions is the constraint on m. You can make hacks only if both versions of the problem are solved.You are given an array a of length n and two integers m and k. Each element in a satisfies 1\le a_i \le m.In one operation, you choose two indices i and j such that 1 \le i < j \le |a|, then append \gcd(a_i,a_j) to the back of the array and delete a_i and a_j from the array. Note that the length of the array decreases by one after this operation.Find the maximum possible sum of the array after performing exactly k operations.InputThe first line contains a single integer t (1\le t\le 10^5) — the number of test cases. The description of test cases follows.The first line of each test case contains three integers n, m and k (2 \le n \le 10^6; 1\le m \le 9\cdot 10^{18}; 1 \le k \le n-1).The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1 \le a_i \le m).It is guaranteed that the sum of n over all test cases does not exceed 10^6.OutputFor each test case, output the maximum possible sum of the array after performing k operations optimally.ExampleInput
43 8 14 7 85 114514 27 2 4 1 63 1919810 22 3 33 9000000000000000000 19000000000000000000 9000000000000000000 9000000000000000000Output
11
14
1
18000000000000000000
NoteIn the first test case, the best way is to choose i=1, j=3 in the first operation. The final sequence is [7,4]. | 43 8 14 7 85 114514 27 2 4 1 63 1919810 22 3 33 9000000000000000000 19000000000000000000 9000000000000000000 9000000000000000000 | 11 14 1 18000000000000000000 | 3 seconds | 1024 megabytes | ['greedy', 'math', 'sortings', '*2900'] |
F1. GCD Master (easy version)time limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference between the two versions is the constraint on m. You can make hacks only if both versions of the problem are solved.You are given an array a of length n and two integers m and k. Each element in a satisfies 1\le a_i \le m.In one operation, you choose two indices i and j such that 1 \le i < j \le |a|, then append \gcd(a_i,a_j) to the back of the array and delete a_i and a_j from the array. Note that the length of the array decreases by one after this operation.Find the maximum possible sum of the array after performing exactly k operations.InputThe first line contains a single integer t (1\le t\le 10^5) — the number of test cases. The description of test cases follows.The first line of each test case contains three integers n, m and k (2 \le n \le 10^6; 1\le m \le 10^6; 1 \le k \le n-1).The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1 \le a_i \le m).It is guaranteed that the sum of n over all test cases does not exceed 10^6 and the sum of m over all test cases does not exceed 10^6.OutputFor each test case, output the maximum possible sum of the array after performing k operations optimally.ExampleInput
33 8 14 7 85 114 27 2 4 1 63 514 22 3 3Output
11
14
1
NoteIn the first test case, the best way is to choose i=1, j=3 in the first operation. The final sequence is [7,4]. | 33 8 14 7 85 114 27 2 4 1 63 514 22 3 3 | 11 14 1 | 3 seconds | 1024 megabytes | ['greedy', 'math', 'number theory', 'sortings', '*2900'] |
E. Tree Mastertime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a tree with n weighted vertices labeled from 1 to n rooted at vertex 1. The parent of vertex i is p_i and the weight of vertex i is a_i. For convenience, define p_1=0.For two vertices x and y of the same depth^\dagger, define f(x,y) as follows: Initialize \mathrm{ans}=0. While both x and y are not 0: \mathrm{ans}\leftarrow \mathrm{ans}+a_x\cdot a_y; x\leftarrow p_x; y\leftarrow p_y. f(x,y) is the value of \mathrm{ans}. You will process q queries. In the i-th query, you are given two integers x_i and y_i and you need to calculate f(x_i,y_i).^\dagger The depth of vertex v is the number of edges on the unique simple path from the root of the tree to vertex v. InputThe first line contains two integers n and q (2 \le n \le 10^5; 1 \le q \le 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^5).The third line contains n-1 integers p_2, \ldots, p_n (1 \le p_i < i).Each of the next q lines contains two integers x_i and y_i (1\le x_i,y_i\le n). It is guaranteed that x_i and y_i are of the same depth.OutputOutput q lines, the i-th line contains a single integer, the value of f(x_i,y_i).ExamplesInput
6 2
1 5 2 3 1 1
1 2 3 3 2
4 5
6 6
Output
33
27
Input
14 8
3 2 5 3 1 4 2 2 2 5 5 5 2 4
1 2 3 1 1 4 7 3 3 1 5 3 8
4 4
4 10
13 10
3 12
13 9
3 12
9 10
11 5
Output
47
53
48
36
42
36
48
14
NoteConsider the first example:In the first query, the answer is a_4\cdot a_5+a_3\cdot a_3+a_2\cdot a_2+a_1\cdot a_1=3+4+25+1=33.In the second query, the answer is a_6\cdot a_6+a_2\cdot a_2+a_1\cdot a_1=1+25+1=27. | 6 2
1 5 2 3 1 1
1 2 3 3 2
4 5
6 6
| 33 27 | 3 seconds | 1024 megabytes | ['brute force', 'data structures', 'dfs and similar', 'trees', '*2200'] |
D. DSU Mastertime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given an integer n and an array a of length n-1 whose elements are either 0 or 1.Let us define the value of a permutation^\dagger p of length m-1 (m \leq n) by the following process.Let G be a graph of m vertices labeled from 1 to m that does not contain any edges. For each i from 1 to m-1, perform the following operations: define u and v as the (unique) vertices in the weakly connected components^\ddagger containing vertices p_i and p_i+1 respectively with only incoming edges^{\dagger\dagger}; in graph G, add a directed edge from vertex v to u if a_{p_i}=0, otherwise add a directed edge from vertex u to v (if a_{p_i}=1). Note that after each step, it can be proven that each weakly connected component of G has a unique vertex with only incoming edges.Then, the value of p is the number of incoming edges of vertex 1 of G.For each k from 1 to n-1, find the sum of values of all k! permutations of length k. Since this value can be big, you are only required to compute this value under modulo 998\,244\,353. Operations when n=3, a=[0,1] and p=[1,2] ^\dagger 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).^\ddagger The weakly connected components of a directed graph is the same as the components of the undirected version of the graph. Formally, for directed graph G, define a graph H where for all edges a \to b in G, you add an undirected edge a \leftrightarrow b in H. Then the weakly connected components of G are the components of H.^{\dagger\dagger} Note that a vertex that has no edges is considered to have only incoming edges.InputThe first line contains a single integer t (1\le t\le 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2\le n\le 5 \cdot 10^5).The second line of each test case contains n-1 integers a_1, a_2, \ldots, a_{n-1} (a_i is 0 or 1).It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^5.OutputFor each test case, output n-1 integers in a line, the i-th integer should represent the answer when k=i, under modulo 998\,244\,353.ExampleInput
230 090 1 0 0 0 1 0 0Output
1 3
1 2 7 31 167 1002 7314 60612
NoteConsider the first test case.When k=1, there is only 1 permutation p. When p=[1], we will add a single edge from vertex 2 to 1. Vertex 1 will have 1 incoming edge. So the value of [1] is 1. Therefore when k=1, the answer is 1.When k=2, there are 2 permutations p. When p=[1,2], we will add an edge from vertex 2 to 1 and an edge from 3 to 1. Vertex 1 will have 2 incoming edges. So the value of [1,2] is 2. When p=[2,1], we will add an edge from vertex 3 to 2 and an edge from 2 to 1. Vertex 1 will have 1 incoming edge. So the value of [2,1] is 1. Therefore when k=2, the answer is 2+1=3. | 230 090 1 0 0 0 1 0 0 | 1 3 1 2 7 31 167 1002 7314 60612 | 2 seconds | 1024 megabytes | ['combinatorics', 'dp', 'dsu', 'math', '*2500'] |
C. Sequence Mastertime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFor some positive integer m, YunQian considers an array q of 2m (possibly negative) integers good, if and only if for every possible subsequence of q that has length m, the product of the m elements in the subsequence is equal to the sum of the m elements that are not in the subsequence. Formally, let U=\{1,2,\ldots,2m\}. For all sets S \subseteq U such that |S|=m, \prod\limits_{i \in S} q_i = \sum\limits_{i \in U \setminus S} q_i.Define the distance between two arrays a and b both of length k to be \sum\limits_{i=1}^k|a_i-b_i|.You are given a positive integer n and an array p of 2n integers.Find the minimum distance between p and q over all good arrays q of length 2n. It can be shown for all positive integers n, at least one good array exists. Note that you are not required to construct the array q that achieves this minimum distance.InputThe first line contains a single integer t (1\le t\le 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1\le n\le 2\cdot10^5).The second line of each test case contains 2n integers p_1, p_2, \ldots, p_{2n} (|p_i| \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, output the minimum distance between p and a good q.ExampleInput
416 921 2 2 12-2 -2 2 24-3 -2 -1 0 1 2 3 4Output
3
2
5
13
NoteIn the first test case, it is optimal to let q=[6,6].In the second test case, it is optimal to let q=[2,2,2,2]. | 416 921 2 2 12-2 -2 2 24-3 -2 -1 0 1 2 3 4 | 3 2 5 13 | 1 second | 1024 megabytes | ['brute force', 'constructive algorithms', 'math', '*1600'] |
B. Mex Mastertime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n. The score of a is the MEX^{\dagger} of [a_1+a_2,a_2+a_3,\ldots,a_{n-1}+a_n]. Find the minimum score of a if you are allowed to rearrange elements of a in any order. Note that you are not required to construct the array a that achieves the minimum score.^{\dagger} The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance: The MEX of [2,2,1] is 0, because 0 does not belong to the array. The MEX of [3,1,0,1] is 2, because 0 and 1 belong to the array, but 2 does not. The MEX of [0,3,1,2] is 4 because 0, 1, 2, and 3 belong to the array, but 4 does not. InputThe first line contains a single integer t (1\le t\le 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2\le n\le 2\cdot10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 2\cdot 10^5).It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, output the minimum score of a after rearranging the elements of a in any order.ExampleInput
320 030 0 181 0 0 0 2 0 3 0Output
1
0
1
NoteIn the first test case, it is optimal to rearrange a as [0,0], the score of this array is the MEX of [0+0]=[0], which is 1.In the second test case, it is optimal to rearrange a as [0,1,0], the score of this array is the MEX of [0+1,1+0]=[1,1], which is 0. | 320 030 0 181 0 0 0 2 0 3 0 | 1 0 1 | 1 second | 1024 megabytes | ['constructive algorithms', 'greedy', '*900'] |
A. Walking Mastertime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYunQian is standing on an infinite plane with the Cartesian coordinate system on it. In one move, she can move to the diagonally adjacent point on the top right or the adjacent point on the left.That is, if she is standing on point (x,y), she can either move to point (x+1,y+1) or point (x-1,y).YunQian initially stands at point (a,b) and wants to move to point (c,d). Find the minimum number of moves she needs to make or declare that it is impossible.InputThe first line contains a single integer t (1\le t\le 10^4) — the number of test cases. The description of test cases follows.The first line and only line of each test case contain four integers a, b, c, d (-10^8\le a,b,c,d\le 10^8).OutputFor each test case, if it is possible to move from point (a,b) to point (c,d), output the minimum number of moves. Otherwise, output -1.ExampleInput
6-1 0 -1 20 0 4 5-2 -1 1 1-3 2 -3 22 -1 -1 -11 1 0 2Output
4
6
-1
0
3
3
NoteIn the first test case, one possible way using 4 moves is (-1,0)\to (0,1)\to (-1,1)\to (0,2)\to (-1,2). It can be proven that it is impossible to move from point (-1,0) to point (-1,2) in less than 4 moves. | 6-1 0 -1 20 0 4 5-2 -1 1 1-3 2 -3 22 -1 -1 -11 1 0 2 | 4 6 -1 0 3 3 | 1 second | 1024 megabytes | ['geometry', 'greedy', 'math', '*800'] |
F2. Survival of the Weakest (hard version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. It differs from the easy one only in constraints on n. You can make hacks only if you lock both versions.Let a_1, a_2, \ldots, a_n be an array of non-negative integers. Let F(a_1, a_2, \ldots, a_n) be the sorted in the non-decreasing order array of n - 1 smallest numbers of the form a_i + a_j, where 1 \le i < j \le n. In other words, F(a_1, a_2, \ldots, a_n) is the sorted in the non-decreasing order array of n - 1 smallest sums of all possible pairs of elements of the array a_1, a_2, \ldots, a_n. For example, F(1, 2, 5, 7) = [1 + 2, 1 + 5, 2 + 5] = [3, 6, 7].You are given an array of non-negative integers a_1, a_2, \ldots, a_n. Determine the single element of the array \underbrace{F(F(F\ldots F}_{n-1}(a_1, a_2, \ldots, a_n)\ldots)). Since the answer can be quite large, output it modulo 10^9+7.InputThe first line contains one integer n (2 \le n \le 2 \cdot 10^5) — the initial length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — the array elements.OutputOutput a single number — the answer modulo 10^9 + 7.ExamplesInput
5
1 2 4 5 6
Output
34
Input
9
1 1 1 7 7 7 9 9 9
Output
256
Input
7
1 7 9 2 0 0 9
Output
20
Input
3
1000000000 1000000000 777
Output
1540
NoteIn the first test, the array is transformed as follows: [1, 2, 4, 5, 6] \to [3, 5, 6, 6] \to [8, 9, 9] \to [17, 17] \to [34]. The only element of the final array is 34.In the second test, F(a_1, a_2, \ldots, a_n) is [2, 2, 2, 8, 8, 8, 8, 8]. This array is made up of 3 numbers of the form 1 + 1 and 5 numbers of the form 1 + 7. In the fourth test, the array is transformed as follows: [10^9, 10^9, 777] \to [10^9+777, 10^9+777] \to [2 \cdot 10^9 + 1554]. 2 \cdot 10^9 + 1554 modulo 10^9+7 equals 1540. | 5
1 2 4 5 6
| 34 | 3 seconds | 256 megabytes | ['greedy', 'math', 'sortings', 'two pointers', '*3100'] |
F1. Survival of the Weakest (easy version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. It differs from the hard one only in constraints on n. You can make hacks only if you lock both versions.Let a_1, a_2, \ldots, a_n be an array of non-negative integers. Let F(a_1, a_2, \ldots, a_n) be the sorted in the non-decreasing order array of n - 1 smallest numbers of the form a_i + a_j, where 1 \le i < j \le n. In other words, F(a_1, a_2, \ldots, a_n) is the sorted in the non-decreasing order array of n - 1 smallest sums of all possible pairs of elements of the array a_1, a_2, \ldots, a_n. For example, F(1, 2, 5, 7) = [1 + 2, 1 + 5, 2 + 5] = [3, 6, 7].You are given an array of non-negative integers a_1, a_2, \ldots, a_n. Determine the single element of the array \underbrace{F(F(F\ldots F}_{n-1}(a_1, a_2, \ldots, a_n)\ldots)). Since the answer can be quite large, output it modulo 10^9+7.InputThe first line contains one integer n (2 \le n \le 3000) — the initial length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — the array elements.OutputOutput a single number — the answer modulo 10^9 + 7.ExamplesInput
5
1 2 4 5 6
Output
34
Input
9
1 1 1 7 7 7 9 9 9
Output
256
Input
7
1 7 9 2 0 0 9
Output
20
Input
3
1000000000 1000000000 777
Output
1540
NoteIn the first test, the array is transformed as follows: [1, 2, 4, 5, 6] \to [3, 5, 6, 6] \to [8, 9, 9] \to [17, 17] \to [34]. The only element of the final array is 34.In the second test, F(a_1, a_2, \ldots, a_n) is [2, 2, 2, 8, 8, 8, 8, 8]. This array is made up of 3 numbers of the form 1 + 1 and 5 numbers of the form 1 + 7. In the fourth test, the array is transformed as follows: [10^9, 10^9, 777] \to [10^9+777, 10^9+777] \to [2 \cdot 10^9 + 1554]. 2 \cdot 10^9 + 1554 modulo 10^9+7 equals 1540. | 5
1 2 4 5 6
| 34 | 3 seconds | 256 megabytes | ['binary search', 'brute force', 'implementation', 'math', 'sortings', '*2600'] |
E. There Should Be a Lot of Maximumstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree (a connected graph without cycles). Each vertex of the tree contains an integer. Let's define the \mathrm{MAD} (maximum double) parameter of the tree as the maximum integer that occurs in the vertices of the tree at least 2 times. If no number occurs in the tree more than once, then we assume \mathrm{MAD}=0.Note that if you remove an edge from the tree, it splits into two trees. Let's compute the \mathrm{MAD} parameters of the two trees and take the maximum of the two values. Let the result be the value of the deleted edge.For each edge, find its value. Note that we don't actually delete any edges from the tree, the values are to be found independently.InputThe first line contains one integer n (2 \le n \le 10^5) — the number of vertices in the tree.Each of the next n - 1 lines contains two integers u and v (1 \le u, v \le n) — the ends of an edge of the tree. It's guaranteed that the given edges form a valid tree.The last line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the numbers in the vertices.OutputFor each edge in the input order, print one number — the maximum of the \mathrm{MAD} parameters of the two trees obtained after removing the given edge from the initial tree.ExamplesInput
5
1 2
2 3
2 4
1 5
2 1 3 2 1
Output
0
2
1
2
Input
6
1 2
1 3
1 4
4 5
4 6
1 2 3 1 4 5
Output
1
1
0
1
1
Note In the first example, after removing edge (1, 2) no number repeats 2 times in any of the resulting subtrees, so the answer is \max(0, 0)=0.After removing edge (2, 3), in the bigger subtree, 1 is repeated twice, and 2 is repeated twice, so the \mathrm{MAD} of this tree is 2.After removing edge (2, 4), in the bigger subtree, only the number 1 is repeated, and in the second subtree, only one number appears, so the answer is 1.In the second example, if edge 1 \leftrightarrow 4 is not removed, then one of the subtrees will have two 1, so the answer — 1. And if edge 1 \leftrightarrow 4 is deleted, both subtrees have no repeating values, so the answer is 0. | 5
1 2
2 3
2 4
1 5
2 1 3 2 1
| 0 2 1 2 | 1 second | 256 megabytes | ['brute force', 'data structures', 'dfs and similar', 'dp', 'trees', 'two pointers', '*2300'] |
D. A Wide, Wide Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree (a connected graph without cycles) with n vertices. Consider a fixed integer k. Then, the graph G_k is an undirected graph with n vertices, where an edge between vertices u and v exists if and only if the distance between vertices u and v in the given tree is at least k.For each k from 1 to n, print the number of connected components in the graph G_k.InputThe first line contains the integer n (2 \le n \le 10^5) — the number of vertices in the graph.Each of the next n-1 lines contains two integers u and v (1 \le u, v \le n), denoting an edge between vertices u and v in the tree. It is guaranteed that these edges form a valid tree.OutputOutput n integers: the number of connected components in the graph G_k for each k from 1 to n.ExamplesInput
6
1 2
1 3
2 4
2 5
3 6
Output
1 1 2 4 6 6
Input
5
1 2
2 3
3 4
3 5
Output
1 1 3 5 5
NoteIn the first example: If k=1, the graph has an edge between each pair of vertices, so it has one component. If k=4, the graph has only edges 4 \leftrightarrow 6 and 5 \leftrightarrow 6, so the graph has 4 components.In the second example: when k=1 or k=2 the graph has one component. When k=3 the graph G_k splits into 3 components: one component has vertices 1, 4 and 5, and two more components contain one vertex each. When k=4 or k=5 each vertex is a separate component. | 6
1 2
1 3
2 4
2 5
3 6
| 1 1 2 4 6 6 | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'graphs', 'greedy', 'trees', '*1800'] |
C. Place for a Selfietime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe universe is a coordinate plane. There are n space highways, each of which is a straight line y=kx passing through the origin (0, 0). Also, there are m asteroid belts on the plane, which we represent as open upwards parabolas, i. e. graphs of functions y=ax^2+bx+c, where a > 0.You want to photograph each parabola. To do this, for each parabola you need to choose a line that does not intersect this parabola and does not touch it. You can select the same line for different parabolas. Please find such a line for each parabola, or determine that there is no such line.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains 2 integers n and m (1 \le n, m \le 10^5) —the number of lines and parabolas, respectively.Each of the next n lines contains one integer k (|k| \le 10^8), denoting a line that is described with the equation y=kx. The lines are not necessarily distinct, k can be equal to 0.Each of the next m lines contains 3 integers a, b, and c (a, |b|, |c| \le 10^8, a > 0) — coefficients of equations of the parabolas ax^2+bx+c. The parabolas are not necessarily distinct.It is guaranteed that the sum n over all test cases does not exceed 10^5, and the sum m over all test cases also does not exceed 10^5.OutputFor each test case, output the answers for each parabola in the given order. If there is a line that does not intersect the given parabola and doesn't touch it, print on a separate line the word "YES", and then on a separate line the number k — the coefficient of this line. If there are several answers, print any of them. If the line does not exist, print one word "NO".You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.The empty lines in the output in the example are given only for illustration, you do not need to output them (but you can).ExampleInput
51 211 -1 21 -1 32 2141 2 12 5 11 101 0 01 1100000000100000000 100000000 1000000002 3022 2 11 -2 11 -2 -1Output
YES
1
YES
1
YES
1
YES
4
NO
YES
100000000
YES
0
NO
NO
NoteIn the first test case, both parabolas do not intersect the only given line y=1\cdot x, so the answer is two numbers 1. In the second test case, the line y=x and the parabola 2x^2+5x+1 intersect, and also the line y=4x and the parabola x^2+2x+1 touch, so these pairs do not satisfy the condition. So for the first parabola, the answer is 1 (y=1x), and for the second parabola — 4. In the third test set, the line and the parabola intersect, so the answer is "NO". | 51 211 -1 21 -1 32 2141 2 12 5 11 101 0 01 1100000000100000000 100000000 1000000002 3022 2 11 -2 11 -2 -1 | YES 1 YES 1 YES 1 YES 4 NO YES 100000000 YES 0 NO NO | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'geometry', 'math', '*1400'] |
B. The String Has a Targettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s. You can apply this operation to the string exactly once: choose index i and move character s_i to the beginning of the string (removing it at the old position). For example, if you apply the operation with index i=4 to the string "abaacd" with numbering from 1, you get the string "aabacd". What is the lexicographically minimal^{\dagger} string you can obtain by this operation?^{\dagger}A string a is lexicographically smaller than a string b of the same length if and only if the following holds: in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10 ^ 5) — the length of the string.The second line of each test case contains the string s of length n, consisting of lowercase English letters.It is guaranteed that the sum of n over all test cases does not exceed 10 ^ 5.OutputFor each test case, on a separate line print the lexicographically smallest string that can be obtained after applying the operation to the original string exactly once.ExampleInput
43cba4acac5abbcb4aabaOutput
acb
aacc
abbcb
aaab
NoteIn the first test case, you need to move the last character to the beginning.In the second case, you need to move the second letter "a".In the third set you need to apply the operation with i=1, then the string will not change. | 43cba4acac5abbcb4aaba | acb aacc abbcb aaab | 1 second | 256 megabytes | ['greedy', 'strings', '*800'] |
A. We Need the Zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an array a consisting of non-negative integers. You can choose an integer x and denote b_i=a_i \oplus x for all 1 \le i \le n, where \oplus denotes the bitwise XOR operation. Is it possible to choose such a number x that the value of the expression b_1 \oplus b_2 \oplus \ldots \oplus b_n equals 0?It can be shown that if a valid number x exists, then there also exists x such that (0 \le x < 2^8).InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). The description of the test cases follows.The first line of the test case contains one integer n (1 \le n \le 10^3) — the length of the array a.The second line of the test case contains n integers — array a (0 \le a_i < 2^8).It is guaranteed that the sum of n over all test cases does not exceed 10^3.OutputFor each set test case, print the integer x (0 \le x < 2^8) if it exists, or -1 otherwise.ExampleInput
531 2 531 2 340 1 2 341 2 2 311Output
6
0
3
-1
1
NoteIn the first test case, after applying the operation with the number 6 the array b becomes [7, 4, 3], 7 \oplus 4 \oplus 3 = 0.There are other answers in the third test case, such as the number 0. | 531 2 531 2 340 1 2 341 2 2 311 | 6 0 3 -1 1 | 1 second | 256 megabytes | ['bitmasks', 'brute force', '*800'] |
H. Code Locktime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLara has a safe that is locked with a circle-shaped code lock that consists of a rotating arrow, a static circumference around the arrow, an input screen, and an input button.The circumference of the lock is split into k equal sections numbered from 1 to k in clockwise order. Arrow always points to one of the sections. Each section is marked with one of the first k letters of the English alphabet. No two sections are marked with the same letter.Due to the lock limitations, the safe's password is a string of length n that consists of first k letters of the English alphabet only. Lara enters the password by rotating the lock's arrow and pressing the input button. Initially, the lock's arrow points to section 1 and the input screen is empty. In one second she can do one of the following actions. Rotate the arrow one section clockwise. If the arrow was pointing at section x < k it will now point at section x + 1. If the arrow was pointing at section k it will now point at section 1. Rotate the arrow one section counter-clockwise. If the arrow was pointing at section x > 1 it will now point at section x - 1. If the arrow was pointing at section 1 it will now point at section k. Press the input button. The letter marked on the section that the arrow points to will be added to the content of the input screen. As soon as the content of the input screen matches the password, the safe will open. Lara always enters her password in the minimum possible time.Lara has recently found out that the safe can be re-programmed. She can take the first k letters of the English alphabet and assign them to the sectors in any order she likes. Now she wants to re-arrange the letters in a way that will minimize the number of seconds it takes her to input the password. Compute this minimum number of seconds and the number of ways to assign letters, for which this minimum number of seconds is achieved.Two ways to assign letters to sectors are considered to be distinct if there exists at least one sector i that is assigned different letters.InputThe first line of the input contains two integers k and n (2 \leq k \leq 16, 2 \leq n \leq 100\,000) — the number of sectors on the lock's circumference and the length of Lara's password, respectively.The second line of the input contains a string of length n that consists of the first k lowercase letters of the English alphabet only. This string is the password.OutputOn the first line print minimum possible number of seconds it can take Lara to enter the password and open the safe if she assigns letters to sectors optimally.On the second line print the number of ways to assign letters optimally.ExamplesInput
3 10
abcabcabca
Output
19
2
Input
4 20
bcbcbcbcadadadadcbda
Output
40
2
Input
4 6
adcbda
Output
12
4
NoteThe initial states of optimal arrangements for the first example are shown in the figure below. The initial states of optimal arrangements for the second example are shown in the figure below. The initial states of optimal arrangements for the third example are shown in the figure below. | 3 10
abcabcabca
| 19 2 | 7 seconds | 512 megabytes | ['bitmasks', 'dp', '*3300'] |
G. Flow Controltime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRaj has a single physical network line that connects his office to the Internet. This line bandwidth is b bytes per millisecond.There are n users who would like to use this network line to transmit some data. The i-th of them will use the line from millisecond s_i to millisecond f_i inclusive. His initial data rate will be set to d_i. That means he will use data rate equal to d_i for millisecond s_i, and then it will change according to the procedure described below.The flow control will happen as follows. Suppose there are m users trying to transmit some data via the given network line during millisecond x. Denote as t_i the data rate that the i-th of these m users has at the beginning of this millisecond. All t_i are non-negative integer values. If m = 0, i. e. there are no users trying to transmit data during this millisecond, nothing happens. If the sum of all t_i is less than or equal to b, each active user successfully completes his transmission (the i-th active user transmits t_i bytes). After that, the data rate of each active user grows by 1, i. e. each t_i is increased by 1. If the sum of all t_i is greater than b, the congestion occurs and no data transmissions succeed this millisecond at all. If that happens, each t_i decreases twice, i. e. each t_i is replaced with \lfloor \frac{t_i}{2} \rfloor. Raj knows all the values n, b, s_i, f_i, and d_i, he wants to calculate the total number of bytes transmitted by all the users in the aggregate.InputThe first line of the input contains two integers n and b (1 \leq n \leq 2 \cdot 10^5, 1 \leq b \leq 10^9), the number of users who will use the line and the line bandwidth, respectively.Each of the following n lines contains three integers s_i, f_i and d_i (1 \leq s_i \leq f_i \leq 10^9, 1 \leq d_i \leq 10^9), denoting that the i-th user will try to transmit data during each millisecond between s_i and f_i inclusive, and the initial data rate of the i-th user.OutputPrint one integer — the total number of bytes all users will successfully transmit.ExamplesInput
1 3
1 5 2
Output
10
Input
1 10
7 11 1000
Output
0
Input
2 6
1 12 1
8 20 3
Output
64
Input
3 10
1 100 1
30 60 20
40 80 6
Output
534
NoteConsider the first example. Millisecond 1: User 1 transmits 2 bytes. Millisecond 2: User 1 transmits 3 bytes. Millisecond 3: Congestion occurs, and no user transmits data. Millisecond 4: User 1 transmits 2 bytes. Millisecond 5: User 1 transmits 3 bytes. In the second example, at each millisecond from the 7-th to the 11-th inclusive, congestion occurs, and the only user decreases their rate twice. However, they don't decrease the speed enough before disconnecting.Consider the third example. Millisecond 1: User 1 transmits 1 bytes. Millisecond 2: User 1 transmits 2 bytes. Millisecond 3: User 1 transmits 3 bytes. Millisecond 4: User 1 transmits 4 bytes. Millisecond 5: User 1 transmits 5 bytes. Millisecond 6: User 1 transmits 6 bytes. Millisecond 7: Congestion occurs, and no user transmits data. Millisecond 8: User 1 transmits 3 bytes. User 2 transmits 3 bytes. Millisecond 9: Congestion occurs, and no user transmits data. Millisecond 10: User 1 transmits 2 bytes. User 2 transmits 2 bytes. Millisecond 11: User 1 transmits 3 bytes. User 2 transmits 3 bytes. Millisecond 12: Congestion occurs, and no user transmits data. Millisecond 13: User 2 transmits 2 bytes. Millisecond 14: User 2 transmits 3 bytes. Millisecond 15: User 2 transmits 4 bytes. Millisecond 16: User 2 transmits 5 bytes. Millisecond 17: User 2 transmits 6 bytes. Millisecond 18: Congestion occurs, and no user transmits data. Millisecond 19: User 2 transmits 3 bytes. Millisecond 20: User 2 transmits 4 bytes. | 1 3
1 5 2
| 10 | 6 seconds | 512 megabytes | ['data structures', 'dsu', 'implementation', '*3500'] |
F. Approximate Diametertime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputJack has a graph of n vertices and m edges. All edges are bidirectional and of unit length. The graph is connected, i. e. there exists a path between any two of its vertices. There can be more than one edge connecting the same pair of vertices. The graph can contain self-loops, i. e. edges connecting a node to itself.The distance between vertices u and v is denoted as \rho(u, v) and equals the minimum possible number of edges on a path between u and v. The diameter of graph G is defined as the maximum possible distance between some pair of its vertices. We denote it as d(G). In other words, d(G) = \max_{1 \le u, v \le n}{\rho(u, v)}.Jack plans to consecutively apply q updates to his graph. Each update adds exactly one edge to the graph. Denote as G_i the graph after exactly i updates are made. Jack wants to calculate q + 1 values d(G_0), d(G_1), d(G_2), \ldots, d(G_q).However, Jack suspects that finding the exact diameters of q + 1 graphs might be a difficult task, so he is fine with approximate answers that differ from the correct answers no more than twice. Formally, Jack wants to find a sequence of positive integers a_0, a_1, a_2, \ldots, a_q such that \left\lceil \frac{d(G_i)}{2} \right\rceil \le a_i \le 2 \cdot d(G_i) for each i.HacksYou cannot make hacks in this problem.InputThe first line of the input contains three integers n, m, and q (2 \leq n \leq 10^5, n - 1 \leq m \leq 10^5, 0 \leq q \leq 10^5), the number of vertices in the given graph, the number of edges and the number of updates, respectively.Then follow m lines describing the initial edges of the graph. The i-th of these lines contains two integers u_i and v_i (1 \leq u_i, v_i \leq n), the indexes of the vertices connected by the i-th edge.Then follow q lines describing the updates. The i-th of these lines contains two integers u'_i and v'_i (1 \leq u'_i, v'_i \leq n), the indexes of the vertices connected by the edge that is added to the graph in the i-th update.Important note. For testing purposes, the input data may contain some extra lines after the mentioned input format. These will be used by the checker to verify your answer. They are not a part of the test data, you should not use them in any way and you can even omit reading them. OutputPrint a sequence of q + 1 positive integers a_0, a_1, a_2, \ldots, a_q. The i-th of these integers should differ from the diameter of graph G_i no more than twice.ExamplesInput
9 10 8
1 2
2 3
2 4
3 5
4 5
5 6
5 7
6 8
7 8
8 9
3 4
6 7
2 8
1 9
1 6
4 9
3 9
7 1
Output
10 6 5 6 2 4 2 2 1
Input
8 7 9
1 2
2 3
3 4
4 5
5 6
6 7
7 8
1 5
3 7
2 4
4 6
6 8
8 2
5 4
2 4
3 3
1 652997 124613 653029 653029 124613 124613 124613 648901 124613 653029
Output
7 5 4 4 4 3 3 3 3 3NoteIn the first example, the correct sequence of d(G_0), d(G_1), d(G_2), \ldots, d(G_q) is 6, 6, 6, 3, 3, 3, 2, 2, 2. In the second example, the input contains an extra line that you can omit reading. It is not a part of the test and will be used for verifying your answer. The output of the second example contains the correct values of d(G_i). | 9 10 8
1 2
2 3
2 4
3 5
4 5
5 6
5 7
6 8
7 8
8 9
3 4
6 7
2 8
1 9
1 6
4 9
3 9
7 1
| 10 6 5 6 2 4 2 2 1 | 2 seconds | 512 megabytes | ['binary search', 'divide and conquer', 'graphs', 'shortest paths', '*2700'] |
E. Routingtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAda operates a network that consists of n servers and m direct connections between them. Each direct connection between a pair of distinct servers allows bidirectional transmission of information between these two servers. Ada knows that these m direct connections allow to directly or indirectly transmit information between any two servers in this network. We say that server v is a neighbor of server u if there exists a direct connection between these two servers.Ada needs to configure her network's WRP (Weird Routing Protocol). For each server u she needs to select exactly one of its neighbors as an auxiliary server a(u). After all a(u) are set, routing works as follows. Suppose server u wants to find a path to server v (different from u). Server u checks all of its direct connections to other servers. If it sees a direct connection with server v, it knows the path and the process terminates. If the path was not found at the first step, server u asks its auxiliary server a(u) to find the path. Auxiliary server a(u) follows this process starting from the first step. After a(u) finds the path, it returns it to u. Then server u constructs the resulting path as the direct connection between u and a(u) plus the path from a(u) to v. As you can see, this procedure either produces a correct path and finishes or keeps running forever. Thus, it is critically important for Ada to configure her network's WRP properly.Your goal is to assign an auxiliary server a(u) for each server u in the given network. Your assignment should make it possible to construct a path from any server u to any other server v using the aforementioned procedure. Or you should report that such an assignment doesn't exist.InputThe first line of the input contains two integers n and m (2 \leq n \leq 20, n - 1 \leq m \leq \frac{n \cdot (n - 1)}{2}) — the number of servers and the number of direct connections in the given network.Then follow m lines containing two integers u_i and v_i (1 \leq u_i, v_i \leq n, u_i \ne v_i) each, the i-th line describes the i-th direct connection.It is guaranteed that there is no more than one direct connection between any two servers. It is guaranteed that there is a direct or indirect route (consisting only of the given direct connections) between any two servers.OutputIf there is no way to assign an auxiliary server a(u) for each server u in such a way that WRP will be able to find a path from any server u to any other server v, print "No" in the only line of the output.Otherwise, print "Yes" in the first line of the output. In the second line of the output print n integers, the i-th of these integers should be equal to a(i) – the index of the auxiliary server for server i. Do not forget that there must be a direct connection between server i and server a(i).You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExamplesInput
6 7
1 2
2 3
3 1
4 5
5 6
4 6
2 5
Output
Yes
2 5 2 5 2 5
Input
3 2
1 2
2 3
Output
Yes
2 1 2
Input
4 4
1 3
2 3
4 1
4 2
Output
Yes
3 3 1 1
Input
6 5
1 2
2 3
3 4
4 5
5 6
Output
No
| 6 7
1 2
2 3
3 1
4 5
5 6
4 6
2 5
| Yes 2 5 2 5 2 5 | 2 seconds | 512 megabytes | ['bitmasks', 'brute force', 'dfs and similar', 'dp', 'graphs', '*2400'] |
D. Accommodationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAnnie is an amateur photographer. She likes to take pictures of giant residential buildings at night. She just took a picture of a huge rectangular building that can be seen as a table of n \times m windows. That means that the building has n floors and each floor has exactly m windows. Each window is either dark or bright, meaning there is light turned on in the room behind it.Annies knows that each apartment in this building is either one-bedroom or two-bedroom. Each one-bedroom apartment has exactly one window representing it on the picture, and each two-bedroom apartment has exactly two consecutive windows on the same floor. Moreover, the value of m is guaranteed to be divisible by 4 and it is known that each floor has exactly \frac{m}{4} two-bedroom apartments and exactly \frac{m}{2} one-bedroom apartments. The actual layout of apartments is unknown and can be different for each floor.Annie considers an apartment to be occupied if at least one of its windows is bright. She now wonders, what are the minimum and maximum possible number of occupied apartments if judged by the given picture?Formally, for each of the floors, she comes up with some particular apartments layout with exactly \frac{m}{4} two-bedroom apartments (two consecutive windows) and \frac{m}{2} one-bedroom apartments (single window). She then counts the total number of apartments that have at least one bright window. What is the minimum and maximum possible number she can get?InputThe first line of the input contains two positive integers n and m (1 \leq n \cdot m \leq 5 \cdot 10^5) — the number of floors in the building and the number of windows per floor, respectively. It is guaranteed that m is divisible by 4.Then follow n lines containing m characters each. The j-th character of the i-th line is "0" if the j-th window on the i-th floor is dark, and is "1" if this window is bright.OutputPrint two integers, the minimum possible number of occupied apartments and the maximum possible number of occupied apartments, assuming each floor can have an individual layout of \frac{m}{4} two-bedroom and \frac{m}{2} one-bedroom apartments.ExamplesInput
5 4
0100
1100
0110
1010
1011
Output
7 10
Input
1 8
01011100
Output
3 4
NoteIn the first example, each floor consists of one two-bedroom apartment and two one-bedroom apartments.The following apartment layout achieves the minimum possible number of occupied apartments equal to 7. |0 1|0|0||1 1|0|0||0|1 1|0||1|0 1|0||1|0|1 1|The following apartment layout achieves the maximum possible number of occupied apartments equal to 10. |0 1|0|0||1|1 0|0||0 1|1|0||1|0 1|0||1 0|1|1| | 5 4
0100
1100
0110
1010
1011
| 7 10 | 2 seconds | 512 megabytes | ['brute force', 'dp', 'greedy', 'implementation', '*2000'] |
C. Pull Your Lucktime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputWhile James is gone on business, Vesper takes her time and explores what the legendary Casino Royale has to offer to people who are fond of competitive programming.Her attention was grabbed by the very new "Pull Your Luck" roulette which functions in a pretty peculiar way. The roulette's wheel consists of n sectors number from 0 to n - 1. There is no ball and the winning sector is determined by a static arrow pointing to one of the sectors. Sectors' indexes go in the natural order and the wheel always spins in the direction of indexes increment. That means that sector i + 1 goes right after sector i for all i from 0 to n - 2, and sector 0 goes right after sector n - 1.After a bet is made, the player is allowed to pull the triggering handle herself and cause the wheel to spin. If the player's initial pull is made with the force equal to positive integer f, the wheel will spin for f seconds. During the first second it will advance f sectors, the next second it will advance f - 1 sectors, then f - 2 sectors, and so on until it comes to a complete stop. After the wheel comes to a complete stop, the sector which the arrow is pointing to is the winning one.The roulette's arrow currently points at sector x. Vesper knows that she can pull the handle with any integer force from 1 to p inclusive. Note that it is not allowed to pull the handle with force 0, i. e. not pull it all. The biggest prize is awarded if the winning sector is 0. Now Vesper wonders if she can make sector 0 win by pulling the triggering handle exactly once?InputThe first line of the input contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. Then follow t lines containing one test description each.Each test description consists of three integers n, x and p (3 \leq n \leq 10^5, 0 \leq x < n, 1 \leq p \leq 10^9). They are the number of sectors on the wheel, the current sector the arrow points at, and the maximum force that Vesper can pull the handle with, respectively.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputPrint t lines, the i-th line should contain the answer for the i-th test case. If it is possible to pull the handle with the integer force from 1 to p in order to make sector 0 win, print "Yes". Otherwise, print "No".You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput
75 2 15 2 210 0 10011 7 1003 1 100031 0 10100 49 7Output
No
Yes
Yes
Yes
No
No
No
NoteIn the first example, the only possible way to pull the handle is with force 1. That is not enough to make the arrow point at sector 0, at least force 2 is required to do so.In the second example, Vesper can pull the handle with the force 2 so the wheel will spin 2 + 1 = 3 sectors ahead and the arrow will point at sector 0.In the third example, Vesper can pull the handle with the force 4 so the wheel will spin 4 + 3 + 2 + 1 = 10 sectors and will point at sector 0 again.In the fourth example, Vesper can pull the handle with the force 5 so the wheel will spin 5 + 4 + 3 + 2 + 1 = 15 sectors. That will make the wheel make one full turn plus 4 more sectors.In the fifth example, whatever force Vesper chooses to pull the handle with, she can only make sectors 1 and 2 win. | 75 2 15 2 210 0 10011 7 1003 1 100031 0 10100 49 7 | No Yes Yes Yes No No No | 1 second | 512 megabytes | ['brute force', 'greedy', 'math', 'number theory', '*1500'] |
B. Vaccinationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputEthan runs a vaccination station to help people combat the seasonal flu. He analyses the historical data in order to develop an optimal strategy for vaccine usage.Consider there are n patients coming to the station on a particular day. The i-th patient comes at the moment t_i. We know that each of these patients can be asked to wait for no more than w time moments. That means the i-th patient can get vaccine at moments t_i, t_i + 1, \ldots, t_i + w.Vaccines come in packs, each pack consists of k doses. Each patient needs exactly one dose. Packs are stored in a special fridge. After a pack is taken out of the fridge and opened, it can no longer be put back. The lifetime of the vaccine outside the fridge is d moments of time. Thus, if the pack was taken out of the fridge and opened at moment x, its doses can be used to vaccinate patients at moments x, x + 1, \ldots, x + d. At moment x + d + 1 all the remaining unused doses of this pack are thrown away.Assume that the vaccination station has enough staff to conduct an arbitrary number of operations at every moment of time. What is the minimum number of vaccine packs required to vaccinate all n patients?InputThe first line of the input contains the number of test cases t (1 \leq t \leq 10^4). Then follow t descriptions of the test cases.The first line of each test case contains four integers n, k, d and w (1 \leq n, k \leq 2 \cdot 10^5, 0 \leq d, w \leq 10^6). They are the number of patients, the number of doses per vaccine pack, the number of moments of time the vaccine can live outside the fridge, and the number of moments of time each of the patients can wait, respectively.The second line of each test case contains a non-decreasing sequence t_1, t_2, \ldots, t_n (0 \leq t_1 \leq t_2 \leq \ldots \leq t_n \leq 10^6). The i-th element of this sequence is the moment when the i-th patient comes to the vaccination station.It is guaranteed that the sum of n over all test cases won't exceed 2 \cdot 10^5.OutputOutput one integer, the minimum number of vaccine packs required to vaccinate all n patients.ExampleInput
56 3 5 31 2 3 10 11 186 4 0 03 3 3 3 3 49 10 2 20 1 2 3 4 5 6 7 83 10 3 610 20 305 5 4 40 2 4 6 8Output
2
3
2
3
1
NoteIn the first example, the first pack can be opened at moment 1 to vaccinate patient 1. The vaccine is durable enough to be used at moments 2 and 3 for patients 2 and 3, respectively. Then the staff needs to ask patients 4 and 5 to wait for moment 13. At moment 13 the staff opens the second vaccine pack and serves patients 4 and 5. Finally, the last patient comes at moment 18 and immediately gets the last dose of the second pack while it is still fine.In the second example, the vaccine should be used exactly at the moment it is taken out of the fridge. Moreover, all the patients want to be served at exactly the same moment they come. That means the staff needs to open two packs at moment 3 and use five doses on patients 1, 2, 3, 4, and 5. There will be three doses left ouf of these two packs but they can't be used for patient 6. When patient 6 comes at moment 4 the staff needs to open a new pack just to use only one dose out of it. | 56 3 5 31 2 3 10 11 186 4 0 03 3 3 3 3 49 10 2 20 1 2 3 4 5 6 7 83 10 3 610 20 305 5 4 40 2 4 6 8 | 2 3 2 3 1 | 2 seconds | 512 megabytes | ['greedy', 'implementation', '*1000'] |
A. Lame Kingtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a checkerboard of size 201 \times 201, i. e. it has 201 rows and 201 columns. The rows of this checkerboard are numbered from -100 to 100 from bottom to top. The columns of this checkerboard are numbered from -100 to 100 from left to right. The notation (r, c) denotes the cell located in the r-th row and the c-th column.There is a king piece at position (0, 0) and it wants to get to position (a, b) as soon as possible. In this problem our king is lame. Each second, the king makes exactly one of the following five moves. Skip move. King's position remains unchanged. Go up. If the current position of the king is (r, c) he goes to position (r + 1, c). Go down. Position changes from (r, c) to (r - 1, c). Go right. Position changes from (r, c) to (r, c + 1). Go left. Position changes from (r, c) to (r, c - 1). King is not allowed to make moves that put him outside of the board. The important consequence of the king being lame is that he is not allowed to make the same move during two consecutive seconds. For example, if the king goes right, the next second he can only skip, go up, down, or left.What is the minimum number of seconds the lame king needs to reach position (a, b)?InputThe first line of the input contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. Then follow t lines containing one test case description each.Each test case consists of two integers a and b (-100 \leq a, b \leq 100) — the position of the cell that the king wants to reach. It is guaranteed that either a \ne 0 or b \ne 0.OutputPrint t integers. The i-th of these integers should be equal to the minimum number of seconds the lame king needs to get to the position he wants to reach in the i-th test case. The king always starts at position (0, 0).ExampleInput
5-4 14 40 -6-5 -47 -8Output
7
8
11
9
15
NoteOne of the possible solutions for the first example is: go down, go right, go down, go right, go down, go left, go down.One of the possible solutions for the second example is to alternate "go right" and "go up" moves 4 times each.One of the possible solutions for the third example is to alternate "go left" and "skip" moves starting with "go left". Thus, "go left" will be used 6 times, and "skip" will be used 5 times. | 5-4 14 40 -6-5 -47 -8 | 7 8 11 9 15 | 1 second | 512 megabytes | ['greedy', 'math', '*800'] |
B. Settlement of Guinea Pigstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDasha loves guinea pigs very much. In this regard, she decided to settle as many guinea pigs at home as possible and developed a plan for the next n days. Every day, she will either buy a new guinea pig or call a doctor to examine all her pets.Unfortunately, the store where she was going to buy guinea pigs does not understand them. Therefore, it cannot determine their gender. Dasha can't do it either. The only one who can help is a doctor. To keep guinea pigs, aviaries are needed. Dasha plans to buy them in the same store. Unfortunately, only one species is sold there — a double aviary. No more than two guinea pigs can live in it.Since Dasha does not want to cause moral injury to her pets — she will not settle two guinea pigs of different genders in one aviary.Help Dasha calculate how many aviaries in the worst case you need to buy so that you can be sure that at no moment of time do two guinea pigs of different genders live in the same aviary.As part of this task, we believe that guinea pigs have only two genders — male and female.InputThe first line of input data contains one number t (1 \leqslant t \leqslant 10^5) — the number of input data sets.The first line of each input data set contains one number n (1 \leqslant n \leqslant 10^5) — the number of days Dasha has a plan for.The next line contains n numbers b_1, b_2, b_3, \ldots, b_n (1 \leqslant b_i \leqslant 2) — Dasha's plan. If b_i = 1, then on the ith day, Dasha will buy a new guinea pig. If b_i = 2, then on the ith day, a doctor will come to Dasha and help determine the sex of all guinea pigs that Dasha already has.It is guaranteed that the sum of n for all input data sets does not exceed 10^5.OutputFor each set of input data, output one number — the minimum number of aviaries Dasha needs to buy so that no matter what the genders of the pigs turn out to be, we can settle them so that at no point in time do two guinea pigs of different genders live together.ExampleInput
631 1 132 2 251 1 1 2 1101 2 1 2 1 2 1 2 1 2201 2 1 1 1 1 1 2 1 2 1 2 2 1 1 1 1 1 1 1202 1 1 2 1 1 2 1 2 2 1 1 1 2 2 1 1 1 1 2Output
3
0
3
4
12
9
NoteIn the first set of input data, Dasha needs to put each guinea pig in a separate enclosure, since she does not know their gender.In the second set of input data, Dasha will buy 0 guinea pigs, which means she will need 0 aviaries.In the third set of input data, you even need 3 aviaries to put each guinea pig in a separate aviary before the doctor arrives at the 4th day. When she finds out their gender, at least two guinea pigs will be of the same gender and they can be placed in one aviary, and the third in another aviary. Thus, she will have one free aviary in which she can settle a new guinea pig. So answer is 3.In the fourth set of input data, we show that 4 is the optimal answer. To begin with, we note that the first four guinea pigs can be placed one at a time in an aviary. Then a doctor will come and determine their gender. Among these four guinea pigs there will be at least one pair of the same gender, because: either male guinea pigs are at least 2, or they are not more than 1, which means that the female is at least 3. Now we can put this couple in one aviary, and the other two in separate ones. We will have one more empty aviary where we can put a new pig.Now let's show that the answer is at least 4. Let's say that among the first 4 guinea pigs, 3 are female and 1 is male. We need at least 3 aviaries to settle them. Then, when we buy a new guinea pig, we will need another aviary in which we will put it, since we do not know its gender. | 631 1 132 2 251 1 1 2 1101 2 1 2 1 2 1 2 1 2201 2 1 1 1 1 1 2 1 2 1 2 2 1 1 1 1 1 1 1202 1 1 2 1 1 2 1 2 2 1 1 1 2 2 1 1 1 1 2 | 3 0 3 4 12 9 | 1 second | 256 megabytes | ['greedy', 'implementation', 'math', '*1000'] |
A. Likestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikita recently held a very controversial round, after which his contribution changed very quickly.The announcement hung on the main page for n seconds. In the ith second |a_i|th person either liked or removed the like (Nikita was lucky in this task and there are no dislikes). If a_i > 0, then the a_ith person put a like. If a_i < 0, then the person -a_i removed the like. Each person put and removed the like no more than once. A person could not remove a like if he had not put it before.Since Nikita's contribution became very bad after the round, he wanted to analyze how his contribution changed while the announcement was on the main page. He turned to the creator of the platform with a request to give him the sequence a_1, a_2, \ldots, a_n. But due to the imperfection of the platform, the sequence a was shuffled.You are given a shuffled sequence of a that describes user activity. You need to tell for each moment from 1 to n what the maximum and minimum number of likes could be on the post at that moment.InputThe first line of input data contains one number t (1 \leqslant t \leqslant 1000) — the number of test cases.In the first line of test case, one number is given n (1 \leqslant n \leqslant 100) — the number of seconds during which Nikita's announcement hung on the main page.The next line contains n numbers b_1, b_2, b_3, \ldots, b_n (1 \leqslant |b_i| \leqslant n) — mixed array a. It is guaranteed that there exists such a permutation of b that it is a correct sequence of events described in the condition.It is guaranteed that the sum of n for all input test cases does not exceed 10^4.OutputFor each test case, output two lines, each of which contains n numbers.In the first line, for each test case, output the maximum number of likes that Nikita could have at the announcement at the ith second.In the second line, for each test case, output the minimum number of likes that Nikita could have at the announcement at the ith second.ExampleInput
531 2 -221 -164 3 -1 2 1 -254 2 -2 1 37-1 6 -4 3 2 4 1Output
1 2 1
1 0 1
1 0
1 0
1 2 3 4 3 2
1 0 1 0 1 2
1 2 3 4 3
1 0 1 2 3
1 2 3 4 5 4 3
1 0 1 0 1 2 3
NoteIn the first test case, the maximum values are reached with the following permutation: 1, 2, -2. And the minimum values for such: 2, -2, 1.In the third test case, all maximal values are reached with the following permutation: 4, 2, 3, 1, -1, -2. And the minimum values for the next permutation: 2, -2, 1, -1, 3, 4. | 531 2 -221 -164 3 -1 2 1 -254 2 -2 1 37-1 6 -4 3 2 4 1 | 1 2 1 1 0 1 1 0 1 0 1 2 3 4 3 2 1 0 1 0 1 2 1 2 3 4 3 1 0 1 2 3 1 2 3 4 5 4 3 1 0 1 0 1 2 3 | 1 second | 256 megabytes | ['greedy', 'implementation', '*800'] |
G. A task for substringstime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard output Philip is very fond of tasks on the lines. He had already solved all the problems known to him, but this was not enough for him. Therefore, Philip decided to come up with his own task.To do this, he took the string t and a set of n strings s_1, s_2, s_3, ..., s_n. Philip has m queries, in the ith of them, Philip wants to take a substring of the string t from l_ith to r_ith character, and count the number of its substrings that match some string from the set. More formally, Philip wants to count the number of pairs of positions a, b, such that l_i \le a \le b \le r_i, and the substring of the string t from ath to bth character coincides with some string s_j from the set.A substring of the string t from ath to bth character is a string obtained from t by removing the a - 1 character from the beginning and |t| - b characters from the end, where |t| denotes the length of the string t.Philip has already solved this problem, but can you? InputThe first line contains two positive integers n and m (1 \le n, m \le 500\,000) — the number of rows in the set and the number of queries.The second line contains a single string t consisting of lowercase letters of the English alphabet (1 \le |t| \le 5 \cdot 10^6).The following n lines describe the strings from the set. In the ith of them, a single string s_i is given, consisting of lowercase letters of the English alphabet. Denote by S the total length of all strings from the set. It is guaranteed that S \le 10^6, as well as that all strings of s_i are different.In the following lines, queries are entered. The ith of them contains two positive integers l_i and r_i (1 \le l_i \le r_i \le |t|) — the left and right border of the substring t from the i-th query. OutputIn a single line, print m integers, ith of them should be equal to the answers to the ith query. Examples Input
3 5
abacaba
aba
a
ac
1 7
1 3
2 7
2 5
4 5
Output
7 3 5 3 1
Input
4 4
abcdca
ab
ca
bcd
openolympiad
1 5
2 2
2 6
1 6
Output
2 0 2 3
NoteIn the first example, the first query requires the entire string to count the number of substrings that are included in the set. The substrings [1, 3] and [4, 6] coincide with the string "aba". The substrings match with the string "a" [1, 1], [3, 3], [5, 5], [7, 7]. The substring [3, 4] matches the string "ac". In total, it turns out that 7 substrings of the string "abacaba" match the strings from the set.In the second query, a substring from position 1 to position 3 is taken from the source string, this is the string "aba". The string "aba" enters it 1 time, the string "a" enters it 2 times and the string "ac" does not enter it once as a substring. In the third query, a substring from the 2nd to the 7th position is taken from the source string, this is the string "bacaba". The string "aba" is included in it 1 time, the string "a" is included 3 times and the string "ac" is included 1 time as a substring. | 3 5
abacaba
aba
a
ac
1 7
1 3
2 7
2 5
4 5
| 7 3 5 3 1 | 4 seconds | 1024 megabytes | ['data structures', 'string suffix structures', 'strings', '*3400'] |
F. Another n-dimensional chocolate bartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard output Mom bought the boy Vasya a n-dimensional chocolate bar, which is a n-dimensional cube with the length of each side equal to 1. The chocolate is planned to be divided into slices. According to the ith dimension, it can be divided by hyperplanes into a_i equal parts. Thus, the chocolate is divided in total into a_1 \cdot a_2 \cdot a_3 \cdot \ldots \cdot a_n slices, each slice has a length of i-th dimension equal to \frac{1}{a_i}, respectively, the volume of each slice is \frac{1}{a_1 a_2 \cdots a_n}.Vasya and his friends want to cut a chocolate bar to get at least k pieces, while Vasya wants to maximize the volume of the smallest of them. It is possible to cut the chocolate bar only at the junction of the lobules, and each incision must pass through the entire chocolate bar along some hyperplane involved in the formation of lobules. Only after making all the cuts, Vasya disassembles the chocolate into pieces.More formally, Vasya wants to choose the numbers b_1, b_2, \dots, b_n (1 \le b_i \le a_i) — the number of parts into which Vasya will cut the chocolate bar along each dimension. The condition b_1 \cdot b_2 \cdot \ldots \cdot b_n \ge k must be met to get at least k pieces after all cuts. It can be noted that with optimal cutting with such parameters, the minimum piece will contain \lfloor \frac{a_1}{b_1} \rfloor \dotsm \lfloor \frac{a_n}{b_n} \rfloor slices, and its volume will be equal to \lfloor \frac{a_1}{b_1} \rfloor \dotsm \lfloor \frac{a_n}{b_n} \rfloor \cdot \frac{1}{a_1 a_2 \cdots a_n}.Vasya wants to get the maximum possible value of the volume of the minimum piece multiplied by k, that is, he wants to maximize the number of \lfloor \frac{a_1}{b_1} \rfloor \dotsm \lfloor \frac{a_n}{b_n} \rfloor \cdot \frac{1}{a_1 a_2 \cdots a_n} \cdot k. Help him with this. InputThe first line contains two integers n and k (1 \le n \le 100, 1 \le k \le 10^7) — the dimension of the chocolate bar, and how many parts it needs to be divided into.The second line contains n integers a_1,\ a_2,\ \dots,\ a_n (1 \le a_i \le 10^7) — the number of pieces on which the chocolate is placed along each of the dimensions. OutputPrint one number — the maximum possible volume of the smallest of the obtained pieces, multiplied by k, with an absolute or relative error of no more than 10^{-9}.If it is impossible to cut a chocolate bar into at least k pieces under the given restrictions, output 0. Examples Input
1 2
5
Output
0.8
Input
2 6
5 10
Output
0.72
Input
2 7
4 4
Output
0.875
Input
2 3
4 5
Output
0.75
Input
4 444
57 179 239 2
Output
0.97557326850704739751
Input
2 5
2 2
Output
0
NoteIn the first example, a one – dimensional chocolate bar can be divided as follows: Then the answer will be \frac{2}{5} \cdot 2 = 0.8In the second example, the chocolate bar can be cut as follows:Then the answer will be \frac{2}{5} \cdot \frac{3}{10} \cdot 6 = 0.72In the third example, the chocolate bar can be cut as follows: Then the answer will be \frac{2}{4} \cdot \frac{1}{4} \cdot 7 = 0.875 | 1 2
5
| 0.8 | 2 seconds | 512 megabytes | ['dp', 'math', 'meet-in-the-middle', 'number theory', '*2700'] |
E. Gasoline pricestime limit per test3.5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard output Berland — is a huge country consisting of n cities. The road network of Berland can be represented as a root tree, that is, there is only n - 1 road in the country, and you can get from any city to any other exactly one way, if you do not visit any city twice. For the convenience of representing the country, for each city i, the city p_i is fixed, equal to the first city to which you need to go from the city i to get to the city 1. In other words, the city p_i is equal to the ancestor of the city i if the tree is hung for the city 1.There is one gas station in each city of Berland. Gas stations have special pricing, and for each gas station there is a fixed range of prices for which they are ready to sell gasoline. A gas station in the city with the number i is ready to sell gasoline at any price from l_i to r_i inclusive.The King of Berland — is an exemplary family man, and for m years, two sons were born to him every year. The king's children have been involved in public affairs since early childhood, and at the end of each year they check the honesty of gasoline prices. From birth, the king's children, who are born in the year i, are responsible for checking gasoline prices on the ways from the city of a_i to the city of b_i and from the city of c_i to the city of d_i, respectively.The check is as follows: both children simultaneously start their journey from the cities a_i and c_i, respectively. The first son of the king, born in the year i, moves along the path from the city a_i to the city b_i, and the second — from the city c_i to the city d_i. Children check that the price of gasoline in the city of a_i coincides with the price of gasoline in the city of c_i. Next, they check that the price of gasoline in the second city on the way from a_i to b_i coincides with the price in the second city on the way from c_i to d_i. Then they repeat the same thing for a couple of third cities on their paths and so on. At the end, they check that the price of gasoline in the city of b_i coincides with the price of gasoline in the city of d_i. It is guaranteed that the length of the path from the city a_i to the city b_i coincides with the length of the path from the city c_i to the city d_i.Gas stations must strictly obey the laws, and therefore all checks of gasoline prices should not reveal violations. Help Berland gas stations find out how many ways they can set gasoline prices for m years. In other words, for each i from 1 to m, calculate how many ways you can set gasoline prices at all gas stations so that after the birth of the first i pairs of the king's children, all their checks did not reveal violations, and at any gas station the price was in the acceptable price range. Since the number of such methods can be large, calculate the answer modulo 10^9 + 7. InputThe first line contains a single integer n (1 \le n \le 200\,000) — the number of cities in Berland.The second line contains (n - 1) numbers p_2,\ p_3,\ p_4,\ \ldots,\ p_n (1 \le p_i \le n), where p_i denotes the number of the next city on the way from city i to city 1.In each of the following lines, two integers are given l_i and r_i (1 \le l_i \le r_i < 10^9+7), specifying the acceptable range of prices at the gas station number i.The following line contains a single integer m (1 \le m \le 200\,000) — the number of years during which two sons were born to the king.In each of the following m lines, four integers are given a_i, b_i, c_i and d_i (1 \le a_i, b_i, c_i, d_i \le n), specifying two paths on which the king's children will check gasoline prices, born in the year i. It is guaranteed that the length of the path between the cities a_i and b_i is equal to the length of the path between the cities c_i and d_i. OutputIn m lines, print one number each. The number in the i line should be equal to the number of ways to set gasoline prices in all cities so that the king's children born in the years up to and including i do not reveal violations in inspections. Output the numbers modulo 10^9 + 7. Examples Input
5
1 1 2 2
2 4
1 3
1 3
2 4
4 4
4
1 1 2 2
1 2 2 1
3 4 4 3
3 4 3 5
Output
18
18
4
0
Input
8
1 2 3 4 5 8 6
3 7
2 6
3 8
5 10
5 8
2 9
3 8
6 8
4
1 3 7 6
4 1 5 7
1 7 7 1
1 8 2 7
Output
720
120
120
1
NoteConsider the first example.After the birth of the first two sons, the prices in the cities of 1 and 2 should be equal. In total, there are 2 ways to choose the same gasoline price for the cities of 1 and 2 so that it falls within the acceptable price range for these cities. So, there are only ways to set gasoline prices: 2 \cdot 3 \cdot 3 \cdot 1 = 18.The second pair of sons will check the prices on the paths 1 - 2 and 2 - 1. This means that gasoline prices in the cities of 1 and 2 must match, which is already being done. Therefore, after the birth of the second pair of sons, the answer did not change in any way.The third pair of sons will check the prices on the tracks 3 - 1 - 2 - 4 and 4 - 2 - 1 - 3. Then the price of non-gasoline in the city of 3 should be equal to the price in the city of 4, and the price in the city of 1 should be equal to the price in the city of 2. Prices in the cities of 1 and 2 are already the same. For the cities of 3 and 4, there are 2 ways to choose the same price for gasoline so that it falls within the acceptable price range for these cities. So, there are only ways to set gasoline prices: 2 \cdot 2 \cdot 1 = 4. The fourth pair of sons will check the prices on the tracks 3 - 1 - 2 - 4 and 3 - 1 - 2 - 5. This means that the prices in the cities of 4 and 5 should be equal, and since the prices in the cities of 3 and 4 already coincide, then in the cities of 3, 4 and 5 there should be the same price for gasoline. The price of gasoline in the city of 3 should be no more than 3, and the price of gasoline in the city of 5 should be no less than 4. So, after the birth of the fourth pair of sons, there are no ways to set gasoline prices so that all checks are carried out and prices are in the required ranges. | 5
1 1 2 2
2 4
1 3
1 3
2 4
4 4
4
1 1 2 2
1 2 2 1
3 4 4 3
3 4 3 5
| 18 18 4 0 | 3.5 seconds | 1024 megabytes | ['data structures', 'divide and conquer', 'dsu', 'hashing', 'trees', '*3000'] |
D. The way hometime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard output The famous magician Borya Budini traveled through the country X, which consists of n cities. However, an accident happened, and he was robbed in the city number 1. Now Budini will have a hard way home to the city number n.He's going to get there by plane. In total, there are m flights in the country, i-th flies from city a_i to city b_i and costs s_i coins. Note that the i-th flight is one-way, so it can't be used to get from city b_i to city a_i. To use it, Borya must be in the city a_i and have at least s_i coins (which he will spend on the flight). After the robbery, he has only p coins left, but he does not despair! Being in the city i, he can organize performances every day, each performance will bring him w_i coins. Help the magician find out if he will be able to get home, and what is the minimum number of performances he will have to organize. InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 80) – the number of test cases. The description of test cases follows.The first line contains three integers n, m and p (2 \le n \le 800, 1 \le m \le 3000, 0 \le p \le 10^9) — the number of cities, the number of flights and the initial amount of coins.The second line contains n integers w_1, w_2, \ldots, w_n (1 \le w_i \le 10^9) — profit from representations.The following m lines each contain three integers a_i, b_i and s_i (1 \le a_i, b_i \le n, 1 \le s_i \le 10^9) — the starting and ending city, and the cost of i-th flight.It is guaranteed that the sum of n over all test cases does not exceed 800 and the sum of m over all test cases does not exceed 10000. OutputFor each test case print a single integer — the minimum number of performances Borya will have to organize to get home, or -1 if it is impossible to do this. Example Input
44 4 27 4 3 11 2 213 2 61 3 82 4 114 4 101 2 10 11 2 202 4 301 3 253 4 894 4 75 1 6 21 2 52 3 103 4 503 4 704 1 21 1 1 11 3 2Output
4
24
10
-1
NoteIn the first example, it is optimal for Borya to make 4 performances in the first city, having as a result 2 + 7 \cdot 4 = 30 coins, and then walk along the route 1-3-2-4, spending 6+8+11=25 coins. In the second example, it is optimal for Borya to make 15 performances in the first city, fly to 3 city, make 9 performances there, and then go to 4 city. | 44 4 27 4 3 11 2 213 2 61 3 82 4 114 4 101 2 10 11 2 202 4 301 3 253 4 894 4 75 1 6 21 2 52 3 103 4 503 4 704 1 21 1 1 11 3 2 | 4 24 10 -1 | 3 seconds | 512 megabytes | ['binary search', 'data structures', 'dp', 'graphs', 'greedy', 'shortest paths', 'sortings', '*2100'] |