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
|
---|---|---|---|---|---|
C. Yet Another Broken Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Norge found a string s = s_1 s_2 \ldots s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all \frac{n (n + 1)}{2} of them!A substring of s is a non-empty string x = s[a \ldots b] = s_{a} s_{a + 1} \ldots s_{b} (1 \leq a \leq b \leq n). For example, "auto" and "ton" are substrings of "automaton".Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only k Latin letters c_1, c_2, \ldots, c_k out of 26.After that, Norge became interested in how many substrings of the string s he could still type using his broken keyboard. Help him to find this number.InputThe first line contains two space-separated integers n and k (1 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 26) — the length of the string s and the number of Latin letters still available on the keyboard.The second line contains the string s consisting of exactly n lowercase Latin letters.The third line contains k space-separated distinct lowercase Latin letters c_1, c_2, \ldots, c_k — the letters still available on the keyboard.OutputPrint a single number — the number of substrings of s that can be typed using only available letters c_1, c_2, \ldots, c_k.ExamplesInput
7 2
abacaba
a b
Output
12
Input
10 3
sadfaasdda
f a d
Output
21
Input
7 1
aaaaaaa
b
Output
0
NoteIn the first example Norge can print substrings s[1\ldots2], s[2\ldots3], s[1\ldots3], s[1\ldots1], s[2\ldots2], s[3\ldots3], s[5\ldots6], s[6\ldots7], s[5\ldots7], s[5\ldots5], s[6\ldots6], s[7\ldots7]. | 7 2
abacaba
a b
| 12 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'implementation', '*1200'] |
B. Snow Walking Robottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently you have bought a snow walking robot and brought it home. Suppose your home is a cell (0, 0) on an infinite grid.You also have the sequence of instructions of this robot. It is written as the string s consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell (x, y) right now, he can move to one of the adjacent cells (depending on the current instruction). If the current instruction is 'L', then the robot can move to the left to (x - 1, y); if the current instruction is 'R', then the robot can move to the right to (x + 1, y); if the current instruction is 'U', then the robot can move to the top to (x, y + 1); if the current instruction is 'D', then the robot can move to the bottom to (x, y - 1). You've noticed the warning on the last page of the manual: if the robot visits some cell (except (0, 0)) twice then it breaks.So the sequence of instructions is valid if the robot starts in the cell (0, 0), performs the given instructions, visits no cell other than (0, 0) two or more times and ends the path in the cell (0, 0). Also cell (0, 0) should be visited at most two times: at the beginning and at the end (if the path is empty then it is visited only once). For example, the following sequences of instructions are considered valid: "UD", "RL", "UUURULLDDDDLDDRRUU", and the following are considered invalid: "U" (the endpoint is not (0, 0)) and "UUDD" (the cell (0, 1) is visited twice).The initial sequence of instructions, however, might be not valid. You don't want your robot to break so you decided to reprogram it in the following way: you will remove some (possibly, all or none) instructions from the initial sequence of instructions, then rearrange the remaining instructions as you wish and turn on your robot to move. Your task is to remove as few instructions from the initial sequence as possible and rearrange the remaining ones so that the sequence is valid. Report the valid sequence of the maximum length you can obtain.Note that you can choose any order of remaining instructions (you don't need to minimize the number of swaps or any other similar metric).You have to answer q independent test cases.InputThe first line of the input contains one integer q (1 \le q \le 2 \cdot 10^4) — the number of test cases.The next q lines contain test cases. The i-th test case is given as the string s consisting of at least 1 and no more than 10^5 characters 'L', 'R', 'U' and 'D' — the initial sequence of instructions.It is guaranteed that the sum of |s| (where |s| is the length of s) does not exceed 10^5 over all test cases (\sum |s| \le 10^5).OutputFor each test case print the answer on it. In the first line print the maximum number of remaining instructions. In the second line print the valid sequence of remaining instructions t the robot has to perform. The moves are performed from left to right in the order of the printed sequence. If there are several answers, you can print any. If the answer is 0, you are allowed to print an empty line (but you can don't print it).ExampleInput
6
LRU
DURLDRUDRULRDURDDL
LRUDDLRUDRUL
LLLLRRRR
URDUR
LLL
Output
2
LR
14
RUURDDDDLLLUUR
12
ULDDDRRRUULL
2
LR
2
UD
0
NoteThere are only two possible answers in the first test case: "LR" and "RL".The picture corresponding to the second test case: Note that the direction of traverse does not matter Another correct answer to the third test case: "URDDLLLUURDR". | 6
LRU
DURLDRUDRULRDURDDL
LRUDDLRUDRUL
LLLLRRRR
URDUR
LLL
| 2 LR 14 RUURDDDDLLLUUR 12 ULDDDRRRUULL 2 LR 2 UD 0 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', '*1200'] |
A. Three Friendstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThree friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it.Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x.Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.You have to answer q independent test cases.InputThe first line of the input contains one integer q (1 \le q \le 1000) — the number of test cases.The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 \le a, b, c \le 10^9) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.OutputFor each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.ExampleInput
8
3 3 4
10 20 30
5 5 5
2 4 3
1 1000000000 1000000000
1 1000000000 999999999
3 2 5
3 2 6
Output
0
36
0
0
1999999994
1999999994
2
4
| 8
3 3 4
10 20 30
5 5 5
2 4 3
1 1000000000 1000000000
1 1000000000 999999999
3 2 5
3 2 6
| 0 36 0 0 1999999994 1999999994 2 4 | 1 second | 256 megabytes | ['brute force', 'greedy', 'math', 'sortings', '*900'] |
F. Divide The Studentstime limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRecently a lot of students were enrolled in Berland State University. All students were divided into groups according to their education program. Some groups turned out to be too large to attend lessons in the same auditorium, so these groups should be divided into two subgroups. Your task is to help divide the first-year students of the computer science faculty.There are t new groups belonging to this faculty. Students have to attend classes on three different subjects — maths, programming and P. E. All classes are held in different places according to the subject — maths classes are held in auditoriums, programming classes are held in computer labs, and P. E. classes are held in gyms.Each group should be divided into two subgroups so that there is enough space in every auditorium, lab or gym for all students of the subgroup. For the first subgroup of the i-th group, maths classes are held in an auditorium with capacity of a_{i, 1} students; programming classes are held in a lab that accomodates up to b_{i, 1} students; and P. E. classes are held in a gym having enough place for c_{i, 1} students. Analogically, the auditorium, lab and gym for the second subgroup can accept no more than a_{i, 2}, b_{i, 2} and c_{i, 2} students, respectively.As usual, some students skip some classes. Each student considers some number of subjects (from 0 to 3) to be useless — that means, he skips all classes on these subjects (and attends all other classes). This data is given to you as follows — the i-th group consists of: d_{i, 1} students which attend all classes; d_{i, 2} students which attend all classes, except for P. E.; d_{i, 3} students which attend all classes, except for programming; d_{i, 4} students which attend only maths classes; d_{i, 5} students which attend all classes, except for maths; d_{i, 6} students which attend only programming classes; d_{i, 7} students which attend only P. E. There is one more type of students — those who don't attend any classes at all (but they, obviously, don't need any place in auditoriums, labs or gyms, so the number of those students is insignificant in this problem).Your task is to divide each group into two subgroups so that every auditorium (or lab, or gym) assigned to each subgroup has enough place for all students from this subgroup attending the corresponding classes (if it is possible). Each student of the i-th group should belong to exactly one subgroup of the i-th group; it is forbidden to move students between groups.InputThe first line contains one integer t (1 \le t \le 300) — the number of groups.Then the descriptions of groups follow. The description of the i-th group consists of three lines: the first line contains three integers a_{i, 1}, b_{i, 1} and c_{i, 1} (1 \le a_{i, 1}, b_{i, 1}, c_{i, 1} \le 3000) — the capacity of the auditorium, lab and gym assigned to the first subgroup of the i-th group, respectively; the second line contains three integers a_{i, 2}, b_{i, 2} and c_{i, 2} (1 \le a_{i, 2}, b_{i, 2}, c_{i, 2} \le 3000) — the capacity of the auditorium, lab and gym assigned to the second subgroup of the i-th group, respectively; the third line contains integers d_{i, 1}, d_{i, 2}, ..., d_{i, 7} (0 \le d_{i, j} \le 3000) — the number of students belonging to each of the seven aforementioned types in the i-th group. It is not guaranteed that the sum of these values is positive — a group can consist entirely of students that don't attend classes at all. It is guaranteed that the total number of students in all groups is not greater than 3000.OutputFor each group, print the result of its division as follows: if it is impossible to divide the group, print one integer -1; otherwise print seven integers f_{i, 1}, f_{i, 2}, ..., f_{i, 7} (0 \le f_{i, j} \le d_{i, j}) — the number of students the first, second, ..., seventh type in the first subgroup of the i-th group (all other students will be assigned to the second subgroup). If there are multiple answers, print any of them. ExampleInput
3
9 4 13
1 10 3
1 2 3 4 5 6 7
9 4 13
1 10 3
2 1 3 4 5 6 7
1 2 3
4 5 6
0 0 0 0 0 0 0
Output
1 1 3 4 2 0 7
-1
0 0 0 0 0 0 0
| 3
9 4 13
1 10 3
1 2 3 4 5 6 7
9 4 13
1 10 3
2 1 3 4 5 6 7
1 2 3
4 5 6
0 0 0 0 0 0 0
| 1 1 3 4 2 0 7 -1 0 0 0 0 0 0 0 | 8 seconds | 512 megabytes | ['brute force', '*2700'] |
E. Common Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt first, let's define function f(x) as follows: \begin{matrix} f(x) & = & \left\{ \begin{matrix} \frac{x}{2} & \mbox{if } x \text{ is even} \\ x - 1 & \mbox{otherwise } \end{matrix} \right. \end{matrix} We can see that if we choose some value v and will apply function f to it, then apply f to f(v), and so on, we'll eventually get 1. Let's write down all values we get in this process in a list and denote this list as path(v). For example, path(1) = [1], path(15) = [15, 14, 7, 6, 3, 2, 1], path(32) = [32, 16, 8, 4, 2, 1].Let's write all lists path(x) for every x from 1 to n. The question is next: what is the maximum value y such that y is contained in at least k different lists path(x)?Formally speaking, you need to find maximum y such that \left| \{ x ~|~ 1 \le x \le n, y \in path(x) \} \right| \ge k.InputThe first line contains two integers n and k (1 \le k \le n \le 10^{18}).OutputPrint the only integer — the maximum value that is contained in at least k paths.ExamplesInput
11 3
Output
5
Input
11 6
Output
4
Input
20 20
Output
1
Input
14 5
Output
6
Input
1000000 100
Output
31248
NoteIn the first example, the answer is 5, since 5 occurs in path(5), path(10) and path(11).In the second example, the answer is 4, since 4 occurs in path(4), path(5), path(8), path(9), path(10) and path(11).In the third example n = k, so the answer is 1, since 1 is the only number occuring in all paths for integers from 1 to 20. | 11 3
| 5 | 2 seconds | 256 megabytes | ['binary search', 'combinatorics', 'dp', 'math', '*2100'] |
D. Portalstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army — formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle: if you are currently in the castle i, you may leave one warrior to defend castle i; there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v. Obviously, when you order your warrior to defend some castle, he leaves your army.You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it — your score will be calculated afterwards).Can you determine an optimal strategy of capturing and defending the castles?InputThe first line contains three integers n, m and k (1 \le n \le 5000, 0 \le m \le \min(\frac{n(n - 1)}{2}, 3 \cdot 10^5), 0 \le k \le 5000) — the number of castles, the number of portals and initial size of your army, respectively.Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 \le a_i, b_i, c_i \le 5000) — the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 \le v_i < u_i \le n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + \sum\limits_{i = 1}^{n} b_i \le 5000).OutputIf it's impossible to capture all the castles, print one integer -1.Otherwise, print one integer equal to the maximum sum of importance values of defended castles.ExamplesInput
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
NoteThe best course of action in the first example is as follows: capture the first castle; hire warriors from the first castle, your army has 11 warriors now; capture the second castle; capture the third castle; hire warriors from the third castle, your army has 13 warriors now; capture the fourth castle; leave one warrior to protect the fourth castle, your army has 12 warriors now. This course of action (and several other ones) gives 5 as your total score.The best course of action in the second example is as follows: capture the first castle; hire warriors from the first castle, your army has 11 warriors now; capture the second castle; capture the third castle; hire warriors from the third castle, your army has 13 warriors now; capture the fourth castle; leave one warrior to protect the fourth castle, your army has 12 warriors now; send one warrior to protect the first castle through the third portal, your army has 11 warriors now. This course of action (and several other ones) gives 22 as your total score.In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it. | 4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
| 5 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'greedy', 'implementation', 'sortings', '*2100'] |
C. Shawarma Tenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.The main school of the capital is located in (s_x, s_y). There are n students attending this school, the i-th of them lives in the house located in (x_i, y_i). It is possible that some students live in the same house, but no student lives in (s_x, s_y).After classes end, each student walks from the school to his house along one of the shortest paths. So the distance the i-th student goes from the school to his house is |s_x - x_i| + |s_y - y_i|.The Provision Department of Berland has decided to open a shawarma tent somewhere in the capital (at some point with integer coordinates). It is considered that the i-th student will buy a shawarma if at least one of the shortest paths from the school to the i-th student's house goes through the point where the shawarma tent is located. It is forbidden to place the shawarma tent at the point where the school is located, but the coordinates of the shawarma tent may coincide with the coordinates of the house of some student (or even multiple students).You want to find the maximum possible number of students buying shawarma and the optimal location for the tent itself.InputThe first line contains three integers n, s_x, s_y (1 \le n \le 200\,000, 0 \le s_x, s_y \le 10^{9}) — the number of students and the coordinates of the school, respectively.Then n lines follow. The i-th of them contains two integers x_i, y_i (0 \le x_i, y_i \le 10^{9}) — the location of the house where the i-th student lives. Some locations of houses may coincide, but no student lives in the same location where the school is situated.OutputThe output should consist of two lines. The first of them should contain one integer c — the maximum number of students that will buy shawarmas at the tent. The second line should contain two integers p_x and p_y — the coordinates where the tent should be located. If there are multiple answers, print any of them. Note that each of p_x and p_y should be not less than 0 and not greater than 10^{9}.ExamplesInput
4 3 2
1 3
4 2
5 1
4 1
Output
3
4 2
Input
3 100 100
0 0
0 0
100 200
Output
2
99 100
Input
7 10 12
5 6
20 23
15 4
16 5
4 54
12 1
4 15
Output
4
10 11
NoteIn the first example, If we build the shawarma tent in (4, 2), then the students living in (4, 2), (4, 1) and (5, 1) will visit it.In the second example, it is possible to build the shawarma tent in (1, 1), then both students living in (0, 0) will visit it. | 4 3 2
1 3
4 2
5 1
4 1
| 3 4 2 | 1 second | 256 megabytes | ['brute force', 'geometry', 'greedy', 'implementation', '*1300'] |
B. Blockstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 \cdot n. If it is impossible to find such a sequence of operations, you need to report it.InputThe first line contains one integer n (2 \le n \le 200) — the number of blocks.The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black. OutputIf it is impossible to make all the blocks having the same color, print -1.Otherwise, print an integer k (0 \le k \le 3 \cdot n) — the number of operations. Then print k integers p_1, p_2, \dots, p_k (1 \le p_j \le n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.If there are multiple answers, print any of them.ExamplesInput
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
NoteIn the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white). | 8
BWWWWWWB
| 3 6 2 4 | 2 seconds | 256 megabytes | ['greedy', 'math', '*1300'] |
A. Suitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA new delivery of clothing has arrived today to the clothing store. This delivery consists of a ties, b scarves, c vests and d jackets.The store does not sell single clothing items — instead, it sells suits of two types: a suit of the first type consists of one tie and one jacket; a suit of the second type consists of one scarf, one vest and one jacket. Each suit of the first type costs e coins, and each suit of the second type costs f coins.Calculate the maximum possible cost of a set of suits that can be composed from the delivered clothing items. Note that one item cannot be used in more than one suit (though some items may be left unused).InputThe first line contains one integer a (1 \le a \le 100\,000) — the number of ties.The second line contains one integer b (1 \le b \le 100\,000) — the number of scarves.The third line contains one integer c (1 \le c \le 100\,000) — the number of vests.The fourth line contains one integer d (1 \le d \le 100\,000) — the number of jackets.The fifth line contains one integer e (1 \le e \le 1\,000) — the cost of one suit of the first type.The sixth line contains one integer f (1 \le f \le 1\,000) — the cost of one suit of the second type.OutputPrint one integer — the maximum total cost of some set of suits that can be composed from the delivered items. ExamplesInput
4
5
6
3
1
2
Output
6
Input
12
11
13
20
4
6
Output
102
Input
17
14
5
21
15
17
Output
325
NoteIt is possible to compose three suits of the second type in the first example, and their total cost will be 6. Since all jackets will be used, it's impossible to add anything to this set.The best course of action in the second example is to compose nine suits of the first type and eleven suits of the second type. The total cost is 9 \cdot 4 + 11 \cdot 6 = 102. | 4
5
6
3
1
2
| 6 | 1 second | 256 megabytes | ['brute force', 'greedy', 'math', '*800'] |
I. Xor on Figurestime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is given an integer k and a grid 2^k \times 2^k with some numbers written in its cells, cell (i, j) initially contains number a_{ij}. Grid is considered to be a torus, that is, the cell to the right of (i, 2^k) is (i, 1), the cell below the (2^k, i) is (1, i) There is also given a lattice figure F, consisting of t cells, where t is odd. F doesn't have to be connected.We can perform the following operation: place F at some position on the grid. (Only translations are allowed, rotations and reflections are prohibited). Now choose any nonnegative integer p. After that, for each cell (i, j), covered by F, replace a_{ij} by a_{ij}\oplus p, where \oplus denotes the bitwise XOR operation.More formally, let F be given by cells (x_1, y_1), (x_2, y_2), \dots, (x_t, y_t). Then you can do the following operation: choose any x, y with 1\le x, y \le 2^k, any nonnegative integer p, and for every i from 1 to n replace number in the cell (((x + x_i - 1)\bmod 2^k) + 1, ((y + y_i - 1)\bmod 2^k) + 1) with a_{((x + x_i - 1)\bmod 2^k) + 1, ((y + y_i - 1)\bmod 2^k) + 1}\oplus p.Our goal is to make all the numbers equal to 0. Can we achieve it? If we can, find the smallest number of operations in which it is possible to do this.InputThe first line contains a single integer k (1 \le k \le 9).The i-th of the next 2^k lines contains 2^k integers a_{i1}, a_{i2}, \dots, a_{i2^k} (0 \le a_{ij} < 2^{60}) — initial values in the i-th row of the grid.The next line contains a single integer t (1\le t \le \min(99, 4^k), t is odd) — number of cells of figure.i-th of next t lines contains two integers x_i and y_i (1 \le x_i, y_i \le 2^k), describing the position of the i-th cell of the figure.It is guaranteed that all cells are different, but it is not guaranteed that the figure is connected. OutputIf it is impossible to make all numbers in the grid equal to 0 with these operations, output -1.Otherwise, output a single integer — the minimal number of operations needed to do this. It can be shown that if it is possible to make all numbers equal 0, it is possible to do so in less than 10^{18} operations.ExampleInput
2
5 5 5 5
2 6 2 3
0 0 2 0
0 0 0 0
5
1 1
1 2
1 3
1 4
2 4
Output
3NoteThe figure and the operations for the example are shown above: | 2
5 5 5 5
2 6 2 3
0 0 2 0
0 0 0 0
5
1 1
1 2
1 3
1 4
2 4
| 3 | 5 seconds | 256 megabytes | ['constructive algorithms', 'fft', 'math', '*3500'] |
H. Number of Componentstime limit per test8 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose that we have an array of n distinct numbers a_1, a_2, \dots, a_n. Let's build a graph on n vertices as follows: for every pair of vertices i < j let's connect i and j with an edge, if a_i < a_j. Let's define weight of the array to be the number of connected components in this graph. For example, weight of array [1, 4, 2] is 1, weight of array [5, 4, 3] is 3.You have to perform q queries of the following form — change the value at some position of the array. After each operation, output the weight of the array. Updates are not independent (the change stays for the future).InputThe first line contains two integers n and q (1 \le n, q \le 5 \cdot 10^5) — the size of the array and the number of queries.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6) — the initial array.Each of the next q lines contains two integers pos and x (1 \le pos \le n, 1 \le x \le 10^6, x \ne a_{pos}). It means that you have to make a_{pos}=x.It's guaranteed that at every moment of time, all elements of the array are different.OutputAfter each query, output the weight of the array.ExampleInput
5 3
50 40 30 20 10
1 25
3 45
1 48
Output
3
3
4
NoteAfter the first query array looks like [25, 40, 30, 20, 10], the weight is equal to 3.After the second query array looks like [25, 40, 45, 20, 10], the weight is still equal to 3.After the third query array looks like [48, 40, 45, 20, 10], the weight is equal to 4. | 5 3
50 40 30 20 10
1 25
3 45
1 48
| 3 3 4 | 8 seconds | 256 megabytes | ['data structures', '*3300'] |
G. Subset with Zero Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers a_1, a_2, \dots, a_n, such that for each 1\le i \le n holds i-n\le a_i\le i-1.Find some nonempty subset of these integers, whose sum is equal to 0. It can be shown that such a subset exists under given constraints. If there are several possible subsets with zero-sum, you can find any of them.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^6). The description of the test cases follows.The first line of each test case contains a single integer n (1\le n \le 10^6).The second line of each test case contains n integers a_1, a_2, \dots, a_n (i-n \le a_i \le i-1).It is guaranteed that the sum of n over all test cases does not exceed 10^6.OutputFor each test case, output two lines.In the first line, output s (1\le s \le n) — the number of elements in your subset.In the second line, output s integers i_1, i_2, \dots, i_s (1\le i_k \le n). All integers have to be pairwise different, and a_{i_1} + a_{i_2} + \dots + a_{i_s} has to be equal to 0. If there are several possible subsets with zero-sum, you can find any of them.ExampleInput
2
5
0 1 2 3 4
4
-3 1 1 1
Output
1
1
4
1 4 3 2
NoteIn the first example, we get sum is a_1 = 0.In the second example, we get sum is a_1 + a_4 + a_3 + a_2 = 0. | 2
5
0 1 2 3 4
4
-3 1 1 1
| 1 1 4 1 4 3 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', 'math', '*2700'] |
F. Awesome Substringstime limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's call a binary string s awesome, if it has at least 1 symbol 1 and length of the string is divisible by the number of 1 in it. In particular, 1, 1010, 111 are awesome, but 0, 110, 01010 aren't.You are given a binary string s. Count the number of its awesome substrings.A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.InputThe first line contains the string s (1 \leq |s|\le 200\,000) consisting only of zeros and ones.OutputOutput a single number — the number of awesome substrings of s.ExamplesInput
111
Output
6
Input
01010
Output
10
Input
0000
Output
0
Input
1111100000
Output
25
NoteIn the first sample, all substrings of s are awesome.In the second sample, we have the following awesome substrings of s: 1 (2 times), 01 (2 times), 10 (2 times), 010 (2 times), 1010, 0101In the third sample, no substring is awesome. | 111
| 6 | 8 seconds | 512 megabytes | ['math', 'strings', '*2600'] |
E. Divide Pointstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of n\ge 2 pairwise different points with integer coordinates. Your task is to partition these points into two nonempty groups A and B, such that the following condition holds:For every two points P and Q, write the Euclidean distance between them on the blackboard: if they belong to the same group — with a yellow pen, and if they belong to different groups — with a blue pen. Then no yellow number is equal to any blue number.It is guaranteed that such a partition exists for any possible input. If there exist multiple partitions, you are allowed to output any of them.InputThe first line contains one integer n (2 \le n \le 10^3) — the number of points.The i-th of the next n lines contains two integers x_i and y_i (-10^6 \le x_i, y_i \le 10^6) — the coordinates of the i-th point. It is guaranteed that all n points are pairwise different.OutputIn the first line, output a (1 \le a \le n-1) — the number of points in a group A.In the second line, output a integers — the indexes of points that you include into group A.If there are multiple answers, print any.ExamplesInput
3
0 0
0 1
1 0
Output
1
1 Input
4
0 1
0 -1
1 0
-1 0
Output
2
1 2 Input
3
-2 1
1 1
-1 0
Output
1
2 Input
6
2 5
0 3
-4 -1
-5 -4
1 0
3 -1
Output
1
6 Input
2
-1000000 -1000000
1000000 1000000
Output
1
1 NoteIn the first example, we set point (0, 0) to group A and points (0, 1) and (1, 0) to group B. In this way, we will have 1 yellow number \sqrt{2} and 2 blue numbers 1 on the blackboard.In the second example, we set points (0, 1) and (0, -1) to group A and points (-1, 0) and (1, 0) to group B. In this way, we will have 2 yellow numbers 2, 4 blue numbers \sqrt{2} on the blackboard. | 3
0 0
0 1
1 0
| 1 1 | 1 second | 256 megabytes | ['constructive algorithms', 'geometry', 'math', '*2300'] |
D. Strange Devicetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden an array a of n pairwise different numbers (this means that no two numbers are equal). You can get some information about this array using a new device you just ordered on Amazon. This device can answer queries of the following form: in response to the positions of k different elements of the array, it will return the position and value of the m-th among them in the ascending order.Unfortunately, the instruction for the device was lost during delivery. However, you remember k, but don't remember m. Your task is to find m using queries to this device. You can ask not more than n queries.Note that the array a and number m are fixed before the start of the interaction and don't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries, and you don't need to guess array a. You just have to guess m.InputThe first line contains two integers n and k (1\le k < n \le 500) — the length of the array and the number of the elements in the query.It is guaranteed that number m satisfies 1\le m \le k, elements a_1, a_2, \dots, a_n of the array satisfy 0\le a_i \le 10^9, and all of them are different.InteractionYou begin the interaction by reading n and k.To ask a question about elements on positions x_1, x_2, \dots, x_k, in a separate line output? x_1 x_2 x_3 ... x_kNumbers in the query have to satisfy 1 \le x_i \le n, and all x_i have to be different. Don't forget to 'flush', to get the answer.In response, you will receive two integers pos and a_{pos} — the position in the array a of the m-th in ascending order element among a_{x_1}, a_{x_2}, \dots, a_{x_k}, and the element on this position.In case your query is invalid or you asked more than n queries, the program will print -1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine m, output ! mAfter printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack formatFor the hacks use the following format:The first line has to contain three integers n, k, m (1 \le m \le k < n \le 500) — the length of the array, number of elements in the query, and which in the ascending order number the device returns.In the next line output n integers a_1, a_2, \dots, a_n (0\le a_i \le 10^9) — the elements of the array. They have to be pairwise different.ExampleInput
4 3
4 9
4 9
4 9
1 2Output
? 2 3 4
? 1 3 4
? 1 2 4
? 1 2 3
! 3
NoteIn the example, n = 4, k = 3, m = 3, a = [2, 0, 1, 9]. | 4 3
4 9
4 9
4 9
1 2 | ? 2 3 4 ? 1 3 4 ? 1 2 4 ? 1 2 3 ! 3 | 1 second | 256 megabytes | ['constructive algorithms', 'interactive', 'math', 'sortings', '*1900'] |
C. Make Goodtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call an array a_1, a_2, \dots, a_m of nonnegative integer numbers good if a_1 + a_2 + \dots + a_m = 2\cdot(a_1 \oplus a_2 \oplus \dots \oplus a_m), where \oplus denotes the bitwise XOR operation.For example, array [1, 2, 3, 6] is good, as 1 + 2 + 3 + 6 = 12 = 2\cdot 6 = 2\cdot (1\oplus 2 \oplus 3 \oplus 6). At the same time, array [1, 2, 1, 3] isn't good, as 1 + 2 + 1 + 3 = 7 \neq 2\cdot 1 = 2\cdot(1\oplus 2 \oplus 1 \oplus 3).You are given an array of length n: a_1, a_2, \dots, a_n. Append at most 3 elements to it to make it good. Appended elements don't have to be different. It can be shown that the solution always exists under the given constraints. If there are different solutions, you are allowed to output any of them. Note that you don't have to minimize the number of added elements!. So, if an array is good already you are allowed to not append elements.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10\,000). 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 size of the array.The second line of each test case contains n integers a_1, a_2, \dots, a_n (0\le a_i \le 10^9) — the elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output two lines.In the first line, output a single integer s (0\le s\le 3) — the number of elements you want to append.In the second line, output s integers b_1, \dots, b_s (0\le b_i \le 10^{18}) — the elements you want to append to the array.If there are different solutions, you are allowed to output any of them.ExampleInput
3
4
1 2 3 6
1
8
2
1 1
Output
0
2
4 4
3
2 6 2
NoteIn the first test case of the example, the sum of all numbers is 12, and their \oplus is 6, so the condition is already satisfied.In the second test case of the example, after adding 4, 4, the array becomes [8, 4, 4]. The sum of numbers in it is 16, \oplus of numbers in it is 8. | 3
4
1 2 3 6
1
8
2
1 1
| 0 2 4 4 3 2 6 2 | 2 seconds | 256 megabytes | ['bitmasks', 'constructive algorithms', 'math', '*1400'] |
B. Interesting Subarraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor an array a of integers let's denote its maximal element as \max(a), and minimal as \min(a). We will call an array a of k integers interesting if \max(a) - \min(a) \ge k. For example, array [1, 3, 4, 3] isn't interesting as \max(a) - \min(a) = 4 - 1 = 3 < 4 while array [7, 3, 0, 4, 3] is as \max(a) - \min(a) = 7 - 0 = 7 \ge 5.You are given an array a of n integers. Find some interesting nonempty subarray of a, or tell that it doesn't exist.An array b is a subarray of an array a if b can be obtained from a by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.InputThe first line contains integer number t (1 \le t \le 10\,000). Then t test cases follow.The first line of each test case contains a single integer n (2\le n \le 2\cdot 10^5) — the length of the array.The second line of each test case contains n integers a_1, a_2, \dots, a_n (0\le a_i \le 10^9) — the elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output "NO" in a separate line if there is no interesting nonempty subarray in a. Otherwise, output "YES" in a separate line. In the next line, output two integers l and r (1\le l \le r \le n) — bounds of the chosen subarray. If there are multiple answers, print any.You can print each letter in any case (upper or lower).ExampleInput
3
5
1 2 3 4 5
4
2 0 1 9
2
2019 2020
Output
NO
YES
1 4
NO
NoteIn the second test case of the example, one of the interesting subarrays is a = [2, 0, 1, 9]: \max(a) - \min(a) = 9 - 0 = 9 \ge 4. | 3
5
1 2 3 4 5
4
2 0 1 9
2
2019 2020
| NO YES 1 4 NO | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*1200'] |
A. Card Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo players decided to play one interesting card game.There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has at least one card. The game goes as follows: on each turn, each player chooses one of their cards (whichever they want) and puts on the table, so that the other player doesn't see which card they chose. After that, both cards are revealed, and the player, value of whose card was larger, takes both cards in his hand. Note that as all cards have different values, one of the cards will be strictly larger than the other one. Every card may be played any amount of times. The player loses if he doesn't have any cards.For example, suppose that n = 5, the first player has cards with values 2 and 3, and the second player has cards with values 1, 4, 5. Then one possible flow of the game is:The first player chooses the card 3. The second player chooses the card 1. As 3>1, the first player gets both cards. Now the first player has cards 1, 2, 3, the second player has cards 4, 5.The first player chooses the card 3. The second player chooses the card 4. As 3<4, the second player gets both cards. Now the first player has cards 1, 2. The second player has cards 3, 4, 5.The first player chooses the card 1. The second player chooses the card 3. As 1<3, the second player gets both cards. Now the first player has only the card 2. The second player has cards 1, 3, 4, 5.The first player chooses the card 2. The second player chooses the card 4. As 2<4, the second player gets both cards. Now the first player is out of cards and loses. Therefore, the second player wins.Who will win if both players are playing optimally? It can be shown that one of the players has a winning strategy.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). The description of the test cases follows.The first line of each test case contains three integers n, k_1, k_2 (2 \le n \le 100, 1 \le k_1 \le n - 1, 1 \le k_2 \le n - 1, k_1 + k_2 = n) — the number of cards, number of cards owned by the first player and second player correspondingly.The second line of each test case contains k_1 integers a_1, \dots, a_{k_1} (1 \le a_i \le n) — the values of cards of the first player.The third line of each test case contains k_2 integers b_1, \dots, b_{k_2} (1 \le b_i \le n) — the values of cards of the second player.It is guaranteed that the values of all cards are different.OutputFor each test case, output "YES" in a separate line, if the first player wins. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExampleInput
2
2 1 1
2
1
5 2 3
2 3
1 4 5
Output
YES
NO
NoteIn the first test case of the example, there is only one possible move for every player: the first player will put 2, the second player will put 1. 2>1, so the first player will get both cards and will win.In the second test case of the example, it can be shown that it is the second player who has a winning strategy. One possible flow of the game is illustrated in the statement. | 2
2 1 1
2
1
5 2 3
2 3
1 4 5
| YES NO | 1 second | 256 megabytes | ['games', 'greedy', 'math', '*800'] |
B. Modulo Equalitytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer m and two integer sequence: a=[a_1, a_2, \ldots, a_n] and b=[b_1, b_2, \ldots, b_n]. Both of these sequence have a length n.Permutation is a sequence of n different positive integers from 1 to n. For example, these sequences are permutations: [1], [1,2], [2,1], [6,7,3,4,1,2,5]. These are not: [0], [1,1], [2,3].You need to find the non-negative integer x, and increase all elements of a_i by x, modulo m (i.e. you want to change a_i to (a_i + x) \bmod m), so it would be possible to rearrange elements of a to make it equal b, among them you need to find the smallest possible x.In other words, you need to find the smallest non-negative integer x, for which it is possible to find some permutation p=[p_1, p_2, \ldots, p_n], such that for all 1 \leq i \leq n, (a_i + x) \bmod m = b_{p_i}, where y \bmod m — remainder of division of y by m.For example, if m=3, a = [0, 0, 2, 1], b = [2, 0, 1, 1], you can choose x=1, and a will be equal to [1, 1, 0, 2] and you can rearrange it to make it equal [2, 0, 1, 1], which is equal to b.InputThe first line contains two integers n,m (1 \leq n \leq 2000, 1 \leq m \leq 10^9): number of elemens in arrays and m.The second line contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i < m).The third line contains n integers b_1, b_2, \ldots, b_n (0 \leq b_i < m).It is guaranteed that there exists some non-negative integer x, such that it would be possible to find some permutation p_1, p_2, \ldots, p_n such that (a_i + x) \bmod m = b_{p_i}.OutputPrint one integer, the smallest non-negative integer x, such that it would be possible to find some permutation p_1, p_2, \ldots, p_n such that (a_i + x) \bmod m = b_{p_i} for all 1 \leq i \leq n.ExamplesInput
4 3
0 0 2 1
2 0 1 1
Output
1
Input
3 2
0 0 0
1 1 1
Output
1
Input
5 10
0 0 0 1 2
2 1 0 0 0
Output
0
| 4 3
0 0 2 1
2 0 1 1
| 1 | 3 seconds | 256 megabytes | ['brute force', 'sortings', '*1500'] |
A. Equationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a positive integer composite if it has at least one divisor other than 1 and itself. For example: the following numbers are composite: 1024, 4, 6, 9; the following numbers are not composite: 13, 1, 2, 3, 37. You are given a positive integer n. Find two composite integers a,b such that a-b=n.It can be proven that solution always exists.InputThe input contains one integer n (1 \leq n \leq 10^7): the given integer.OutputPrint two composite integers a,b (2 \leq a, b \leq 10^9, a-b=n).It can be proven, that solution always exists.If there are several possible solutions, you can print any. ExamplesInput
1
Output
9 8
Input
512
Output
4608 4096
| 1
| 9 8 | 3 seconds | 256 megabytes | ['brute force', 'math', '*800'] |
E. Happy Cactustime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a cactus graph, in this graph each edge lies on at most one simple cycle.It is given as m edges a_i, b_i, weight of i-th edge is i.Let's call a path in cactus increasing if the weights of edges on this path are increasing.Let's call a pair of vertices (u,v) happy if there exists an increasing path that starts in u and ends in v.For each vertex u find the number of other vertices v, such that pair (u,v) is happy.InputThe first line of input contains two integers n,m (1 \leq n, m \leq 500\,000): the number of vertices and edges in the given cactus.The next m lines contain a description of cactus edges, i-th of them contain two integers a_i, b_i (1 \leq a_i, b_i \leq n, a_i \neq b_i).It is guaranteed that there are no multiple edges and the graph is connected.OutputPrint n integers, required values for vertices 1,2,\ldots,n.ExamplesInput
3 3
1 2
2 3
3 1
Output
2 2 2
Input
5 4
1 2
2 3
3 4
4 5
Output
4 4 3 2 1
| 3 3
1 2
2 3
3 1
| 2 2 2 | 3 seconds | 256 megabytes | ['dp', '*3400'] |
D. Invertation in Tournamenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tournament — complete directed graph.In one operation you can pick any vertex v and change the direction of all edges with v on one of the ends (i.e all edges u \to v change their orientation to v \to u and vice versa).You want to make the tournament strongly connected with the smallest possible number of such operations if it is possible. Also, if it is possible, you need to find the number of ways to make this number of operations to make graph strongly connected (two ways are different if for some i vertex that we chose on i-th operation in one way is different from vertex that we chose on i-th operation in another way). You only need to find this value modulo 998\,244\,353.InputThe first line of input contains one integer n (3 \leq n \leq 2000): the number of vertices in the tournament.Following n lines contain a description of the given tournament, each of them contains a binary string of length n. If j-th character of i-th string is equal to '1', then the graph has an edge i \to j.It is guaranteed that there are no edges i \to i and the graph has exactly one edge among i \to j and j \to i for different i and j.OutputIf it is not possible to convert tournament to strongly connected with the given operations, output "-1".Otherwise, output two integers: the smallest number of operations that you need to make the given graph strongly connected and the number of ways to do this number of operations to make graph strongly connected, modulo 998\,244\,353.ExamplesInput
3
010
001
100
Output
0 1
Input
4
0010
1000
0100
1110
Output
-1
Input
6
010000
001000
100000
111001
111100
111010
Output
2 18
| 3
010
001
100
| 0 1 | 3 seconds | 256 megabytes | ['brute force', 'divide and conquer', 'graphs', 'math', '*3200'] |
C. K Integerstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p_1, p_2, \ldots, p_n.In one move you can swap two adjacent values.You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,\ldots, k, in other words in the end there should be an integer i, 1 \leq i \leq n-k+1 such that p_i = 1, p_{i+1} = 2, \ldots, p_{i+k-1}=k.Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,\ldots,k appear in the permutation.You need to find f(1), f(2), \ldots, f(n).InputThe first line of input contains one integer n (1 \leq n \leq 200\,000): the number of elements in the permutation.The next line of input contains n integers p_1, p_2, \ldots, p_n: given permutation (1 \leq p_i \leq n).OutputPrint n integers, the minimum number of moves that you need to make a subsegment with values 1,2,\ldots,k appear in the permutation, for k=1, 2, \ldots, n.ExamplesInput
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
| 5
5 4 3 2 1
| 0 1 3 6 10 | 3 seconds | 256 megabytes | ['binary search', 'data structures', '*2300'] |
B. Domino for Youngtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a Young diagram. Given diagram is a histogram with n columns of lengths a_1, a_2, \ldots, a_n (a_1 \geq a_2 \geq \ldots \geq a_n \geq 1). Young diagram for a=[3,2,2,2,1]. Your goal is to find the largest number of non-overlapping dominos that you can draw inside of this histogram, a domino is a 1 \times 2 or 2 \times 1 rectangle.InputThe first line of input contain one integer n (1 \leq n \leq 300\,000): the number of columns in the given histogram.The next line of input contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 300\,000, a_i \geq a_{i+1}): the lengths of columns.OutputOutput one integer: the largest number of non-overlapping dominos that you can draw inside of the given Young diagram.ExampleInput
5
3 2 2 2 1
Output
4
NoteSome of the possible solutions for the example: | 5
3 2 2 2 1
| 4 | 3 seconds | 256 megabytes | ['dp', 'greedy', 'math', '*2000'] |
A. Long Beautiful Integertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer x of n digits a_1, a_2, \ldots, a_n, which make up its decimal notation in order from left to right.Also, you are given a positive integer k < n.Let's call integer b_1, b_2, \ldots, b_m beautiful if b_i = b_{i+k} for each i, such that 1 \leq i \leq m - k.You need to find the smallest beautiful integer y, such that y \geq x. InputThe first line of input contains two integers n, k (2 \leq n \leq 200\,000, 1 \leq k < n): the number of digits in x and k.The next line of input contains n digits a_1, a_2, \ldots, a_n (a_1 \neq 0, 0 \leq a_i \leq 9): digits of x.OutputIn the first line print one integer m: the number of digits in y.In the next line print m digits b_1, b_2, \ldots, b_m (b_1 \neq 0, 0 \leq b_i \leq 9): digits of y.ExamplesInput
3 2
353
Output
3
353
Input
4 2
1234
Output
4
1313
| 3 2
353
| 3 353 | 3 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', 'strings', '*1700'] |
L. Lexicographytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLucy likes letters. She studied the definition of the lexicographical order at school and plays with it.At first, she tried to construct the lexicographically smallest word out of given letters. It was so easy! Then she tried to build multiple words and minimize one of them. This was much harder!Formally, Lucy wants to make n words of length l each out of the given n \cdot l letters, so that the k-th of them in the lexicographic order is lexicographically as small as possible.InputThe first line contains three integers n, l, and k (1\le k \le n \le 1\,000; 1 \le l \le 1\,000) — the total number of words, the length of each word, and the index of the word Lucy wants to minimize.The next line contains a string of n \cdot l lowercase letters of the English alphabet.OutputOutput n words of l letters each, one per line, using the letters from the input. Words must be sorted in the lexicographic order, and the k-th of them must be lexicographically as small as possible. If there are multiple answers with the smallest k-th word, output any of them.ExamplesInput
3 2 2
abcdef
Output
af
bc
edInput
2 3 1
abcabc
Output
aab
bcc
| 3 2 2
abcdef
| af bc ed | 3 seconds | 512 megabytes | ['constructive algorithms', 'strings', '*1800'] |
K. Key Storagetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKarl is developing a key storage service. Each user has a positive integer key.Karl knows that storing keys in plain text is bad practice. So, instead of storing a key, he decided to store a fingerprint of a key. However, using some existing fingerprint algorithm looked too boring to him, so he invented his own one.Karl's fingerprint is calculated by the following process: divide the given integer by 2, then divide the result by 3, then divide the result by 4, and so on, until we get a result that equals zero (we are speaking about integer division each time). The fingerprint is defined as the multiset of the remainders of these divisions. For example, this is how Karl's fingerprint algorithm is applied to the key 11: 11 divided by 2 has remainder 1 and result 5, then 5 divided by 3 has remainder 2 and result 1, and 1 divided by 4 has remainder 1 and result 0. Thus, the key 11 produces the sequence of remainders [1, 2, 1] and has the fingerprint multiset \{1, 1, 2\}.Ksenia wants to prove that Karl's fingerprint algorithm is not very good. For example, she found that both keys 178800 and 123456 produce the fingerprint of \{0, 0, 0, 0, 2, 3, 3, 4\}. Thus, users are at risk of fingerprint collision with some commonly used and easy to guess keys like 123456.Ksenia wants to make her words more persuasive. She wants to calculate the number of other keys that have the same fingerprint as the keys in the given list of some commonly used keys. Your task is to help her.InputThe first line contains an integer t (1 \le t \le 50\,000) — the number of commonly used keys to examine. Each of the next t lines contains one integer k_i (1 \le k_i \le 10^{18}) — the key itself. OutputFor each of the keys print one integer — the number of other keys that have the same fingerprint. ExampleInput
3
1
11
123456
Output
0
1
127
NoteThe other key with the same fingerprint as 11 is 15. 15 produces a sequence of remainders [1, 1, 2]. So both numbers have the fingerprint multiset \{1, 1, 2\}. | 3
1
11
123456
| 0 1 127 | 3 seconds | 512 megabytes | ['combinatorics', 'math', '*2100'] |
J. Just Arrange the Iconstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerPhone X is almost ready for release with n applications being preinstalled on the phone. A category of an application characterizes a genre or a theme of this application (like "game", "business", or "education"). The categories are given as integers between 1 and n, inclusive; the i-th application has category c_i. You can choose m — the number of screens and s — the size of each screen. You need to fit all n icons of the applications (one icon representing one application) meeting the following requirements: On each screen, all the icons must belong to applications of the same category (but different screens can contain icons of applications of the same category); Each screen must be either completely filled with icons (the number of icons on the screen is equal to s) or almost filled with icons (the number of icons is equal to s-1). Your task is to find the minimal possible number of screens m.InputThe first line contains an integer t (1 \le t \le 10\,000) — the number of test cases in the input. Then t test cases follow.The first line of each test case contains an integer n (1 \le n \le 2\cdot10^6) — the number of the icons. The second line contains n integers c_1, c_2, \dots, c_n (1 \le c_i \le n), where c_i is the category of the i-th application.It is guaranteed that the sum of the values of n for all test cases in the input does not exceed 2\cdot10^6.OutputPrint t integers — the answers to the given test cases in the order they follow in the input. The answer to a test case is an integer m — the minimum number of screens on which all n icons can be placed satisfying the given requirements.ExampleInput
3
11
1 5 1 5 1 5 1 1 1 1 5
6
1 2 2 2 2 1
5
4 3 3 1 2
Output
3
3
4
NoteIn the first test case of the example, all the icons can be placed on three screens of size 4: a screen with 4 icons of the category 1, a screen with 3 icons of the category 1, and a screen with 4 icons of the category 5. | 3
11
1 5 1 5 1 5 1 1 1 1 5
6
1 2 2 2 2 1
5
4 3 3 1 2
| 3 3 4 | 5 seconds | 512 megabytes | ['greedy', 'implementation', 'math', '*1800'] |
I. Intriguing Selectiontime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.You are the head coach of a chess club. The club has 2n players, each player has some strength which can be represented by a number, and all those numbers are distinct. The strengths of the players are not known to you.You need to select n players who would represent your club in the upcoming championship. Naturally, you want to select n players with the highest strengths.You can organize matches between the players to do that. In every match, you pick two players, they play some games, and you learn which one of the two has higher strength. You can wait for the outcome of a match before deciding who will participate in the next one.However, you do not want to know exactly how those n players compare between themselves, as that would make the championship itself less intriguing. More formally, you must reach a state where there is exactly one way to choose n players with the highest strengths that is consistent with the outcomes of the matches you organized, but there must be at least two possible orderings of those n players by strength that are consistent with the outcomes of the matches you organized.InteractionYour program has to process multiple test cases in one run. First, it should read the integer t (t \ge 1) — the number of test cases. Then, it should process the test cases one by one.In each test case, your program should start by reading the integer n (3 \le n \le 100) — the number of players to select out of 2n players. The sum of squares of the values of n over all test cases does not exceed 10\,000.Then your program can organize matches zero or more times. To organize a match, your program should print a match description formatted as ? i j — a question mark followed by two distinct numbers of players participating in the match. The players are numbered from 1 to 2n, inclusive. Remember to flush the output after printing the match description. Then your program should read the match outcome — it will be either the greater-than character (>), if the first player in the match description has higher strength, or the less-than character (<), if the second player in the match description has higher strength.Your program can organize at most 4n^2 matches. After it is done organizing matches, it should print the exclamation mark (!) and continue to the next test case, or exit gracefully if this was the last test case. Remember to flush the output after printing the exclamation mark.There must be exactly one way to choose n players with the highest strength that is consistent with the outcomes of the matches you organized, but there must be at least two possible orderings of those n players by their strength that are consistent with the outcomes of the matches you organized.The judging program picks some distinct numbers as the strengths of all players before your program starts organizing matches and uses them to answer the requests.ExampleInput
2
3
>
<
>
<
>
>
3
<
<
<
>
>
Output
? 1 3
? 4 2
? 4 5
? 6 5
? 3 4
? 5 6
!
? 3 4
? 4 2
? 5 3
? 6 4
? 3 1
!
NoteIn the example, the players in the first test case are sorted by strength in decreasing order. From the matches in the example output, we can deduce that players 1, 2, and 3 have the highest strength, but we do not know how the player 1 compares to the player 2. | 2
3
>
<
>
<
>
>
3
<
<
<
>
>
| ? 1 3 ? 4 2 ? 4 5 ? 6 5 ? 3 4 ? 5 6 ! ? 3 4 ? 4 2 ? 5 3 ? 6 4 ? 3 1 ! | 5 seconds | 512 megabytes | ['brute force', 'constructive algorithms', 'implementation', 'interactive', 'sortings', '*2600'] |
H. Help BerLinetime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVery soon, the new cell phone services provider "BerLine" will begin its work in Berland!The start of customer service is planned along the main street of the capital. There are n base stations that are already installed. They are located one after another along the main street in the order from the 1-st to the n-th from left to right. Currently, all these base stations are turned off. They will be turned on one by one, one base station per day, according to some permutation p = [p_1, p_2, \dots, p_n] ( 1 \le p_i \le n), where p_i is the index of a base station that will be turned on on the i-th day. Thus, it will take n days to turn on all base stations.Each base station is characterized by its operating frequency f_i — an integer between 1 and 24, inclusive.There is an important requirement for operating frequencies of base stations. Consider an arbitrary moment in time. For any phone owner, if we consider all base stations turned on in the access area of their phone, then in this set of base stations there should be at least one whose operating frequency is unique among the frequencies of these stations. Since the power of the phone and the position are not known in advance, this means that for any nonempty subsegment of turned on base stations, at least one of them has to have the operating frequency that is unique among the stations of this subsegment.For example, let's take a look at a case of n = 7, all n stations are turned on, and their frequencies are equal to f = [1, 2, 1, 3, 1, 2, 1]. Consider any subsegment of the base stations — there is a base station with a unique frequency within this subsegment. However, if f = [1, 2, 1, 2, 3, 2, 1], then there is no unique frequency on the segment [1, 2, 1, 2] from the index 1 to the index 4, inclusive.Your task is to assign a frequency from 1 to 24 to each of n base stations in such a way that the frequency requirement is met at every moment. Remember that the base stations are turned on in the order of the given permutation p.InputThe first line of the input contains an integer t (1 \le t \le 50) — the number of test cases in the input. Then t test case descriptions follow.The first line of a test case contains an integer n ( 1 \le n \le 8\,500) — the number of "BerLine" base stations.The following line contains n distinct integers p_1, p_2, \dots, p_n (1 \le p_i \le n) — the order in which the base stations are turned on, i. e. on the i-th day the base station with the index p_i is turned on.It is guaranteed that a correct answer exists for all test cases in the input.OutputPrint exactly t lines, where the j-th line contains the answer for the j-th test case in the input. Print the required frequencies f_1, f_2, \dots, f_n (1 \le f_i \le 24). If there are several possible answers, print any of them.ExampleInput
5
3
1 3 2
3
1 2 3
1
1
10
6 10 4 2 7 9 5 8 3 1
10
2 4 6 9 1 8 10 5 3 7
Output
1 3 2
10 20 10
1
2 3 4 5 3 1 3 5 4 2
1 2 3 4 5 6 7 8 9 10NoteIn the first test case n = 3 and p = [1, 3, 2]. The base stations can be assigned frequencies [1, 3, 2]. Day 1: only the base station 1 is turned on, its frequency is 1. Day 2: the base stations 1 and 3 are turned on, their frequencies are [1, 2]. Day 3: all base stations are turned on, their frequencies are [1, 3, 2] (in the direction along the street). On each day, each nonempty subsegment of turned on base stations has a base station with a unique frequency among this subsegment. It can be shown that three distinct frequencies are necessary in this test case. | 5
3
1 3 2
3
1 2 3
1
1
10
6 10 4 2 7 9 5 8 3 1
10
2 4 6 9 1 8 10 5 3 7
| 1 3 2 10 20 10 1 2 3 4 5 3 1 3 5 4 2 1 2 3 4 5 6 7 8 9 10 | 5 seconds | 512 megabytes | ['constructive algorithms', '*3200'] |
G. Game Relicstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputEsports is a form of competitive sports using video games. Dota 2 is one of the most popular competitive video games in Esports. Recently, a new video game Dota 3 was released. In Dota 3 a player can buy some relics for their hero. Relics are counters that track hero's actions and statistics in a game.Gloria likes to play Dota 3, so she wants to buy all n available relics for her favorite hero.Relics can be bought using an in-game currency called shards. Each relic has its own price — c_i shards for the i-th relic. A player can buy a relic using one of the following options: Pay c_i shards to buy the i-th relic; Pay x shards and randomly get one of all n relics. The probability of getting a relic is the same for all n relics. If a duplicate relic is received, then the relic is recycled and \frac{x}{2} shards are given back to the player. Gloria wants to buy all n relics. Help her minimize the expected number of shards she spends to buy all the relics.InputThe first line contains two integers n and x (1 \le n \le 100; 1 \le x \le 10\,000) — the number of relics and the cost to receive a random relic.The second line consists of n integers c_1, c_2, \ldots, c_n (x \le c_i \le 10\,000; \sum{c_i} \le 10\,000) — the prices of n relics.OutputPrint a single real number — the minimum expected number of shards that Gloria must spend to buy all the relics.The absolute or relative error should not exceed 10^{-9}.ExamplesInput
2 20
25 100
Output
47.50000000000000000
Input
4 30
60 50 60 80
Output
171.25000000000000000
NoteIn the first example, the optimal strategy is to randomly get one of the two relics paying 20 shards. Then there are two scenarios. The first one happens if Gloria receives the first relic. Then she keeps getting random relics until she obtains the second relic. The expected number of shards to spend in this scenario is 20 + 30 = 50.In the second scenario, Gloria initially gets the second relic. Then it is better to buy the first relic for 25 shards, so the expected number of shards to spend in this scenario is 20 + 25 = 45.Thus, the expected number of shards to spend is \frac{50 + 45}{2} = 47.5. | 2 20
25 100
| 47.50000000000000000 | 3 seconds | 512 megabytes | ['math', 'probabilities', '*3000'] |
E. Electionstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputByteburg Senate elections are coming. Usually "United Byteland", the ruling Byteland party, takes all the seats in the Senate to ensure stability and sustainable development. But this year there is one opposition candidate in one of the constituencies. Even one opposition member can disturb the stability in the Senate, so the head of the Party asks you to ensure that the opposition candidate will not be elected.There are n candidates, numbered from 1 to n. Candidate n is the opposition candidate. There are m polling stations in the constituency, numbered from 1 to m. You know the number of votes cast for each candidate at each polling station. The only thing you can do to prevent the election of the opposition candidate is to cancel the election results at some polling stations. The opposition candidate will be elected if the sum of the votes cast in their favor at all non-canceled stations will be strictly greater than the analogous sum for every other candidate. Your task is to prevent the election of the opposition candidate by canceling the election results at the minimal possible number of polling stations. Notice that solution always exists, because if you cancel the elections at all polling stations, the number of votes for each candidate will be 0, and the opposition candidate will not be elected.InputThe first line of the input contains two integers n and m (2\le n\le 100; 1\le m \le 100) — the number of candidates and the number of polling stations. The next m lines contain the election results at each polling station with n numbers on each line. In the i-th line the j-th number is a_{i,j} — the number of votes cast for the candidate j at the station i (0\le a_{i,j} \le 1\,000).OutputIn the first line output integer k — the minimal number of the polling stations in which you need to cancel the election results. In the second line output k integers — the indices of canceled polling stations, in any order. If there are multiple ways to cancel results at k stations, output any one of them.ExamplesInput
5 3
6 3 4 2 8
3 7 5 6 7
5 2 4 7 9
Output
2
3 1
Input
2 1
1 1
Output
0
Input
3 3
2 3 8
4 2 9
3 1 7
Output
3
1 2 3
NoteIn the first example, the candidates from 1 to 5 received 14, 12, 13, 15, and 24 votes correspondingly. The opposition candidate has the most votes. However, if you cancel the election results at the first and the third polling stations, then only the result from the second polling station remains and the vote sums become 3, 7, 5, 6, and 7, without the opposition candidate being in the lead anymore. | 5 3
6 3 4 2 8
3 7 5 6 7
5 2 4 7 9
| 2 3 1 | 3 seconds | 512 megabytes | ['greedy', '*1700'] |
D. DevOps Best Practicestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDaisy is a senior software engineer at RainyDay, LLC. She has just implemented three new features in their product: the first feature makes their product work, the second one makes their product fast, and the third one makes their product correct. The company encourages at least some testing of new features, so Daisy appointed her intern Demid to write some tests for the new features.Interestingly enough, these three features pass all the tests on Demid's development server, which has index 1, but might fail the tests on some other servers.After Demid has completed this task, Daisy appointed you to deploy these three features to all n servers of your company. For every feature f and every server s, Daisy told you whether she wants the feature f to be deployed on the server s. If she wants it to be deployed, it must be done even if the feature f fails the tests on the server s. If she does not want it to be deployed, you may not deploy it there.Your company has two important instruments for the deployment of new features to servers: Continuous Deployment (CD) and Continuous Testing (CT). CD can be established between several pairs of servers, forming a directed graph. CT can be set up on some set of servers.If CD is configured from the server s_1 to the server s_2 then every time s_1 receives a new feature f the system starts the following deployment process of f to s_2: If the feature f is already deployed on the server s_2, then nothing is done. Otherwise, if CT is not set up on the server s_1, then the server s_1 just deploys the feature f to the server s_2 without any testing. Otherwise, the server s_1 runs tests for the feature f. If the tests fail on the server s_1, nothing is done. If the tests pass, then the server s_1 deploys the feature f to the server s_2. You are to configure the CD/CT system, and after that Demid will deploy all three features on his development server. Your CD/CT system must deploy each feature exactly to the set of servers that Daisy wants.Your company does not have a lot of computing resources, so you can establish CD from one server to another at most 264 times.InputThe first line contains integer n (2 \le n \le 256) — the number of servers in your company.Next n lines contain three integers each. The j-th integer in the i-th line is 1 if Daisy wants the j-th feature to be deployed to the i-th server, or 0 otherwise.Next n lines contain three integers each. The j-th integer in the i-th line is 1 if tests pass for the j-th feature on the i-th server, or 0 otherwise.Demid's development server has index 1. It is guaranteed that Daisy wants all three features to be deployed to the server number 1, and all three features pass their tests on the server number 1.OutputIf it is impossible to configure CD/CT system with CD being set up between at most 264 pairs of servers, then output the single line "Impossible".Otherwise, the first line of the output must contain the line "Possible".Next line must contain n space-separated integers — the configuration of CT. The i-th integer should be 1 if you set up CT on the i-th server, or 0 otherwise.Next line must contain the integer m (0 \le m \le 264) — the number of CD pairs you want to set up.Each of the next m lines must describe CD configuration, each line with two integers s_i and t_i (1 \le s_i, t_i \le n; s_i \ne t_i), establishing automated deployment of new features from the server s_i to the server t_i.ExamplesInput
3
1 1 1
1 0 1
1 1 1
1 1 1
0 0 0
1 0 1
Output
Possible
1 1 1
2
3 2
1 3
Input
2
1 1 1
0 0 1
1 1 1
1 1 0
Output
Impossible
NoteCD/CT system for the first sample test is shown below. | 3
1 1 1
1 0 1
1 1 1
1 1 1
0 0 0
1 0 1
| Possible 1 1 1 2 3 2 1 3 | 3 seconds | 512 megabytes | ['constructive algorithms', '*2800'] |
B. Balls of Bumatime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBalph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated. Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.InputThe only line contains a non-empty string of uppercase English letters of length at most 3 \cdot 10^5. Each letter represents a ball with the corresponding color.OutputOutput the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.ExamplesInput
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
| BBWWBB
| 3 | 3 seconds | 512 megabytes | ['*900'] |
H. Red-Blue Graphtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is a directed graph on n vertices numbered 1 through n where each vertex (except n) has two outgoing arcs, red and blue. At any point in time, exactly one of the arcs is active for each vertex. Initially, all blue arcs are active and there is a token located at vertex 1. In one second, the vertex with token first switches its active arcs — the inactive arc becomes active and vice versa. Then, the token is moved along the active arc. When the token reaches the vertex n, it stops. It is guaranteed that n is reachable via arcs from every vertex.You are given q queries. Each query contains a state of the graph — a pair (v, s) of the following form: v is the vertex where the token is currently located; s is a string consisting of n - 1 characters. The i-th character corresponds to the color of the active edge leading from the i-th vertex (the character is 'R' if red arc is active, otherwise the character is 'B'). For each query, determine whether the given state is reachable from the initial state and the first time this configuration appears. Note that the two operations (change active arc and traverse it) are atomic — a state is not considered reached if it appears after changing the active arc but before traversing it.InputThe first line contains a single integer n (2 \leq n \leq 58) — the number of vertices.n-1 lines follow, i-th of contains two space separated integers b_i and r_i (1 \leq b_i, r_i \leq n) representing a blue arc (i, b_i) and red arc (i, r_i), respectively. It is guaranteed that vertex n is reachable from every vertex.The next line contains a single integer q (1 \leq q \leq 5000) — the number of queries.Then q lines with queries follow. The j-th of these lines contains an integer v (1 \leq v < n) and a string s of length n-1 consiting only of characters 'R' and 'B'. The i-th of these characters is 'R' if the red arc going from i is active and 'B' otherwise.OutputOutput q lines, each containing answer to a single query.If the state in the i-th query is unreachable, output the integer -1. Otherwise, output t_i — the first time when the state appears (measured in seconds, starting from the initial state of the graph which appears in time 0).ExampleInput
6
2 1
5 5
2 1
6 3
4 3
21
1 BBBBB
1 RBBBB
2 BBBBB
5 BRBBB
3 BRBBR
1 BRRBR
1 RRRBR
2 BRRBR
5 BBRBR
4 BBRBB
3 BBRRB
2 BBBRB
5 BRBRB
3 BRBRR
1 BRRRR
1 RRRRR
2 BRRRR
5 BBRRR
4 BBRRB
2 BRBBB
4 BRBBR
Output
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-1
-1
NoteThe graph in the first example is depticed in the figure below.The first 19 queries denote the journey of the token. On the 19-th move the token would reach the vertex 6. The last two queries show states that are unreachable. | 6
2 1
5 5
2 1
6 3
4 3
21
1 BBBBB
1 RBBBB
2 BBBBB
5 BRBBB
3 BRBBR
1 BRRBR
1 RRRBR
2 BRRBR
5 BBRBR
4 BBRBB
3 BBRRB
2 BBBRB
5 BRBRB
3 BRBRR
1 BRRRR
1 RRRRR
2 BRRRR
5 BBRRR
4 BBRRB
2 BRBBB
4 BRBBR
| 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 -1 -1 | 4 seconds | 512 megabytes | ['dp', 'graphs', 'math', 'matrices', 'meet-in-the-middle', '*3400'] |
G. Permutation Concatenationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n \cdot n!.Let 1 \leq i \leq j \leq n \cdot n! be a pair of indices. We call the sequence (P_i, P_{i+1}, \dots, P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). InputThe only line contains one integer n (1 \leq n \leq 10^6), as described in the problem statement.OutputOutput a single integer — the number of distinct subarrays, modulo 998244353.ExamplesInput
2
Output
8
Input
10
Output
19210869
NoteIn the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1]. | 2
| 8 | 1 second | 256 megabytes | ['string suffix structures', '*3300'] |
F. Almost Same Distancetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet G be a simple graph. Let W be a non-empty subset of vertices. Then W is almost-k-uniform if for each pair of distinct vertices u,v \in W the distance between u and v is either k or k+1.You are given a tree on n vertices. For each i between 1 and n, find the maximum size of an almost-i-uniform set.InputThe first line contains a single integer n (2 \leq n \leq 5 \cdot 10^5) – the number of vertices of the tree.Then n-1 lines follows, the i-th of which consisting of two space separated integers u_i, v_i (1 \leq u_i, v_i \leq n) meaning that there is an edge between vertices u_i and v_i. It is guaranteed that the given graph is tree. OutputOutput a single line containing n space separated integers a_i, where a_i is the maximum size of an almost-i-uniform set.ExamplesInput
5
1 2
1 3
1 4
4 5
Output
4 3 2 1 1
Input
6
1 2
1 3
1 4
4 5
4 6
Output
4 4 2 1 1 1
NoteConsider the first example. The only maximum almost-1-uniform set is \{1, 2, 3, 4\}. One of the maximum almost-2-uniform sets is or \{2, 3, 5\}, another one is \{2, 3, 4\}. A maximum almost-3-uniform set is any pair of vertices on distance 3. Any single vertex is an almost-k-uniform set for k \geq 1. In the second sample there is an almost-2-uniform set of size 4, and that is \{2, 3, 5, 6\}. | 5
1 2
1 3
1 4
4 5
| 4 3 2 1 1 | 5 seconds | 256 megabytes | ['dfs and similar', 'graphs', '*2900'] |
E. Spaceship Solitairetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob is playing a game of Spaceship Solitaire. The goal of this game is to build a spaceship. In order to do this, he first needs to accumulate enough resources for the construction. There are n types of resources, numbered 1 through n. Bob needs at least a_i pieces of the i-th resource to build the spaceship. The number a_i is called the goal for resource i.Each resource takes 1 turn to produce and in each turn only one resource can be produced. However, there are certain milestones that speed up production. Every milestone is a triple (s_j, t_j, u_j), meaning that as soon as Bob has t_j units of the resource s_j, he receives one unit of the resource u_j for free, without him needing to spend a turn. It is possible that getting this free resource allows Bob to claim reward for another milestone. This way, he can obtain a large number of resources in a single turn.The game is constructed in such a way that there are never two milestones that have the same s_j and t_j, that is, the award for reaching t_j units of resource s_j is at most one additional resource.A bonus is never awarded for 0 of any resource, neither for reaching the goal a_i nor for going past the goal — formally, for every milestone 0 < t_j < a_{s_j}.A bonus for reaching certain amount of a resource can be the resource itself, that is, s_j = u_j.Initially there are no milestones. You are to process q updates, each of which adds, removes or modifies a milestone. After every update, output the minimum number of turns needed to finish the game, that is, to accumulate at least a_i of i-th resource for each i \in [1, n].InputThe first line contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the number of types of resources.The second line contains n space separated integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^9), the i-th of which is the goal for the i-th resource.The third line contains a single integer q (1 \leq q \leq 10^5) — the number of updates to the game milestones.Then q lines follow, the j-th of which contains three space separated integers s_j, t_j, u_j (1 \leq s_j \leq n, 1 \leq t_j < a_{s_j}, 0 \leq u_j \leq n). For each triple, perform the following actions: First, if there is already a milestone for obtaining t_j units of resource s_j, it is removed. If u_j = 0, no new milestone is added. If u_j \neq 0, add the following milestone: "For reaching t_j units of resource s_j, gain one free piece of u_j." Output the minimum number of turns needed to win the game. OutputOutput q lines, each consisting of a single integer, the i-th represents the answer after the i-th update.ExampleInput
2
2 3
5
2 1 1
2 2 1
1 1 1
2 1 2
2 2 0
Output
4
3
3
2
3
NoteAfter the first update, the optimal strategy is as follows. First produce 2 once, which gives a free resource 1. Then, produce 2 twice and 1 once, for a total of four turns.After the second update, the optimal strategy is to produce 2 three times — the first two times a single unit of resource 1 is also granted.After the third update, the game is won as follows. First produce 2 once. This gives a free unit of 1. This gives additional bonus of resource 1. After the first turn, the number of resources is thus [2, 1]. Next, produce resource 2 again, which gives another unit of 1. After this, produce one more unit of 2. The final count of resources is [3, 3], and three turns are needed to reach this situation. Notice that we have more of resource 1 than its goal, which is of no use. | 2
2 3
5
2 1 1
2 2 1
1 1 1
2 1 2
2 2 0
| 4 3 3 2 3 | 1 second | 256 megabytes | ['data structures', 'greedy', 'implementation', '*2100'] |
D. Decreasing Debtstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n people in this world, conveniently numbered 1 through n. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let d(a,b) denote the debt of a towards b, or 0 if there is no such debt.Sometimes, this becomes very complex, as the person lending money can run into financial troubles before his debtor is able to repay his debt, and finds himself in the need of borrowing money. When this process runs for a long enough time, it might happen that there are so many debts that they can be consolidated. There are two ways this can be done: Let d(a,b) > 0 and d(c,d) > 0 such that a \neq c or b \neq d. We can decrease the d(a,b) and d(c,d) by z and increase d(c,b) and d(a,d) by z, where 0 < z \leq \min(d(a,b),d(c,d)). Let d(a,a) > 0. We can set d(a,a) to 0. The total debt is defined as the sum of all debts:\Sigma_d = \sum_{a,b} d(a,b)Your goal is to use the above rules in any order any number of times, to make the total debt as small as possible. Note that you don't have to minimise the number of non-zero debts, only the total debt.InputThe first line contains two space separated integers n (1 \leq n \leq 10^5) and m (0 \leq m \leq 3\cdot 10^5), representing the number of people and the number of debts, respectively.m lines follow, each of which contains three space separated integers u_i, v_i (1 \leq u_i, v_i \leq n, u_i \neq v_i), d_i (1 \leq d_i \leq 10^9), meaning that the person u_i borrowed d_i burles from person v_i.OutputOn the first line print an integer m' (0 \leq m' \leq 3\cdot 10^5), representing the number of debts after the consolidation. It can be shown that an answer always exists with this additional constraint.After that print m' lines, i-th of which contains three space separated integers u_i, v_i, d_i, meaning that the person u_i owes the person v_i exactly d_i burles. The output must satisfy 1 \leq u_i, v_i \leq n, u_i \neq v_i and 0 < d_i \leq 10^{18}.For each pair i \neq j, it should hold that u_i \neq u_j or v_i \neq v_j. In other words, each pair of people can be included at most once in the output.ExamplesInput3 21 2 102 3 5Output21 2 51 3 5Input3 31 2 102 3 153 1 10Output12 3 5Input4 21 2 123 4 8Output21 2 123 4 8Input3 42 3 12 3 22 3 42 3 8Output12 3 15NoteIn the first example the optimal sequence of operations can be the following: Perform an operation of the first type with a = 1, b = 2, c = 2, d = 3 and z = 5. The resulting debts are: d(1, 2) = 5, d(2, 2) = 5, d(1, 3) = 5, all other debts are 0; Perform an operation of the second type with a = 2. The resulting debts are: d(1, 2) = 5, d(1, 3) = 5, all other debts are 0. In the second example the optimal sequence of operations can be the following: Perform an operation of the first type with a = 1, b = 2, c = 3, d = 1 and z = 10. The resulting debts are: d(3, 2) = 10, d(2, 3) = 15, d(1, 1) = 10, all other debts are 0; Perform an operation of the first type with a = 2, b = 3, c = 3, d = 2 and z = 10. The resulting debts are: d(2, 2) = 10, d(3, 3) = 10, d(2, 3) = 5, d(1, 1) = 10, all other debts are 0; Perform an operation of the second type with a = 2. The resulting debts are: d(3, 3) = 10, d(2, 3) = 5, d(1, 1) = 10, all other debts are 0; Perform an operation of the second type with a = 3. The resulting debts are: d(2, 3) = 5, d(1, 1) = 10, all other debts are 0; Perform an operation of the second type with a = 1. The resulting debts are: d(2, 3) = 5, all other debts are 0. | Input3 21 2 102 3 5 | Output21 2 51 3 5 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'graphs', 'greedy', 'implementation', 'math', 'two pointers', '*2000'] |
C. Diverse Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet a be a matrix of size r \times c containing positive integers, not necessarily distinct. Rows of the matrix are numbered from 1 to r, columns are numbered from 1 to c. We can construct an array b consisting of r + c integers as follows: for each i \in [1, r], let b_i be the greatest common divisor of integers in the i-th row, and for each j \in [1, c] let b_{r+j} be the greatest common divisor of integers in the j-th column. We call the matrix diverse if all r + c numbers b_k (k \in [1, r + c]) are pairwise distinct. The magnitude of a matrix equals to the maximum of b_k.For example, suppose we have the following matrix: \begin{pmatrix} 2 & 9 & 7\\ 4 & 144 & 84 \end{pmatrix} We construct the array b: b_1 is the greatest common divisor of 2, 9, and 7, that is 1; b_2 is the greatest common divisor of 4, 144, and 84, that is 4; b_3 is the greatest common divisor of 2 and 4, that is 2; b_4 is the greatest common divisor of 9 and 144, that is 9; b_5 is the greatest common divisor of 7 and 84, that is 7. So b = [1, 4, 2, 9, 7]. All values in this array are distinct, so the matrix is diverse. The magnitude is equal to 9.For a given r and c, find a diverse matrix that minimises the magnitude. If there are multiple solutions, you may output any of them. If there are no solutions, output a single integer 0. InputThe only line in the input contains two space separated integers r and c (1 \leq r,c \leq 500) — the number of rows and the number of columns of the matrix to be found.OutputIf there is no solution, output a single integer 0.Otherwise, output r rows. The i-th of them should contain c space-separated integers, the j-th of which is a_{i,j} — the positive integer in the i-th row and j-th column of a diverse matrix minimizing the magnitude.Furthermore, it must hold that 1 \leq a_{i,j} \leq 10^9. It can be shown that if a solution exists, there is also a solution with this additional constraint (still having minimum possible magnitude).ExamplesInput
2 2
Output
4 12
2 9Input
1 1
Output
0
NoteIn the first example, the GCDs of rows are b_1 = 4 and b_2 = 1, and the GCDs of columns are b_3 = 2 and b_4 = 3. All GCDs are pairwise distinct and the maximum of them is 4. Since the GCDs have to be distinct and at least 1, it is clear that there are no diverse matrices of size 2 \times 2 with magnitude smaller than 4.In the second example, no matter what a_{1,1} is, b_1 = b_2 will always hold, so there are no diverse matrices. | 2 2
| 4 12 2 9 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', 'number theory', '*1400'] |
B. Dice Towertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob is playing with 6-sided dice. A net of such standard cube is shown below.He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.For example, the number of visible pips on the tower below is 29 — the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5.The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of favourite integers of Bob. The second line contains t space-separated integers x_i (1 \leq x_i \leq 10^{18}) — Bob's favourite integers.OutputFor each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).ExampleInput
4
29 34 19 38
Output
YES
YES
YES
NO
NoteThe first example is mentioned in the problem statement.In the second example, one can build the tower by flipping the top dice from the previous tower.In the third example, one can use a single die that has 5 on top.The fourth example is impossible. | 4
29 34 19 38
| YES YES YES NO | 1 second | 256 megabytes | ['constructive algorithms', 'math', '*1000'] |
A. Competitive Programmertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked n of them how much effort they needed to reach red."Oh, I just spent x_i hours solving problems", said the i-th of them. Bob wants to train his math skills, so for each answer he wrote down the number of minutes (60 \cdot x_i), thanked the grandmasters and went home. Bob could write numbers with leading zeroes — for example, if some grandmaster answered that he had spent 2 hours, Bob could write 000120 instead of 120.Alice wanted to tease Bob and so she took the numbers Bob wrote down, and for each of them she did one of the following independently: rearranged its digits, or wrote a random number. This way, Alice generated n numbers, denoted y_1, ..., y_n.For each of the numbers, help Bob determine whether y_i can be a permutation of a number divisible by 60 (possibly with leading zeroes).InputThe first line contains a single integer n (1 \leq n \leq 418) — the number of grandmasters Bob asked.Then n lines follow, the i-th of which contains a single integer y_i — the number that Alice wrote down.Each of these numbers has between 2 and 100 digits '0' through '9'. They can contain leading zeroes.OutputOutput n lines.For each i, output the following. If it is possible to rearrange the digits of y_i such that the resulting number is divisible by 60, output "red" (quotes for clarity). Otherwise, output "cyan".ExampleInput
6
603
006
205
228
1053
0000000000000000000000000000000000000000000000
Output
red
red
cyan
cyan
cyan
red
NoteIn the first example, there is one rearrangement that yields a number divisible by 60, and that is 360.In the second example, there are two solutions. One is 060 and the second is 600.In the third example, there are 6 possible rearrangments: 025, 052, 205, 250, 502, 520. None of these numbers is divisible by 60.In the fourth example, there are 3 rearrangements: 228, 282, 822.In the fifth example, none of the 24 rearrangements result in a number divisible by 60.In the sixth example, note that 000\dots0 is a valid solution. | 6
603
006
205
228
1053
0000000000000000000000000000000000000000000000
| red red cyan cyan cyan red | 1 second | 256 megabytes | ['chinese remainder theorem', 'math', '*1000'] |
E. Beautiful Mirrorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCreatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability \frac{p_i}{100} for all 1 \le i \le n.Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the 1-st mirror again. You need to calculate the expected number of days until Creatnx becomes happy.This number should be found by modulo 998244353. Formally, let M = 998244353. 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}.InputThe first line contains one integer n (1\le n\le 2\cdot 10^5) — the number of mirrors.The second line contains n integers p_1, p_2, \ldots, p_n (1 \leq p_i \leq 100).OutputPrint the answer modulo 998244353 in a single line.ExamplesInput
1
50
Output
2
Input
3
10 20 50
Output
112
NoteIn the first test, there is only one mirror and it tells, that Creatnx is beautiful with probability \frac{1}{2}. So, the expected number of days until Creatnx becomes happy is 2. | 1
50
| 2 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'math', 'probabilities', '*2100'] |
B. Beautiful Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p=[p_1, p_2, \ldots, p_n] of integers from 1 to n. Let's call the number m (1 \le m \le n) beautiful, if there exists two indices l, r (1 \le l \le r \le n), such that the numbers [p_l, p_{l+1}, \ldots, p_r] is a permutation of numbers 1, 2, \ldots, m.For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: if l = 3 and r = 3 we will have a permutation [1] for m = 1; if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; it is impossible to take some l and r, such that [p_l, p_{l+1}, \ldots, p_r] is a permutation of numbers 1, 2, \ldots, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, \ldots, p_n]. For all m (1 \le m \le n) determine if it is a beautiful number or not.InputThe first line contains the only integer t (1 \le t \le 1000) — the number of test cases in the input. The next lines contain the description of test cases.The first line of a test case contains a number n (1 \le n \le 2 \cdot 10^5) — the length of the given permutation p. The next line contains n integers p_1, p_2, \ldots, p_n (1 \le p_i \le n, all p_i are different) — the given permutation p.It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 \cdot 10^5.OutputPrint t lines — the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number.ExampleInput
3
6
4 5 1 3 2 6
5
5 3 1 2 4
4
1 4 3 2
Output
101011
11111
1001
NoteThe first test case is described in the problem statement.In the second test case all numbers from 1 to 5 are beautiful: if l = 3 and r = 3 we will have a permutation [1] for m = 1; if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. | 3
6
4 5 1 3 2 6
5
5 3 1 2 4
4
1 4 3 2
| 101011 11111 1001 | 1 second | 256 megabytes | ['data structures', 'implementation', 'math', 'two pointers', '*1300'] |
A. Beautiful Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition s_i \neq s_{i+1} should be satisfied for all 1 \leq i \leq |s| - 1, where |s| is the length of the string s.InputThe first line contains positive integer t (1 \leq t \leq 1000) — the number of test cases. Next t lines contain the descriptions of test cases.Each line contains a non-empty string s consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string s has at least one character '?'. The sum of lengths of strings s in all test cases does not exceed 10^5.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them. ExampleInput
3
a???cb
a??bbc
a?b?c
Output
ababcb
-1
acbac
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the 4-th and 5-th characters will be always equal.In the third test case, the only answer is "acbac". | 3
a???cb
a??bbc
a?b?c
| ababcb -1 acbac | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*1000'] |
F. Beautiful Fibonacci Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe well-known Fibonacci sequence F_0, F_1, F_2,\ldots is defined as follows: F_0 = 0, F_1 = 1. For each i \geq 2: F_i = F_{i - 1} + F_{i - 2}. Given an increasing arithmetic sequence of positive integers with n elements: (a, a + d, a + 2\cdot d,\ldots, a + (n - 1)\cdot d).You need to find another increasing arithmetic sequence of positive integers with n elements (b, b + e, b + 2\cdot e,\ldots, b + (n - 1)\cdot e) such that: 0 < b, e < 2^{64}, for all 0\leq i < n, the decimal representation of a + i \cdot d appears as substring in the last 18 digits of the decimal representation of F_{b + i \cdot e} (if this number has less than 18 digits, then we consider all its digits). InputThe first line contains three positive integers n, a, d (1 \leq n, a, d, a + (n - 1) \cdot d < 10^6).OutputIf no such arithmetic sequence exists, print -1.Otherwise, print two integers b and e, separated by space in a single line (0 < b, e < 2^{64}).If there are many answers, you can output any of them.ExamplesInput
3 1 1
Output
2 1Input
5 1 2
Output
19 5
NoteIn the first test case, we can choose (b, e) = (2, 1), because F_2 = 1, F_3 = 2, F_4 = 3.In the second test case, we can choose (b, e) = (19, 5) because: F_{19} = 4181 contains 1; F_{24} = 46368 contains 3; F_{29} = 514229 contains 5; F_{34} = 5702887 contains 7; F_{39} = 63245986 contains 9. | 3 1 1
| 2 1 | 1 second | 256 megabytes | ['constructive algorithms', 'number theory', '*3500'] |
E. Beautiful Leaguetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA football league has recently begun in Beautiful land. There are n teams participating in the league. Let's enumerate them with integers from 1 to n.There will be played exactly \frac{n(n-1)}{2} matches: each team will play against all other teams exactly once. In each match, there is always a winner and loser and there is no draw.After all matches are played, the organizers will count the number of beautiful triples. Let's call a triple of three teams (A, B, C) beautiful if a team A win against a team B, a team B win against a team C and a team C win against a team A. We look only to a triples of different teams and the order of teams in the triple is important.The beauty of the league is the number of beautiful triples.At the moment, m matches were played and their results are known.What is the maximum beauty of the league that can be, after playing all remaining matches? Also find a possible results for all remaining \frac{n(n-1)}{2} - m matches, so that the league has this maximum beauty.InputThe first line contains two integers n, m (3 \leq n \leq 50, 0 \leq m \leq \frac{n(n-1)}{2}) — the number of teams in the football league and the number of matches that were played.Each of m following lines contains two integers u and v (1 \leq u, v \leq n, u \neq v) denoting that the u-th team won against the v-th team. It is guaranteed that each unordered pair of teams appears at most once.OutputPrint n lines, each line having a string of exactly n characters. Each character must be either 0 or 1.Let a_{ij} be the j-th number in the i-th line. For all 1 \leq i \leq n it should be true, that a_{ii} = 0. For all pairs of teams i \neq j the number a_{ij} indicates the result of the match between the i-th team and the j-th team: If a_{ij} is 1, the i-th team wins against the j-th team; Otherwise the j-th team wins against the i-th team; Also, it should be true, that a_{ij} + a_{ji} = 1. Also note that the results of the m matches that were already played cannot be changed in your league.The beauty of the league in the output should be maximum possible. If there are multiple possible answers with maximum beauty, you can print any of them.ExamplesInput
3 1
1 2
Output
010
001
100
Input
4 2
1 2
1 3
Output
0110
0001
0100
1010
NoteThe beauty of league in the first test case is equal to 3 because there exists three beautiful triples: (1, 2, 3), (2, 3, 1), (3, 1, 2).The beauty of league in the second test is equal to 6 because there exists six beautiful triples: (1, 2, 4), (2, 4, 1), (4, 1, 2), (2, 4, 3), (4, 3, 2), (3, 2, 4). | 3 1
1 2
| 010 001 100 | 1 second | 256 megabytes | ['constructive algorithms', 'flows', 'graph matchings', '*2700'] |
D2. Beautiful Bracket Sequence (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of this problem. The only difference is the limit of n - the length of the input string. In this version, 1 \leq n \leq 10^6.Let's define a correct bracket sequence and its depth as follow: An empty string is a correct bracket sequence with depth 0. If "s" is a correct bracket sequence with depth d then "(s)" is a correct bracket sequence with depth d + 1. If "s" and "t" are both correct bracket sequences then their concatenation "st" is a correct bracket sequence with depth equal to the maximum depth of s and t. For a (not necessarily correct) bracket sequence s, we define its depth as the maximum depth of any correct bracket sequence induced by removing some characters from s (possibly zero). For example: the bracket sequence s = "())(())" has depth 2, because by removing the third character we obtain a correct bracket sequence "()(())" with depth 2.Given a string a consists of only characters '(', ')' and '?'. Consider all (not necessarily correct) bracket sequences obtained by replacing all characters '?' in a by either '(' or ')'. Calculate the sum of all the depths of all these bracket sequences. As this number can be large, find it modulo 998244353.Hacks in this problem can be done only if easy and hard versions of this problem was solved.InputThe only line contains a non-empty string consist of only '(', ')' and '?'. The length of the string is at most 10^6.OutputPrint the answer modulo 998244353 in a single line.ExamplesInput
??
Output
1
Input
(?(?))
Output
9
NoteIn the first test case, we can obtain 4 bracket sequences by replacing all characters '?' with either '(' or ')': "((". Its depth is 0; "))". Its depth is 0; ")(". Its depth is 0; "()". Its depth is 1. So, the answer is 1 = 0 + 0 + 0 + 1.In the second test case, we can obtain 4 bracket sequences by replacing all characters '?' with either '(' or ')': "(((())". Its depth is 2; "()()))". Its depth is 2; "((()))". Its depth is 3; "()(())". Its depth is 2. So, the answer is 9 = 2 + 2 + 3 + 2. | ??
| 1 | 2 seconds | 256 megabytes | ['combinatorics', 'probabilities', '*2900'] |
D1. Beautiful Bracket Sequence (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of this problem. The only difference is the limit of n - the length of the input string. In this version, 1 \leq n \leq 2000. The hard version of this challenge is not offered in the round for the second division. Let's define a correct bracket sequence and its depth as follow: An empty string is a correct bracket sequence with depth 0. If "s" is a correct bracket sequence with depth d then "(s)" is a correct bracket sequence with depth d + 1. If "s" and "t" are both correct bracket sequences then their concatenation "st" is a correct bracket sequence with depth equal to the maximum depth of s and t. For a (not necessarily correct) bracket sequence s, we define its depth as the maximum depth of any correct bracket sequence induced by removing some characters from s (possibly zero). For example: the bracket sequence s = "())(())" has depth 2, because by removing the third character we obtain a correct bracket sequence "()(())" with depth 2.Given a string a consists of only characters '(', ')' and '?'. Consider all (not necessarily correct) bracket sequences obtained by replacing all characters '?' in a by either '(' or ')'. Calculate the sum of all the depths of all these bracket sequences. As this number can be large, find it modulo 998244353.Hacks in this problem in the first division can be done only if easy and hard versions of this problem was solved.InputThe only line contains a non-empty string consist of only '(', ')' and '?'. The length of the string is at most 2000.OutputPrint the answer modulo 998244353 in a single line.ExamplesInput
??
Output
1
Input
(?(?))
Output
9
NoteIn the first test case, we can obtain 4 bracket sequences by replacing all characters '?' with either '(' or ')': "((". Its depth is 0; "))". Its depth is 0; ")(". Its depth is 0; "()". Its depth is 1. So, the answer is 1 = 0 + 0 + 0 + 1.In the second test case, we can obtain 4 bracket sequences by replacing all characters '?' with either '(' or ')': "(((())". Its depth is 2; "()()))". Its depth is 2; "((()))". Its depth is 3; "()(())". Its depth is 2. So, the answer is 9 = 2 + 2 + 3 + 2. | ??
| 1 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'probabilities', '*2600'] |
C. Beautiful Mirrors with queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCreatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability \frac{p_i}{100} for all 1 \le i \le n.Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time.Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint.After each query, you need to calculate the expected number of days until Creatnx becomes happy.Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. 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}.InputThe first line contains two integers n, q (2 \leq n, q \le 2 \cdot 10^5) — the number of mirrors and queries.The second line contains n integers: p_1, p_2, \ldots, p_n (1 \leq p_i \leq 100).Each of q following lines contains a single integer u (2 \leq u \leq n) — next query.OutputPrint q numbers – the answers after each query by modulo 998244353.ExamplesInput
2 2
50 50
2
2
Output
4
6
Input
5 5
10 20 30 40 50
2
3
4
5
3
Output
117
665496274
332748143
831870317
499122211
NoteIn the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to \frac{1}{2}. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. | 2 2
50 50
2
2
| 4 6 | 2 seconds | 256 megabytes | ['data structures', 'probabilities', '*2400'] |
B. Beautiful Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn integer sequence is called beautiful if the difference between any two consecutive numbers is equal to 1. More formally, a sequence s_1, s_2, \ldots, s_{n} is beautiful if |s_i - s_{i+1}| = 1 for all 1 \leq i \leq n - 1.Trans has a numbers 0, b numbers 1, c numbers 2 and d numbers 3. He wants to construct a beautiful sequence using all of these a + b + c + d numbers.However, it turns out to be a non-trivial task, and Trans was not able to do it. Could you please help Trans?InputThe only input line contains four non-negative integers a, b, c and d (0 < a+b+c+d \leq 10^5).OutputIf it is impossible to construct a beautiful sequence satisfying the above constraints, print "NO" (without quotes) in one line.Otherwise, print "YES" (without quotes) in the first line. Then in the second line print a + b + c + d integers, separated by spaces — a beautiful sequence. There should be a numbers equal to 0, b numbers equal to 1, c numbers equal to 2 and d numbers equal to 3.If there are multiple answers, you can print any of them.ExamplesInput
2 2 2 1
Output
YES
0 1 0 1 2 3 2
Input
1 2 3 4
Output
NO
Input
2 2 2 3
Output
NO
NoteIn the first test, it is easy to see, that the sequence is beautiful because the difference between any two consecutive numbers is equal to 1. Also, there are exactly two numbers, equal to 0, 1, 2 and exactly one number, equal to 3.It can be proved, that it is impossible to construct beautiful sequences in the second and third tests. | 2 2 2 1
| YES 0 1 0 1 2 3 2 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', '*1900'] |
A. Beautiful Regional Contesttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSo the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 \ge p_2 \ge \dots \ge p_n.Help the jury distribute the gold, silver and bronze medals. Let their numbers be g, s and b, respectively. Here is a list of requirements from the rules, which all must be satisfied: for each of the three types of medals, at least one medal must be awarded (that is, g>0, s>0 and b>0); the number of gold medals must be strictly less than the number of silver and the number of bronze (that is, g<s and g<b, but there are no requirements between s and b); each gold medalist must solve strictly more problems than any awarded with a silver medal; each silver medalist must solve strictly more problems than any awarded a bronze medal; each bronze medalist must solve strictly more problems than any participant not awarded a medal; the total number of medalists g+s+b should not exceed half of all participants (for example, if n=21, then you can award a maximum of 10 participants, and if n=26, then you can award a maximum of 13 participants). The jury wants to reward with medals the total maximal number participants (i.e. to maximize g+s+b) so that all of the items listed above are fulfilled. Help the jury find such a way to award medals.InputThe first line of the input contains an integer t (1 \le t \le 10000) — the number of test cases in the input. Then t test cases follow.The first line of a test case contains an integer n (1 \le n \le 4\cdot10^5) — the number of BeRC participants. The second line of a test case contains integers p_1, p_2, \dots, p_n (0 \le p_i \le 10^6), where p_i is equal to the number of problems solved by the i-th participant from the final standings. The values p_i are sorted in non-increasing order, i.e. p_1 \ge p_2 \ge \dots \ge p_n.The sum of n over all test cases in the input does not exceed 4\cdot10^5.OutputPrint t lines, the j-th line should contain the answer to the j-th test case.The answer consists of three non-negative integers g, s, b. Print g=s=b=0 if there is no way to reward participants with medals so that all requirements from the statement are satisfied at the same time. Otherwise, print three positive numbers g, s, b — the possible number of gold, silver and bronze medals, respectively. The sum of g+s+b should be the maximum possible. If there are several answers, print any of them. ExampleInput
5
12
5 4 4 3 2 2 1 1 1 1 1 1
4
4 3 2 1
1
1000000
20
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
32
64 64 63 58 58 58 58 58 37 37 37 37 34 34 28 28 28 28 28 28 24 24 19 17 17 17 17 16 16 16 16 11
Output
1 2 3
0 0 0
0 0 0
2 5 3
2 6 6
NoteIn the first test case, it is possible to reward 1 gold, 2 silver and 3 bronze medals. In this case, the participant solved 5 tasks will be rewarded with the gold medal, participants solved 4 tasks will be rewarded with silver medals, participants solved 2 or 3 tasks will be rewarded with bronze medals. Participants solved exactly 1 task won't be rewarded. It's easy to see, that in this case, all conditions are satisfied and it is possible to reward participants in this way. It is impossible to give more than 6 medals because the number of medals should not exceed half of the number of participants. The answer 1, 3, 2 is also correct in this test case.In the second and third test cases, it is impossible to reward medals, because at least one medal of each type should be given, but the number of medals should not exceed half of the number of participants. | 5
12
5 4 4 3 2 2 1 1 1 1 1 1
4
4 3 2 1
1
1000000
20
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
32
64 64 63 58 58 58 58 58 37 37 37 37 34 34 28 28 28 28 28 28 24 24 19 17 17 17 17 16 16 16 16 11
| 1 2 3 0 0 0 0 0 0 2 5 3 2 6 6 | 2 seconds | 256 megabytes | ['greedy', 'implementation', '*1500'] |
F. Economic Difficultiestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea!Each grid (main and reserve) has a head node (its number is 1). Every other node gets electricity from the head node. Each node can be reached from the head node by a unique path. Also, both grids have exactly n nodes, which do not spread electricity further.In other words, every grid is a rooted directed tree on n leaves with a root in the node, which number is 1. Each tree has independent enumeration and nodes from one grid are not connected with nodes of another grid.Also, the palace has n electrical devices. Each device is connected with one node of the main grid and with one node of the reserve grid. Devices connect only with nodes, from which electricity is not spread further (these nodes are the tree's leaves). Each grid's leaf is connected with exactly one device. In this example the main grid contains 6 nodes (the top tree) and the reserve grid contains 4 nodes (the lower tree). There are 3 devices with numbers colored in blue. It is guaranteed that the whole grid (two grids and n devices) can be shown in this way (like in the picture above): main grid is a top tree, whose wires are directed 'from the top to the down', reserve grid is a lower tree, whose wires are directed 'from the down to the top', devices — horizontal row between two grids, which are numbered from 1 to n from the left to the right, wires between nodes do not intersect. Formally, for each tree exists a depth-first search from the node with number 1, that visits leaves in order of connection to devices 1, 2, \dots, n (firstly, the node, that is connected to the device 1, then the node, that is connected to the device 2, etc.).Businessman wants to sell (remove) maximal amount of wires so that each device will be powered from at least one grid (main or reserve). In other words, for each device should exist at least one path to the head node (in the main grid or the reserve grid), which contains only nodes from one grid.InputThe first line contains an integer n (1 \le n \le 1000) — the number of devices in the palace.The next line contains an integer a (1 + n \le a \le 1000 + n) — the amount of nodes in the main grid.Next line contains a - 1 integers p_i (1 \le p_i \le a). Each integer p_i means that the main grid contains a wire from p_i-th node to (i + 1)-th.The next line contains n integers x_i (1 \le x_i \le a) — the number of a node in the main grid that is connected to the i-th device.The next line contains an integer b (1 + n \le b \le 1000 + n) — the amount of nodes in the reserve grid.Next line contains b - 1 integers q_i (1 \le q_i \le b). Each integer q_i means that the reserve grid contains a wire from q_i-th node to (i + 1)-th.The next line contains n integers y_i (1 \le y_i \le b) — the number of a node in the reserve grid that is connected to the i-th device.It is guaranteed that each grid is a tree, which has exactly n leaves and each leaf is connected with one device. Also, it is guaranteed, that for each tree exists a depth-first search from the node 1, that visits leaves in order of connection to devices.OutputPrint a single integer — the maximal amount of wires that can be cut so that each device is powered.ExamplesInput
3
6
4 1 1 4 2
6 5 3
4
1 1 1
3 4 2
Output
5
Input
4
6
4 4 1 1 1
3 2 6 5
6
6 6 1 1 1
5 4 3 2
Output
6
Input
5
14
1 1 11 2 14 14 13 7 12 2 5 6 1
9 8 3 10 4
16
1 1 9 9 2 5 10 1 14 3 7 11 6 12 2
8 16 13 4 15
Output
17
NoteFor the first example, the picture below shows one of the possible solutions (wires that can be removed are marked in red): The second and the third examples can be seen below: | 3
6
4 1 1 4 2
6 5 3
4
1 1 1
3 4 2
| 5 | 3 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'dp', 'flows', 'graphs', 'trees', '*2400'] |
E. Editortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text.Your editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters). Thus, it points to an index character. The user can move the cursor left or right one position. If the cursor is already at the first (leftmost) position, then it does not move left.Initially, the cursor is in the first (leftmost) character.Also, the user can write a letter or brackets (either (, or )) to the position that the cursor is currently pointing at. A new character always overwrites the old value at that position.Your editor must check, whether the current line is the correct text. Text is correct if the brackets in them form the correct bracket sequence.Formally, correct text (CT) must satisfy the following rules: any line without brackets is CT (the line can contain whitespaces); If the first character of the string — is (, the last — is ), and all the rest form a CT, then the whole line is a CT; two consecutively written CT is also CT. Examples of correct texts: hello(codeforces), round, ((i)(write))edi(tor)s, ( me). Examples of incorrect texts: hello)oops(, round), ((me).The user uses special commands to work with your editor. Each command has its symbol, which must be written to execute this command.The correspondence of commands and characters is as follows: L — move the cursor one character to the left (remains in place if it already points to the first character); R — move the cursor one character to the right; any lowercase Latin letter or bracket (( or )) — write the entered character to the position where the cursor is now. For a complete understanding, take a look at the first example and its illustrations in the note below.You are given a string containing the characters that the user entered. For the brackets coloring module's work, after each command you need to: check if the current text in the editor is a correct text; if it is, print the least number of colors that required, to color all brackets. If two pairs of brackets are nested (the first in the second or vice versa), then these pairs of brackets should be painted in different colors. If two pairs of brackets are not nested, then they can be painted in different or the same colors. For example, for the bracket sequence ()(())()() the least number of colors is 2, and for the bracket sequence (()(()())())(()) — is 3.Write a program that prints the minimal number of colors after processing each command.InputThe first line contains an integer n (1 \le n \le 10^6) — the number of commands. The second line contains s — a sequence of commands. The string s consists of n characters. It is guaranteed that all characters in a string are valid commands.OutputIn a single line print n integers, where the i-th number is: -1 if the line received after processing the first i commands is not valid text, the minimal number of colors in the case of the correct text. ExamplesInput
11
(RaRbR)L)L(
Output
-1 -1 -1 -1 -1 -1 1 1 -1 -1 2 Input
11
(R)R(R)Ra)c
Output
-1 -1 1 1 -1 -1 1 1 1 -1 1 NoteIn the first example, the text in the editor will take the following form: (^ ( ^ (a ^ (a ^ (ab ^ (ab ^ (ab) ^ (ab) ^ (a)) ^ (a)) ^ (()) ^ | 11
(RaRbR)L)L(
| -1 -1 -1 -1 -1 -1 1 1 -1 -1 2 | 1 second | 256 megabytes | ['data structures', 'implementation', '*2100'] |
D. Secret Passwordstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: two passwords a and b are equivalent if there is a letter, that exists in both a and b; two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.InputThe first line contain integer n (1 \le n \le 2 \cdot 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal.It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters.OutputIn a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.ExamplesInput
4
a
b
ab
d
Output
2Input
3
ab
bc
abc
Output
1Input
1
codeforces
Output
1NoteIn the second example hacker need to use any of the passwords to access the system. | 4
a
b
ab
d
| 2 | 1 second | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', '*1500'] |
C. Everyone is a Winner!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the well-known testing system MathForces, a draw of n rating units is arranged. The rating will be distributed according to the following algorithm: if k participants take part in this event, then the n rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an unused rating may remain — it is not given to any of the participants.For example, if n = 5 and k = 3, then each participant will recieve an 1 rating unit, and also 2 rating units will remain unused. If n = 5, and k = 6, then none of the participants will increase their rating.Vasya participates in this rating draw but does not have information on the total number of participants in this event. Therefore, he wants to know what different values of the rating increment are possible to get as a result of this draw and asks you for help.For example, if n=5, then the answer is equal to the sequence 0, 1, 2, 5. Each of the sequence values (and only them) can be obtained as \lfloor n/k \rfloor for some positive integer k (where \lfloor x \rfloor is the value of x rounded down): 0 = \lfloor 5/7 \rfloor, 1 = \lfloor 5/5 \rfloor, 2 = \lfloor 5/2 \rfloor, 5 = \lfloor 5/1 \rfloor.Write a program that, for a given n, finds a sequence of all possible rating increments.InputThe first line contains integer number t (1 \le t \le 10) — the number of test cases in the input. Then t test cases follow.Each line contains an integer n (1 \le n \le 10^9) — the total number of the rating units being drawn.OutputOutput the answers for each of t test cases. Each answer should be contained in two lines.In the first line print a single integer m — the number of different rating increment values that Vasya can get.In the following line print m integers in ascending order — the values of possible rating increments.ExampleInput
4
5
11
1
3
Output
4
0 1 2 5
6
0 1 2 3 5 11
2
0 1
3
0 1 3
| 4
5
11
1
3
| 4 0 1 2 5 6 0 1 2 3 5 11 2 0 1 3 0 1 3 | 1 second | 256 megabytes | ['binary search', 'math', 'meet-in-the-middle', 'number theory', '*1400'] |
B. PIN Codestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA PIN code is a string that consists of exactly 4 digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0.Polycarp has n (2 \le n \le 10) bank cards, the PIN code of the i-th card is p_i.Polycarp has recently read a recommendation that it is better to set different PIN codes on different cards. Thus he wants to change the minimal number of digits in the PIN codes of his cards so that all n codes would become different.Formally, in one step, Polycarp picks i-th card (1 \le i \le n), then in its PIN code p_i selects one position (from 1 to 4), and changes the digit in this position to any other. He needs to change the minimum number of digits so that all PIN codes become different.Polycarp quickly solved this problem. Can you solve it?InputThe first line contains integer t (1 \le t \le 100) — the number of test cases in the input. Then test cases follow.The first line of each of t test sets contains a single integer n (2 \le n \le 10) — the number of Polycarp's bank cards. The next n lines contain the PIN codes p_1, p_2, \dots, p_n — one per line. The length of each of them is 4. All PIN codes consist of digits only.OutputPrint the answers to t test sets. The answer to each set should consist of a n + 1 linesIn the first line print k — the least number of changes to make all PIN codes different. In the next n lines output the changed PIN codes in the order corresponding to their appearance in the input. If there are several optimal answers, print any of them.ExampleInput
3
2
1234
0600
2
1337
1337
4
3139
3139
3139
3139
Output
0
1234
0600
1
1337
1237
3
3139
3138
3939
6139
| 3
2
1234
0600
2
1337
1337
4
3139
3139
3139
3139
| 0 1234 0600 1 1337 1237 3 3139 3138 3939 6139 | 1 second | 256 megabytes | ['greedy', 'implementation', '*1400'] |
A. Sweet Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are r candies in it, the second pile contains only green candies and there are g candies in it, the third pile contains only blue candies and there are b candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.InputThe first line contains integer t (1 \le t \le 1000) — the number of test cases in the input. Then t test cases follow.Each test case is given as a separate line of the input. It contains three integers r, g and b (1 \le r, g, b \le 10^8) — the number of red, green and blue candies, respectively.OutputPrint t integers: the i-th printed integer is the answer on the i-th test case in the input.ExampleInput
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten. | 6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
| 1 2 2 10 5 9 | 1 second | 256 megabytes | ['math', '*1100'] |
F. Xor-Settime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two sets of integers: A and B. You need to output the sum of elements in the set C = \{x | x = a \oplus b, a \in A, b \in B\} modulo 998244353, where \oplus denotes the bitwise XOR operation. Each number should be counted only once.For example, if A = \{2, 3\} and B = \{2, 3\} you should count integer 1 only once, despite the fact that you can get it as 3 \oplus 2 and as 2 \oplus 3. So the answer for this case is equal to 1 + 0 = 1.Let's call a segment [l; r] a set of integers \{l, l+1, \dots, r\}.The set A is given as a union of n_A segments, the set B is given as a union of n_B segments.InputThe first line contains a single integer n_A (1 \le n_A \le 100).The i-th of the next n_A lines contains two integers l_i and r_i (1 \le l_i \le r_i \le 10^{18}), describing a segment of values of set A.The next line contains a single integer n_B (1 \le n_B \le 100).The i-th of the next n_B lines contains two integers l_j and r_j (1 \le l_j \le r_j \le 10^{18}), describing a segment of values of set B.Note that segments in both sets may intersect.OutputPrint one integer — the sum of all elements in set C = \{x | x = a \oplus b, a \in A, b \in B\} modulo 998244353.ExamplesInput
2
3 5
5 8
3
1 2
1 9
2 9
Output
112
Input
1
1 9
2
2 4
2 10
Output
120
NoteIn the second example, we can discover that the set C = \{0,1,\dots,15\}, which means that all numbers between 0 and 15 can be represented as a \oplus b. | 2
3 5
5 8
3
1 2
1 9
2 9
| 112 | 2 seconds | 256 megabytes | ['bitmasks', 'divide and conquer', 'math', '*3100'] |
F. Colored Treetime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given a tree with n vertices. The color of the i-th vertex is h_{i}.The value of the tree is defined as \sum\limits_{h_{i} = h_{j}, 1 \le i < j \le n}{dis(i,j)}, where dis(i,j) is the number of edges on the shortest path between i and j. The color of each vertex is lost, you only remember that h_{i} can be any integer from [l_{i}, r_{i}](inclusive). You want to calculate the sum of values of all trees meeting these conditions modulo 10^9 + 7 (the set of edges is fixed, but each color is unknown, so there are \prod\limits_{i = 1}^{n} (r_{i} - l_{i} + 1) different trees).InputThe first line contains one integer n (2 \le n \le 10^5) — the number of vertices.Then n lines follow, each line contains two integers l_i and r_i (1 \le l_i \le r_i \le 10^5) denoting the range of possible colors of vertex i.Then n - 1 lines follow, each containing two integers u and v (1 \le u, v \le n, u \ne v) denoting an edge of the tree. It is guaranteed that these edges form a tree.OutputPrint one integer — the sum of values of all possible trees, taken modulo 10^9 + 7.ExampleInput
4
1 1
1 2
1 1
1 2
1 2
1 3
3 4
Output
22
NoteIn the first example there are four different ways to color the tree (so, there are four different trees): a tree with vertices colored as follows: \lbrace 1,1,1,1 \rbrace. The value of this tree is dis(1,2)+dis(1,3)+dis(1,4)+dis(2,3)+dis(2,4)+dis(3,4) = 10; a tree with vertices colored as follows: \lbrace 1,2,1,1 \rbrace. The value of this tree is dis(1,3)+dis(1,4)+dis(3,4)=4; a tree with vertices colored as follows: \lbrace 1,1,1,2 \rbrace. The value of this tree is dis(1,2)+dis(1,3)+dis(2,3)=4; a tree with vertices colored as follows: \lbrace 1,2,1,2 \rbrace. The value of this tree is dis(1,3)+dis(2,4)=4. Overall the sum of all values is 10+4+4+4=22. | 4
1 1
1 2
1 1
1 2
1 2
1 3
3 4
| 22 | 2.5 seconds | 256 megabytes | ['data structures', 'trees', '*2700'] |
E. Tournamenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j.The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and \frac{n}{2} winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner).Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower.Furthermore, during each stage you distribute the boxers into pairs as you wish.The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish?InputThe first line contains one integer n (2 \le n \le 2^{18}) — the number of boxers. n is a power of 2.The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 — it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9].OutputPrint one integer — the minimum number of dollars you have to pay so your friend wins.ExamplesInput
4
3 9 1 -1
Output
0Input
8
11 -1 13 19 24 7 17 5
Output
12NoteIn the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament.In the second test case you can distribute boxers as follows (your friend is number 2):1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage);2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6);2 : 8 (you have to bribe the boxer with strength 8); | 4
3 9 1 -1
| 0 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'greedy', '*2400'] |
D. A Game with Trapstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a computer game, where you lead a party of m soldiers. Each soldier is characterised by his agility a_i.The level you are trying to get through can be represented as a straight line segment from point 0 (where you and your squad is initially located) to point n + 1 (where the boss is located).The level is filled with k traps. Each trap is represented by three numbers l_i, r_i and d_i. l_i is the location of the trap, and d_i is the danger level of the trap: whenever a soldier with agility lower than d_i steps on a trap (that is, moves to the point l_i), he gets instantly killed. Fortunately, you can disarm traps: if you move to the point r_i, you disarm this trap, and it no longer poses any danger to your soldiers. Traps don't affect you, only your soldiers.You have t seconds to complete the level — that is, to bring some soldiers from your squad to the boss. Before the level starts, you choose which soldiers will be coming with you, and which soldiers won't be. After that, you have to bring all of the chosen soldiers to the boss. To do so, you may perform the following actions: if your location is x, you may move to x + 1 or x - 1. This action consumes one second; if your location is x and the location of your squad is x, you may move to x + 1 or to x - 1 with your squad in one second. You may not perform this action if it puts some soldier in danger (i. e. the point your squad is moving into contains a non-disarmed trap with d_i greater than agility of some soldier from the squad). This action consumes one second; if your location is x and there is a trap i with r_i = x, you may disarm this trap. This action is done instantly (it consumes no time). Note that after each action both your coordinate and the coordinate of your squad should be integers.You have to choose the maximum number of soldiers such that they all can be brought from the point 0 to the point n + 1 (where the boss waits) in no more than t seconds.InputThe first line contains four integers m, n, k and t (1 \le m, n, k, t \le 2 \cdot 10^5, n < t) — the number of soldiers, the number of integer points between the squad and the boss, the number of traps and the maximum number of seconds you may spend to bring the squad to the boss, respectively.The second line contains m integers a_1, a_2, ..., a_m (1 \le a_i \le 2 \cdot 10^5), where a_i is the agility of the i-th soldier.Then k lines follow, containing the descriptions of traps. Each line contains three numbers l_i, r_i and d_i (1 \le l_i \le r_i \le n, 1 \le d_i \le 2 \cdot 10^5) — the location of the trap, the location where the trap can be disarmed, and its danger level, respectively.OutputPrint one integer — the maximum number of soldiers you may choose so that you may bring them all to the boss in no more than t seconds.ExampleInput
5 6 4 14
1 2 3 4 5
1 5 2
1 2 5
2 3 5
3 5 3
Output
3
NoteIn the first example you may take soldiers with agility 3, 4 and 5 with you. The course of action is as follows: go to 2 without your squad; disarm the trap 2; go to 3 without your squad; disartm the trap 3; go to 0 without your squad; go to 7 with your squad. The whole plan can be executed in 13 seconds. | 5 6 4 14
1 2 3 4 5
1 5 2
1 2 5
2 3 5
3 5 3
| 3 | 3 seconds | 256 megabytes | ['binary search', 'dp', 'greedy', 'sortings', '*1900'] |
C. Infinite Fencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.You must paint a fence which consists of 10^{100} planks in two colors in the following way (suppose planks are numbered from left to right from 0): if the index of the plank is divisible by r (such planks have indices 0, r, 2r and so on) then you must paint it red; if the index of the plank is divisible by b (such planks have indices 0, b, 2b and so on) then you must paint it blue; if the index is divisible both by r and b you can choose the color to paint the plank; otherwise, you don't need to paint the plank at all (and it is forbidden to spent paint on it). Furthermore, the Government added one additional restriction to make your punishment worse. Let's list all painted planks of the fence in ascending order: if there are k consecutive planks with the same color in this list, then the Government will state that you failed the labor and execute you immediately. If you don't paint the fence according to the four aforementioned conditions, you will also be executed.The question is: will you be able to accomplish the labor (the time is not important) or the execution is unavoidable and you need to escape at all costs.InputThe first line contains single integer T (1 \le T \le 1000) — the number of test cases.The next T lines contain descriptions of test cases — one per line. Each test case contains three integers r, b, k (1 \le r, b \le 10^9, 2 \le k \le 10^9) — the corresponding coefficients.OutputPrint T words — one per line. For each test case print REBEL (case insensitive) if the execution is unavoidable or OBEY (case insensitive) otherwise.ExampleInput
4
1 1 2
2 10 4
5 2 3
3 2 2
Output
OBEY
REBEL
OBEY
OBEY
| 4
1 1 2
2 10 4
5 2 3
3 2 2
| OBEY REBEL OBEY OBEY | 2 seconds | 256 megabytes | ['greedy', 'math', 'number theory', '*1700'] |
B. Obtain Two Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers a and b. You may perform any number of operations on them (possibly zero).During each operation you should choose any positive integer x and set a := a - x, b := b - 2x or a := a - 2x, b := b - x. Note that you may choose different values of x in different operations.Is it possible to make a and b equal to 0 simultaneously?Your program should answer t independent test cases.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.Then the test cases follow, each test case is represented by one line containing two integers a and b for this test case (0 \le a, b \le 10^9).OutputFor each test case print the answer to it — YES if it is possible to make a and b equal to 0 simultaneously, and NO otherwise.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).ExampleInput
3
6 9
1 1
1 2
Output
YES
NO
YES
NoteIn the first test case of the example two operations can be used to make both a and b equal to zero: choose x = 4 and set a := a - x, b := b - 2x. Then a = 6 - 4 = 2, b = 9 - 8 = 1; choose x = 1 and set a := a - 2x, b := b - x. Then a = 2 - 2 = 0, b = 1 - 1 = 0. | 3
6 9
1 1
1 2
| YES NO YES | 1 second | 256 megabytes | ['binary search', 'math', '*1300'] |
A. Heatingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSeveral days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has n rooms. In the i-th room you can install at most c_i heating radiators. Each radiator can have several sections, but the cost of the radiator with k sections is equal to k^2 burles.Since rooms can have different sizes, you calculated that you need at least sum_i sections in total in the i-th room. For each room calculate the minimum cost to install at most c_i radiators with total number of sections not less than sum_i.InputThe first line contains single integer n (1 \le n \le 1000) — the number of rooms.Each of the next n lines contains the description of some room. The i-th line contains two integers c_i and sum_i (1 \le c_i, sum_i \le 10^4) — the maximum number of radiators and the minimum total number of sections in the i-th room, respectively.OutputFor each room print one integer — the minimum possible cost to install at most c_i radiators with total number of sections not less than sum_i.ExampleInput
4
1 10000
10000 1
2 6
4 6
Output
100000000
1
18
10
NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with sum_1 sections. The cost of the radiator is equal to (10^4)^2 = 10^8.In the second room, you can install up to 10^4 radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there 7 variants to install radiators: [6, 0], [5, 1], [4, 2], [3, 3], [2, 4], [1, 5], [0, 6]. The optimal variant is [3, 3] and it costs 3^2+ 3^2 = 18. | 4
1 10000
10000 1
2 6
4 6
| 100000000 1 18 10 | 1 second | 256 megabytes | ['math', '*1000'] |
G. Divisor Settime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an integer x represented as a product of n its prime divisors p_1 \cdot p_2, \cdot \ldots \cdot p_n. Let S be the set of all positive integer divisors of x (including 1 and x itself).We call a set of integers D good if (and only if) there is no pair a \in D, b \in D such that a \ne b and a divides b.Find a good subset of S with maximum possible size. Since the answer can be large, print the size of the subset modulo 998244353.InputThe first line contains the single integer n (1 \le n \le 2 \cdot 10^5) — the number of prime divisors in representation of x.The second line contains n integers p_1, p_2, \dots, p_n (2 \le p_i \le 3 \cdot 10^6) — the prime factorization of x.OutputPrint the maximum possible size of a good subset modulo 998244353.ExamplesInput
3
2999999 43 2999957
Output
3
Input
6
2 3 2 3 2 2
Output
3
NoteIn the first sample, x = 2999999 \cdot 43 \cdot 2999957 and one of the maximum good subsets is \{ 43, 2999957, 2999999 \}.In the second sample, x = 2 \cdot 3 \cdot 2 \cdot 3 \cdot 2 \cdot 2 = 144 and one of the maximum good subsets is \{ 9, 12, 16 \}. | 3
2999999 43 2999957
| 3 | 5 seconds | 512 megabytes | ['divide and conquer', 'fft', 'greedy', 'math', 'number theory', '*2600'] |
F. Make Them Similartime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputLet's call two numbers similar if their binary representations contain the same number of digits equal to 1. For example: 2 and 4 are similar (binary representations are 10 and 100); 1337 and 4213 are similar (binary representations are 10100111001 and 1000001110101); 3 and 2 are not similar (binary representations are 11 and 10); 42 and 13 are similar (binary representations are 101010 and 1101). You are given an array of n integers a_1, a_2, ..., a_n. You may choose a non-negative integer x, and then get another array of n integers b_1, b_2, ..., b_n, where b_i = a_i \oplus x (\oplus denotes bitwise XOR).Is it possible to obtain an array b where all numbers are similar to each other?InputThe first line contains one integer n (2 \le n \le 100).The second line contains n integers a_1, a_2, ..., a_n (0 \le a_i \le 2^{30} - 1).OutputIf it is impossible to choose x so that all elements in the resulting array are similar to each other, print one integer -1.Otherwise, print any non-negative integer not exceeding 2^{30} - 1 that can be used as x so that all elements in the resulting array are similar.ExamplesInput
2
7 2
Output
1
Input
4
3 17 6 0
Output
5
Input
3
1 2 3
Output
-1
Input
3
43 12 12
Output
1073709057
| 2
7 2
| 1 | 4 seconds | 1024 megabytes | ['bitmasks', 'brute force', 'hashing', 'meet-in-the-middle', '*2400'] |
E. The Contesttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order.The first contestant has received problems a_{1, 1}, a_{1, 2}, \dots, a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, \dots, a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, \dots, a_{3, k_3}).The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems.During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems?It is possible that after redistribution some participant (or even two of them) will not have any problems.InputThe first line contains three integers k_1, k_2 and k_3 (1 \le k_1, k_2, k_3 \le 2 \cdot 10^5, k_1 + k_2 + k_3 \le 2 \cdot 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively.The second line contains k_1 integers a_{1, 1}, a_{1, 2}, \dots, a_{1, k_1} — the problems initially taken by the first participant.The third line contains k_2 integers a_{2, 1}, a_{2, 2}, \dots, a_{2, k_2} — the problems initially taken by the second participant.The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, \dots, a_{3, k_3} — the problems initially taken by the third participant.It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 \le a_{i, j} \le n, where n = k_1 + k_2 + k_3.OutputPrint one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems.ExamplesInput
2 1 2
3 1
4
2 5
Output
1
Input
3 2 1
3 2 1
5 4
6
Output
0
Input
2 1 3
5 6
4
1 2 3
Output
3
Input
1 5 1
6
5 1 2 4 7
3
Output
2
NoteIn the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem.In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems.The best course of action in the third example is to give all problems to the third contestant.The best course of action in the fourth example is to give all problems to the second contestant. | 2 1 2
3 1
4
2 5
| 1 | 2 seconds | 512 megabytes | ['data structures', 'dp', 'greedy', '*2000'] |
D. Yet Another Monster Killing Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou play a computer game. In this game, you lead a party of m heroes, and you have to clear a dungeon with n monsters. Each monster is characterized by its power a_i. Each hero is characterized by his power p_i and endurance s_i.The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero (exactly one) who is going to enter the dungeon this day.When the hero enters the dungeon, he is challenged by the first monster which was not defeated during the previous days (so, if the heroes have already defeated k monsters, the hero fights with the monster k + 1). When the hero fights the monster, there are two possible outcomes: if the monster's power is strictly greater than the hero's power, the hero retreats from the dungeon. The current day ends; otherwise, the monster is defeated. After defeating a monster, the hero either continues fighting with the next monster or leaves the dungeon. He leaves the dungeon either if he has already defeated the number of monsters equal to his endurance during this day (so, the i-th hero cannot defeat more than s_i monsters during each day), or if all monsters are defeated — otherwise, he fights with the next monster. When the hero leaves the dungeon, the current day ends.Your goal is to defeat the last monster. What is the minimum number of days that you need to achieve your goal? Each day you have to use exactly one hero; it is possible that some heroes don't fight the monsters at all. Each hero can be used arbitrary number of times.InputThe first line contains one integer t (1 \le t \le 10^5) — the number of test cases. Then the test cases follow.The first line of each test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of monsters in the dungeon.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^9), where a_i is the power of the i-th monster.The third line contains one integer m (1 \le m \le 2 \cdot 10^5) — the number of heroes in your party.Then m lines follow, each describing a hero. Each line contains two integers p_i and s_i (1 \le p_i \le 10^9, 1 \le s_i \le n) — the power and the endurance of the i-th hero.It is guaranteed that the sum of n + m over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print one integer — the minimum number of days you have to spend to defeat all of the monsters (or -1 if it is impossible).ExampleInput
2
6
2 3 11 14 1 8
2
3 2
100 1
5
3 5 100 2 3
2
30 5
90 1
Output
5
-1
| 2
6
2 3 11 14 1 8
2
3 2
100 1
5
3 5 100 2 3
2
30 5
90 1
| 5 -1 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dp', 'greedy', 'sortings', 'two pointers', '*1700'] |
C. Dominated Subarraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call an array t dominated by value v in the next situation.At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.You are given array a_1, a_2, \dots, a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, \dots, a_j for some 1 \le i \le j \le n.InputThe first line contains single integer T (1 \le T \le 1000) — the number of test cases. Each test case consists of two lines.The first line contains single integer n (1 \le n \le 2 \cdot 10^5) — the length of the array a.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — the corresponding values of the array a.It's guaranteed that the total length of all arrays in one test doesn't exceed 2 \cdot 10^5.OutputPrint T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.ExampleInput
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
NoteIn the first test case, there are no subarrays of length at least 2, so the answer is -1.In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.In the fourth test case, all subarrays of length more than one are dominated. | 4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
| -1 6 3 2 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'sortings', 'strings', 'two pointers', '*1200'] |
B. Magic Sticktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Petya walked in the forest and found a magic stick.Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer: If the chosen number a is even, then the spell will turn it into \frac{3a}{2}; If the chosen number a is greater than one, then the spell will turn it into a-1. Note that if the number is even and greater than one, then Petya can choose which spell to apply.Petya now has only one number x. He wants to know if his favorite number y can be obtained from x using the spells he knows. The spells can be used any number of times in any order. It is not required to use spells, Petya can leave x as it is.InputThe first line contains single integer T (1 \le T \le 10^4) — the number of test cases. Each test case consists of two lines.The first line of each test case contains two integers x and y (1 \le x, y \le 10^9) — the current number and the number that Petya wants to get.OutputFor the i-th test case print the answer on it — YES if Petya can get the number y from the number x using known spells, and NO otherwise.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).ExampleInput
7
2 3
1 1
3 6
6 8
1 2
4 1
31235 6578234
Output
YES
YES
NO
YES
NO
YES
YES
| 7
2 3
1 1
3 6
6 8
1 2
4 1
31235 6578234
| YES YES NO YES NO YES YES | 1 second | 256 megabytes | ['math', '*1000'] |
A. Two Rival Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are the gym teacher in the school.There are n students in the row. And there are two rivalling students among them. The first one is in position a, the second in position b. Positions are numbered from 1 to n from left to right.Since they are rivals, you want to maximize the distance between them. If students are in positions p and s respectively, then distance between them is |p - s|. You can do the following operation at most x times: choose two adjacent (neighbouring) students and swap them.Calculate the maximum distance between two rivalling students after at most x swaps.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.The only line of each test case contains four integers n, x, a and b (2 \le n \le 100, 0 \le x \le 100, 1 \le a, b \le n, a \neq b) — the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.OutputFor each test case print one integer — the maximum distance between two rivaling students which you can obtain.ExampleInput
3
5 1 3 2
100 33 100 1
6 0 2 3
Output
2
99
1
NoteIn the first test case you can swap students in positions 3 and 4. And then the distance between the rivals is equal to |4 - 2| = 2.In the second test case you don't have to swap students. In the third test case you can't swap students. | 3
5 1 3 2
100 33 100 1
6 0 2 3
| 2 99 1 | 1 second | 256 megabytes | ['greedy', 'math', '*800'] |
F. Equalizing Two Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t both of length n and both consisting of lowercase Latin letters.In one move, you can choose any length len from 1 to n and perform the following operation: Choose any contiguous substring of the string s of length len and reverse it; at the same time choose any contiguous substring of the string t of length len and reverse it as well. Note that during one move you reverse exactly one substring of the string s and exactly one substring of the string t.Also note that borders of substrings you reverse in s and in t can be different, the only restriction is that you reverse the substrings of equal length. For example, if len=3 and n=5, you can reverse s[1 \dots 3] and t[3 \dots 5], s[2 \dots 4] and t[2 \dots 4], but not s[1 \dots 3] and t[1 \dots 2].Your task is to say if it is possible to make strings s and t equal after some (possibly, empty) sequence of moves.You have to answer q independent test cases.InputThe first line of the input contains one integer q (1 \le q \le 10^4) — the number of test cases. Then q test cases follow.The first line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the length of s and t.The second line of the test case contains one string s consisting of n lowercase Latin letters.The third line of the test case contains one string t consisting of n lowercase Latin letters.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to make strings s and t equal after some (possibly, empty) sequence of moves and "NO" otherwise.ExampleInput
4
4
abcd
abdc
5
ababa
baaba
4
asdf
asdg
4
abcd
badc
Output
NO
YES
NO
YES
| 4
4
abcd
abdc
5
ababa
baaba
4
asdf
asdg
4
abcd
badc
| NO YES NO YES | 1 second | 256 megabytes | ['constructive algorithms', 'sortings', 'strings', '*2000'] |
E. Yet Another Division Into Teamstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students at your university. The programming skill of the i-th student is a_i. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has 2 \cdot 10^5 students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of k students with programming skills a[i_1], a[i_2], \dots, a[i_k], then the diversity of this team is \max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students.InputThe first line of the input contains one integer n (3 \le n \le 2 \cdot 10^5) — the number of students.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the programming skill of the i-th student.OutputIn the first line print two integers res and k — the minimum total diversity of the division of students and the number of teams in your division, correspondingly.In the second line print n integers t_1, t_2, \dots, t_n (1 \le t_i \le k), where t_i is the number of team to which the i-th student belong.If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students.ExamplesInput
5
1 1 3 4 2
Output
3 1
1 1 1 1 1
Input
6
1 5 12 13 2 15
Output
7 2
2 2 1 1 2 1
Input
10
1 2 5 129 185 581 1041 1909 1580 8150
Output
7486 3
3 3 3 2 2 2 2 1 1 1
NoteIn the first example, there is only one team with skills [1, 1, 2, 3, 4] so the answer is 3. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills [1, 2, 5] and [12, 13, 15] so the answer is 4 + 3 = 7.In the third example, there are three teams with skills [1, 2, 5], [129, 185, 581, 1041] and [1580, 1909, 8150] so the answer is 4 + 912 + 6570 = 7486. | 5
1 1 3 4 2
| 3 1 1 1 1 1 1 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'sortings', '*2000'] |
D. Binary String Minimizingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string of length n (i. e. a string consisting of n characters '0' and '1').In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do not perform any moves at all.Note that you can swap the same pair of adjacent characters with indices i and i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.You have to answer q independent test cases.InputThe first line of the input contains one integer q (1 \le q \le 10^4) — the number of test cases.The first line of the test case contains two integers n and k (1 \le n \le 10^6, 1 \le k \le n^2) — the length of the string and the number of moves you can perform.The second line of the test case contains one string consisting of n characters '0' and '1'.It is guaranteed that the sum of n over all test cases does not exceed 10^6 (\sum n \le 10^6).OutputFor each test case, print the answer on it: the lexicographically minimum possible string of length n you can obtain from the given one if you can perform no more than k moves.ExampleInput
3
8 5
11011010
7 9
1111100
7 11
1111100
Output
01011110
0101111
0011111
NoteIn the first example, you can change the string as follows: 1\underline{10}11010 \rightarrow \underline{10}111010 \rightarrow 0111\underline{10}10 \rightarrow 011\underline{10}110 \rightarrow 01\underline{10}1110 \rightarrow 01011110. In the third example, there are enough operations to make the string sorted. | 3
8 5
11011010
7 9
1111100
7 11
1111100
| 01011110 0101111 0011111 | 1 second | 256 megabytes | ['greedy', '*1500'] |
C. Platforms Jumpingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a river of width n. The left bank of the river is cell 0 and the right bank is cell n + 1 (more formally, the river can be represented as a sequence of n + 2 cells numbered from 0 to n + 1). There are also m wooden platforms on a river, the i-th platform has length c_i (so the i-th platform takes c_i consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed n.You are standing at 0 and want to reach n+1 somehow. If you are standing at the position x, you can jump to any position in the range [x + 1; x + d]. However you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if d=1, you can jump only to the next position (if it belongs to the wooden platform). You can assume that cells 0 and n+1 belong to wooden platforms.You want to know if it is possible to reach n+1 from 0 if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms.Note that you should move platforms until you start jumping (in other words, you first move the platforms and then start jumping).For example, if n=7, m=3, d=2 and c = [1, 2, 1], then one of the ways to reach 8 from 0 is follow: The first example: n=7. InputThe first line of the input contains three integers n, m and d (1 \le n, m, d \le 1000, m \le n) — the width of the river, the number of platforms and the maximum distance of your jump, correspondingly.The second line of the input contains m integers c_1, c_2, \dots, c_m (1 \le c_i \le n, \sum\limits_{i=1}^{m} c_i \le n), where c_i is the length of the i-th platform.OutputIf it is impossible to reach n+1 from 0, print NO in the first line. Otherwise, print YES in the first line and the array a of length n in the second line — the sequence of river cells (excluding cell 0 and cell n + 1).If the cell i does not belong to any platform, a_i should be 0. Otherwise, it should be equal to the index of the platform (1-indexed, platforms are numbered from 1 to m in order of input) to which the cell i belongs.Note that all a_i equal to 1 should form a contiguous subsegment of the array a of length c_1, all a_i equal to 2 should form a contiguous subsegment of the array a of length c_2, ..., all a_i equal to m should form a contiguous subsegment of the array a of length c_m. The leftmost position of 2 in a should be greater than the rightmost position of 1, the leftmost position of 3 in a should be greater than the rightmost position of 2, ..., the leftmost position of m in a should be greater than the rightmost position of m-1.See example outputs for better understanding.ExamplesInput
7 3 2
1 2 1
Output
YES
0 1 0 2 2 0 3
Input
10 1 11
1
Output
YES
0 0 0 0 0 0 0 0 0 1
Input
10 1 5
2
Output
YES
0 0 0 0 1 1 0 0 0 0
NoteConsider the first example: the answer is [0, 1, 0, 2, 2, 0, 3]. The sequence of jumps you perform is 0 \rightarrow 2 \rightarrow 4 \rightarrow 5 \rightarrow 7 \rightarrow 8.Consider the second example: it does not matter how to place the platform because you always can jump from 0 to 11.Consider the third example: the answer is [0, 0, 0, 0, 1, 1, 0, 0, 0, 0]. The sequence of jumps you perform is 0 \rightarrow 5 \rightarrow 6 \rightarrow 11. | 7 3 2
1 2 1
| YES 0 1 0 2 2 0 3 | 1 second | 256 megabytes | ['greedy', '*1700'] |
B. Minimize the Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation of length n. Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (n=3 but there is 4 in the array).You can perform at most n-1 operations with the given permutation (it is possible that you don't perform any operations at all). The i-th operation allows you to swap elements of the given permutation on positions i and i+1. Each operation can be performed at most once. The operations can be performed in arbitrary order.Your task is to find the lexicographically minimum possible permutation obtained by performing some of the given operations in some order.You can see the definition of the lexicographical order in the notes section.You have to answer q independent test cases.For example, let's consider the permutation [5, 4, 1, 3, 2]. The minimum possible permutation we can obtain is [1, 5, 2, 4, 3] and we can do it in the following way: perform the second operation (swap the second and the third elements) and obtain the permutation [5, 1, 4, 3, 2]; perform the fourth operation (swap the fourth and the fifth elements) and obtain the permutation [5, 1, 4, 2, 3]; perform the third operation (swap the third and the fourth elements) and obtain the permutation [5, 1, 2, 4, 3]. perform the first operation (swap the first and the second elements) and obtain the permutation [1, 5, 2, 4, 3]; Another example is [1, 2, 4, 3]. The minimum possible permutation we can obtain is [1, 2, 3, 4] by performing the third operation (swap the third and the fourth elements).InputThe first line of the input contains one integer q (1 \le q \le 100) — the number of test cases. Then q test cases follow.The first line of the test case contains one integer n (1 \le n \le 100) — the number of elements in the permutation.The second line of the test case contains n distinct integers from 1 to n — the given permutation.OutputFor each test case, print the answer on it — the lexicograhically minimum possible permutation obtained by performing some of the given operations in some order.ExampleInput
4
5
5 4 1 3 2
4
1 2 4 3
1
1
4
4 3 2 1
Output
1 5 2 4 3
1 2 3 4
1
1 4 3 2
NoteRecall that the permutation p of length n is lexicographically less than the permutation q of length n if there is such index i \le n that for all j from 1 to i - 1 the condition p_j = q_j is satisfied, and p_i < q_i. For example: p = [1, 3, 5, 2, 4] is less than q = [1, 3, 5, 4, 2] (such i=4 exists, that p_i < q_i and for each j < i holds p_j = q_j), p = [1, 2] is less than q = [2, 1] (such i=1 exists, that p_i < q_i and for each j < i holds p_j = q_j). | 4
5
5 4 1 3 2
4
1 2 4 3
1
1
4
4 3 2 1
| 1 5 2 4 3 1 2 3 4 1 1 4 3 2 | 1 second | 256 megabytes | ['greedy', '*1400'] |
A. Payment Without Changetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 \le x \le a) coins of value n and y (0 \le y \le b) coins of value 1, then the total value of taken coins will be S.You have to answer q independent test cases.InputThe first line of the input contains one integer q (1 \le q \le 10^4) — the number of test cases. Then q test cases follow.The only line of the test case contains four integers a, b, n and S (1 \le a, b, n, S \le 10^9) — the number of coins of value n, the number of coins of value 1, the value n and the required total value.OutputFor the i-th test case print the answer on it — YES (without quotes) if there exist such x and y that if you take x coins of value n and y coins of value 1, then the total value of taken coins will be S, and NO otherwise.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).ExampleInput
4
1 2 3 4
1 2 3 6
5 2 6 27
3 3 5 18
Output
YES
NO
NO
YES
| 4
1 2 3 4
1 2 3 6
5 2 6 27
3 3 5 18
| YES NO NO YES | 1 second | 256 megabytes | ['math', '*1000'] |
C. League of Leesinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n \ge 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 \le p_i \le n, all p_i are unique). In other words, p is a permutation of 1, 2, \dots, n.As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 \le i \le n-2. Bob was very proud of his array, so he showed it to his friend Alice.After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond.For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples.As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. InputThe first line contains a single integer n (5 \le n \le 10^5) — the size of permutation p.The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 \le q_{i, j} \le n) — the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged.It is guaranteed that there is at least one permutation p that is consistent with the input. OutputPrint n distinct integers p_1, p_2, \ldots, p_n (1 \le p_i \le n) such that p is consistent with array q. If there are multiple answers, print any. ExampleInput
5
4 3 2
2 3 5
4 1 2
Output
1 4 2 3 5
| 5
4 3 2
2 3 5
4 1 2
| 1 4 2 3 5 | 2 seconds | 256 megabytes | ['constructive algorithms', 'implementation', '*1600'] |
B. Fridge Lockerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHanh lives in a shared apartment. There are n people (including Hanh) living there, each has a private fridge. n fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridge can be open only if all chains connected to it are unlocked. For example, if a fridge has no chains connected to it at all, then any of n people can open it. For exampe, in the picture there are n=4 people and 5 chains. The first person knows passcodes of two chains: 1-4 and 1-2. The fridge 1 can be open by its owner (the person 1), also two people 2 and 4 (acting together) can open it. The weights of these fridges are a_1, a_2, \ldots, a_n. To make a steel chain connecting fridges u and v, you have to pay a_u + a_v dollars. Note that the landlord allows you to create multiple chains connecting the same pair of fridges. Hanh's apartment landlord asks you to create exactly m steel chains so that all fridges are private. A fridge is private if and only if, among n people living in the apartment, only the owner can open it (i.e. no other person acting alone can do it). In other words, the fridge i is not private if there exists the person j (i \ne j) that the person j can open the fridge i.For example, in the picture all the fridges are private. On the other hand, if there are n=2 fridges and only one chain (which connects them) then both fridges are not private (both fridges can be open not only by its owner but also by another person).Of course, the landlord wants to minimize the total cost of all steel chains to fulfill his request. Determine whether there exists any way to make exactly m chains, and if yes, output any solution that minimizes the total cost. InputEach test contains multiple test cases. The first line contains the number of test cases T (1 \le T \le 10). Then the descriptions of the test cases follow.The first line of each test case contains two integers n, m (2 \le n \le 1000, 1 \le m \le n) — the number of people living in Hanh's apartment and the number of steel chains that the landlord requires, respectively.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^4) — weights of all fridges.OutputFor each test case: If there is no solution, print a single integer -1. Otherwise, print a single integer c — the minimum total cost. The i-th of the next m lines contains two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \ne v_i), meaning that the i-th steel chain connects fridges u_i and v_i. An arbitrary number of chains can be between a pair of fridges. If there are multiple answers, print any.ExampleInput
3
4 4
1 1 1 1
3 1
1 2 3
3 3
1 2 3
Output
8
1 2
4 3
3 2
4 1
-1
12
3 2
1 2
3 1 | 3
4 4
1 1 1 1
3 1
1 2 3
3 3
1 2 3
| 8 1 2 4 3 3 2 4 1 -1 12 3 2 1 2 3 1 | 1 second | 256 megabytes | ['graphs', 'implementation', '*1100'] |
A. Changing Volumetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob watches TV every day. He always sets the volume of his TV to b. However, today he is angry to find out someone has changed the volume to a. Of course, Bob has a remote control that can change the volume.There are six buttons (-5, -2, -1, +1, +2, +5) on the control, which in one press can either increase or decrease the current volume by 1, 2, or 5. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than 0.As Bob is so angry, he wants to change the volume to b using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given a and b, finds the minimum number of presses to change the TV volume from a to b.InputEach test contains multiple test cases. The first line contains the number of test cases T (1 \le T \le 1\,000). Then the descriptions of the test cases follow.Each test case consists of one line containing two integers a and b (0 \le a, b \le 10^{9}) — the current volume and Bob's desired volume, respectively.OutputFor each test case, output a single integer — the minimum number of presses to change the TV volume from a to b. If Bob does not need to change the volume (i.e. a=b), then print 0.ExampleInput
3
4 0
5 14
3 9
Output
2
3
2
NoteIn the first example, Bob can press the -2 button twice to reach 0. Note that Bob can not press -5 when the volume is 4 since it will make the volume negative. In the second example, one of the optimal ways for Bob is to press the +5 twice, then press -1 once.In the last example, Bob can press the +5 once, then press +1. | 3
4 0
5 14
3 9
| 2 3 2 | 1 second | 256 megabytes | ['math', '*800'] |
E. Send Tree to Charlietime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputChristmas was knocking on the door, and our protagonist, Bob, was preparing a spectacular present for his long-time second best friend Charlie. As chocolate boxes are lame, he decided to decorate a tree instead. Bob's tree can be represented as an undirected connected graph with n nodes (numbered 1 to n) and n-1 edges. Initially, Bob placed a decoration with label i on node i, for each 1 \le i \le n. However, as such a simple arrangement is lame, he decided to shuffle the decorations a bit. Formally, Bob did the following steps: First, he listed the n-1 edges in some order. Then, he considered the edges one by one in that order. For each edge (u, v), he swapped the decorations of node u with the one of node v.After finishing, Bob seemed satisfied with the arrangement, so he went to sleep.The next morning, Bob wakes up only to find out that his beautiful arrangement has been ruined! Last night, Bob's younger brother Bobo dropped some of the decorations on the floor while he was playing with the tree. Fortunately, no decorations were lost, so Bob can repair the tree in no time. However, he completely forgets how the tree looked like yesterday. Therefore, given the labels of the decorations still on the tree, Bob wants to know the number of possible configurations of the tree. As the result can be quite large, Bob will be happy if you can output the result modulo 1000000007 (10^9+7). Note that, it is possible that there exists no possible configurations.InputThe first line contains a single integer n (2 \leq n \leq 500\,000) — the number of nodes.Each of the next n - 1 lines contains two integers u and v (1 \leq u, v \leq n), denoting that there is an edge connecting two nodes u and v. It is guaranteed that the given edges form a tree.The last line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le n). For each i, a_i = 0 means that the decoration of node i has been dropped on the floor. Otherwise, a_i is the label of the decoration of node i. It is guaranteed that no label appears more than once.OutputOutput the number of possible configurations modulo 1000000007 (10^9+7).ExamplesInput
4
3 4
2 4
4 1
0 4 0 0
Output
2
Input
5
1 2
2 4
3 4
5 4
0 0 0 0 0
Output
12
Input
3
1 2
1 3
1 0 0
Output
0
NoteIn the first example, the possible configurations of the tree are [2, 4, 1, 3] and [3, 4, 2, 1].In the second example, note that while there are 4! = 24 possible permutations of the edges, each of them results in a possible configuration, there are only 12 different configurations.In the third example, it is easy to see that the decoration 1 cannot stay at node 1 after the swaps. | 4
3 4
2 4
4 1
0 4 0 0
| 2 | 4 seconds | 512 megabytes | ['combinatorics', 'dfs and similar', 'dsu', 'trees', '*3300'] |
D. Tree Queriestime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputHanh is a famous biologist. He loves growing trees and doing experiments on his own garden.One day, he got a tree consisting of n vertices. Vertices are numbered from 1 to n. A tree with n vertices is an undirected connected graph with n-1 edges. Initially, Hanh sets the value of every vertex to 0.Now, Hanh performs q operations, each is either of the following types: Type 1: Hanh selects a vertex v and an integer d. Then he chooses some vertex r uniformly at random, lists all vertices u such that the path from r to u passes through v. Hanh then increases the value of all such vertices u by d. Type 2: Hanh selects a vertex v and calculates the expected value of v. Since Hanh is good at biology but not math, he needs your help on these operations.InputThe first line contains two integers n and q (1 \leq n, q \leq 150\,000) — the number of vertices on Hanh's tree and the number of operations he performs.Each of the next n - 1 lines contains two integers u and v (1 \leq u, v \leq n), denoting that there is an edge connecting two vertices u and v. It is guaranteed that these n - 1 edges form a tree.Each of the last q lines describes an operation in either formats: 1 v d (1 \leq v \leq n, 0 \leq d \leq 10^7), representing a first-type operation. 2 v (1 \leq v \leq n), representing a second-type operation. It is guaranteed that there is at least one query of the second type.OutputFor each operation of the second type, write the expected value on a single line. Let M = 998244353, it can be shown that the expected value 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
5 12
1 2
1 3
2 4
2 5
1 1 1
2 1
2 2
2 3
2 4
2 5
1 2 2
2 1
2 2
2 3
2 4
2 5
Output
1
199648871
399297742
199648871
199648871
598946614
199648873
2
2
2
NoteThe image below shows the tree in the example: For the first query, where v = 1 and d = 1: If r = 1, the values of all vertices get increased. If r = 2, the values of vertices 1 and 3 get increased. If r = 3, the values of vertices 1, 2, 4 and 5 get increased. If r = 4, the values of vertices 1 and 3 get increased. If r = 5, the values of vertices 1 and 3 get increased. Hence, the expected values of all vertices after this query are (1, 0.4, 0.8, 0.4, 0.4).For the second query, where v = 2 and d = 2: If r = 1, the values of vertices 2, 4 and 5 get increased. If r = 2, the values of all vertices get increased. If r = 3, the values of vertices 2, 4 and 5 get increased. If r = 4, the values of vertices 1, 2, 3 and 5 get increased. If r = 5, the values of vertices 1, 2, 3 and 4 get increased. Hence, the expected values of all vertices after this query are (2.2, 2.4, 2, 2, 2). | 5 12
1 2
1 3
2 4
2 5
1 1 1
2 1
2 2
2 3
2 4
2 5
1 2 2
2 1
2 2
2 3
2 4
2 5
| 1 199648871 399297742 199648871 199648871 598946614 199648873 2 2 2 | 5 seconds | 512 megabytes | ['data structures', 'probabilities', 'trees', '*2700'] |
C. Point Orderingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Khanh has n points on the Cartesian plane, denoted by a_1, a_2, \ldots, a_n. All points' coordinates are integers between -10^9 and 10^9, inclusive. No three points are collinear. He says that these points are vertices of a convex polygon; in other words, there exists a permutation p_1, p_2, \ldots, p_n of integers from 1 to n such that the polygon a_{p_1} a_{p_2} \ldots a_{p_n} is convex and vertices are listed in counter-clockwise order.Khanh gives you the number n, but hides the coordinates of his points. Your task is to guess the above permutation by asking multiple queries. In each query, you give Khanh 4 integers t, i, j, k; where either t = 1 or t = 2; and i, j, k are three distinct indices from 1 to n, inclusive. In response, Khanh tells you: if t = 1, the area of the triangle a_ia_ja_k multiplied by 2. if t = 2, the sign of the cross product of two vectors \overrightarrow{a_ia_j} and \overrightarrow{a_ia_k}. Recall that the cross product of vector \overrightarrow{a} = (x_a, y_a) and vector \overrightarrow{b} = (x_b, y_b) is the integer x_a \cdot y_b - x_b \cdot y_a. The sign of a number is 1 it it is positive, and -1 otherwise. It can be proven that the cross product obtained in the above queries can not be 0.You can ask at most 3 \cdot n queries.Please note that Khanh fixes the coordinates of his points and does not change it while answering your queries. You do not need to guess the coordinates. In your permutation a_{p_1}a_{p_2}\ldots a_{p_n}, p_1 should be equal to 1 and the indices of vertices should be listed in counter-clockwise order.InteractionYou start the interaction by reading n (3 \leq n \leq 1\,000) — the number of vertices.To ask a query, write 4 integers t, i, j, k (1 \leq t \leq 2, 1 \leq i, j, k \leq n) in a separate line. i, j and k should be distinct.Then read a single integer to get the answer to this query, as explained above. It can be proven that the answer of a query is always an integer.When you find the permutation, write a number 0. Then write n integers p_1, p_2, \ldots, p_n in the same line.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack formatTo hack, use the following format:The first line contains an integer n (3 \leq n \leq 1\,000) — the number of vertices.The i-th of the next n lines contains two integers x_i and y_i (-10^9 \le x_i, y_i \le 10^9) — the coordinate of the point a_i.ExampleInput
6
15
-1
1Output
1 1 4 6
2 1 5 6
2 2 1 4
0 1 3 4 2 6 5NoteThe image below shows the hidden polygon in the example: The interaction in the example goes as below: Contestant reads n = 6. Contestant asks a query with t = 1, i = 1, j = 4, k = 6. Jury answers 15. The area of the triangle A_1A_4A_6 is 7.5. Note that the answer is two times the area of the triangle. Contestant asks a query with t = 2, i = 1, j = 5, k = 6. Jury answers -1. The cross product of \overrightarrow{A_1A_5} = (2, 2) and \overrightarrow{A_1A_6} = (4, 1) is -2. The sign of -2 is -1. Contestant asks a query with t = 2, i = 2, j = 1, k = 4. Jury answers 1. The cross product of \overrightarrow{A_2A_1} = (-5, 2) and \overrightarrow{A_2A_4} = (-2, -1) is 1. The sign of 1 is 1. Contestant says that the permutation is (1, 3, 4, 2, 6, 5). | 6
15
-1
1 | 1 1 4 6 2 1 5 6 2 2 1 4 0 1 3 4 2 6 5 | 1 second | 256 megabytes | ['constructive algorithms', 'geometry', 'interactive', 'math', '*2300'] |
B2. Send Boxes to Alice (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the harder version of the problem. In this version, 1 \le n \le 10^6 and 0 \leq a_i \leq 10^6. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problemsChristmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes of chocolate, numbered from 1 to n. Initially, the i-th box contains a_i chocolate pieces.Since Bob is a typical nice guy, he will not send Alice n empty boxes. In other words, at least one of a_1, a_2, \ldots, a_n is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer k > 1 such that the number of pieces in each box is divisible by k. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box i and put it into either box i-1 or box i+1 (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.InputThe first line contains a single integer n (1 \le n \le 10^6) — the number of chocolate boxes.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^6) — the number of chocolate pieces in the i-th box.It is guaranteed that at least one of a_1, a_2, \ldots, a_n is positive.OutputIf there is no way for Charlie to make Alice happy, print -1.Otherwise, print a single integer x — the minimum number of seconds for Charlie to help Bob make Alice happy.ExamplesInput
3
4 8 5
Output
9
Input
5
3 10 2 1 5
Output
2
Input
4
0 5 15 10
Output
0
Input
1
1
Output
-1
NoteIn the first example, Charlie can move all chocolate pieces to the second box. Each box will be divisible by 17.In the second example, Charlie can move a piece from box 2 to box 3 and a piece from box 4 to box 5. Each box will be divisible by 3.In the third example, each box is already divisible by 5.In the fourth example, since Charlie has no available move, he cannot help Bob make Alice happy. | 3
4 8 5
| 9 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', 'number theory', 'ternary search', 'two pointers', '*2100'] |
B1. Send Boxes to Alice (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easier version of the problem. In this version, 1 \le n \le 10^5 and 0 \le a_i \le 1. You can hack this problem only if you solve and lock both problems.Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes of chocolate, numbered from 1 to n. Initially, the i-th box contains a_i chocolate pieces.Since Bob is a typical nice guy, he will not send Alice n empty boxes. In other words, at least one of a_1, a_2, \ldots, a_n is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer k > 1 such that the number of pieces in each box is divisible by k. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box i and put it into either box i-1 or box i+1 (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of chocolate boxes.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 1) — the number of chocolate pieces in the i-th box.It is guaranteed that at least one of a_1, a_2, \ldots, a_n is positive.OutputIf there is no way for Charlie to make Alice happy, print -1.Otherwise, print a single integer x — the minimum number of seconds for Charlie to help Bob make Alice happy.ExamplesInput
3
1 0 1
Output
2
Input
1
1
Output
-1
| 3
1 0 1
| 2 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', 'number theory', 'ternary search', 'two pointers', '*1800'] |
A. Feeding Chickentime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLong is a huge fan of CFC (Codeforces Fried Chicken). But the price of CFC is increasing, so he decides to breed the chicken on his own farm.His farm is presented by a rectangle grid with r rows and c columns. Some of these cells contain rice, others are empty. k chickens are living on his farm. The number of chickens is not greater than the number of cells with rice on the farm.Long wants to give his chicken playgrounds by assigning these farm cells to his chickens. He would like to satisfy the following requirements: Each cell of the farm is assigned to exactly one chicken. Each chicken is assigned at least one cell. The set of cells assigned to every chicken forms a connected area. More precisely, if two cells (x, y) and (u, v) are assigned to the same chicken, this chicken is able to walk from (x, y) to (u, v) by passing only its cells and moving from each cell to another cell sharing a side. Long also wants to prevent his chickens from fighting for food. Hence he wants the difference between the maximum and the minimum number of cells with rice assigned to a chicken to be as small as possible. Please help him.InputEach test contains multiple test cases. The first line contains the number of test cases T (1 \le T \le 2 \cdot 10^4). Description of the test cases follows.The first line of each test case contains three integers r, c and k (1 \leq r, c \leq 100, 1 \leq k \leq 62), representing the size of Long's farm and the number of chickens Long has. Each of the next r lines contains c characters, each is either "." or "R", representing an empty cell or a cell with rice. It is guaranteed that the number of chickens is not greater than the number of cells with rice on the farm.It is guaranteed that the sum of r \cdot c over all test cases does not exceed 2 \cdot 10^4.OutputFor each test case, print r lines with c characters on each line. Each character should be either a lowercase English character, an uppercase English character, or a digit. Two characters should be equal if and only if the two corresponding cells are assigned to the same chicken. Uppercase and lowercase characters are considered different, so "A" and "a" belong to two different chickens.If there are multiple optimal answers, print any.ExampleInput
4
3 5 3
..R..
...R.
....R
6 4 6
R..R
R..R
RRRR
RRRR
R..R
R..R
5 5 4
RRR..
R.R..
RRR..
R..R.
R...R
2 31 62
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
Output
11122
22223
33333
aacc
aBBc
aBBc
CbbA
CbbA
CCAA
11114
22244
32444
33344
33334
abcdefghijklmnopqrstuvwxyzABCDE
FGHIJKLMNOPQRSTUVWXYZ0123456789NoteThese pictures explain the sample output. Each color represents one chicken. Cells filled with patterns (not solid colors) contain rice.In the first test case, each chicken has one cell with rice. Hence, the difference between the maximum and the minimum number of cells with rice assigned to a chicken is 0.In the second test case, there are 4 chickens with 3 cells of rice, and 2 chickens with 2 cells of rice. Hence, the difference between the maximum and the minimum number of cells with rice assigned to a chicken is 3 - 2 = 1.In the third test case, each chicken has 3 cells with rice. In the last test case, since there are 62 chicken with exactly 62 cells of rice, each chicken must be assigned to exactly one cell. The sample output is one of the possible way. | 4
3 5 3
..R..
...R.
....R
6 4 6
R..R
R..R
RRRR
RRRR
R..R
R..R
5 5 4
RRR..
R.R..
RRR..
R..R.
R...R
2 31 62
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
| 11122 22223 33333 aacc aBBc aBBc CbbA CbbA CCAA 11114 22244 32444 33344 33334 abcdefghijklmnopqrstuvwxyzABCDE FGHIJKLMNOPQRSTUVWXYZ0123456789 | 1.5 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', '*1700'] |
F. Cheap Robottime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou're given a simple, undirected, connected, weighted graph with n nodes and m edges.Nodes are numbered from 1 to n. There are exactly k centrals (recharge points), which are nodes 1, 2, \ldots, k.We consider a robot moving into this graph, with a battery of capacity c, not fixed by the constructor yet. At any time, the battery contains an integer amount x of energy between 0 and c inclusive.Traversing an edge of weight w_i is possible only if x \ge w_i, and costs w_i energy points (x := x - w_i).Moreover, when the robot reaches a central, its battery is entirely recharged (x := c).You're given q independent missions, the i-th mission requires to move the robot from central a_i to central b_i.For each mission, you should tell the minimum capacity required to acheive it.InputThe first line contains four integers n, m, k and q (2 \le k \le n \le 10^5 and 1 \le m, q \le 3 \cdot 10^5).The i-th of the next m lines contains three integers u_i, v_i and w_i (1 \le u_i, v_i \le n, u_i \neq v_i, 1 \le w_i \le 10^9), that mean that there's an edge between nodes u and v, with a weight w_i.It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes) and connected.The i-th of the next q lines contains two integers a_i and b_i (1 \le a_i, b_i \le k, a_i \neq b_i).OutputYou have to output q lines, where the i-th line contains a single integer : the minimum capacity required to acheive the i-th mission.ExamplesInput
10 9 3 1
10 9 11
9 2 37
2 4 4
4 1 8
1 5 2
5 7 3
7 3 2
3 8 4
8 6 13
2 3
Output
12
Input
9 11 3 2
1 3 99
1 4 5
4 5 3
5 6 3
6 4 11
6 7 21
7 2 6
7 8 4
8 9 3
9 2 57
9 3 2
3 1
2 3
Output
38
15
NoteIn the first example, the graph is the chain 10 - 9 - 2^C - 4 - 1^C - 5 - 7 - 3^C - 8 - 6, where centrals are nodes 1, 2 and 3.For the mission (2, 3), there is only one simple path possible. Here is a simulation of this mission when the capacity is 12. The robot begins on the node 2, with c = 12 energy points. The robot uses an edge of weight 4. The robot reaches the node 4, with 12 - 4 = 8 energy points. The robot uses an edge of weight 8. The robot reaches the node 1 with 8 - 8 = 0 energy points. The robot is on a central, so its battery is recharged. He has now c = 12 energy points. The robot uses an edge of weight 2. The robot is on the node 5, with 12 - 2 = 10 energy points. The robot uses an edge of weight 3. The robot is on the node 7, with 10 - 3 = 7 energy points. The robot uses an edge of weight 2. The robot is on the node 3, with 7 - 2 = 5 energy points. The robot is on a central, so its battery is recharged. He has now c = 12 energy points. End of the simulation. Note that if value of c was lower than 12, we would have less than 8 energy points on node 4, and we would be unable to use the edge 4 \leftrightarrow 1 of weight 8. Hence 12 is the minimum capacity required to acheive the mission.—The graph of the second example is described here (centrals are red nodes): The robot can acheive the mission (3, 1) with a battery of capacity c = 38, using the path 3 \rightarrow 9 \rightarrow 8 \rightarrow 7 \rightarrow 2 \rightarrow 7 \rightarrow 6 \rightarrow 5 \rightarrow 4 \rightarrow 1The robot can acheive the mission (2, 3) with a battery of capacity c = 15, using the path 2 \rightarrow 7 \rightarrow 8 \rightarrow 9 \rightarrow 3 | 10 9 3 1
10 9 11
9 2 37
2 4 4
4 1 8
1 5 2
5 7 3
7 3 2
3 8 4
8 6 13
2 3
| 12 | 3 seconds | 512 megabytes | ['binary search', 'dsu', 'graphs', 'shortest paths', 'trees', '*2500'] |
E. Antenna Coveragetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe mayor of the Central Town wants to modernize Central Street, represented in this problem by the (Ox) axis.On this street, there are n antennas, numbered from 1 to n. The i-th antenna lies on the position x_i and has an initial scope of s_i: it covers all integer positions inside the interval [x_i - s_i; x_i + s_i].It is possible to increment the scope of any antenna by 1, this operation costs 1 coin. We can do this operation as much as we want (multiple times on the same antenna if we want).To modernize the street, we need to make all integer positions from 1 to m inclusive covered by at least one antenna. Note that it is authorized to cover positions outside [1; m], even if it's not required.What is the minimum amount of coins needed to achieve this modernization?InputThe first line contains two integers n and m (1 \le n \le 80 and n \le m \le 100\ 000).The i-th of the next n lines contains two integers x_i and s_i (1 \le x_i \le m and 0 \le s_i \le m).On each position, there is at most one antenna (values x_i are pairwise distinct).OutputYou have to output a single integer: the minimum amount of coins required to make all integer positions from 1 to m inclusive covered by at least one antenna.ExamplesInput
3 595
43 2
300 4
554 10
Output
281
Input
1 1
1 1
Output
0
Input
2 50
20 0
3 1
Output
30
Input
5 240
13 0
50 25
60 5
155 70
165 70
Output
26
NoteIn the first example, here is a possible strategy: Increase the scope of the first antenna by 40, so that it becomes 2 + 40 = 42. This antenna will cover interval [43 - 42; 43 + 42] which is [1; 85] Increase the scope of the second antenna by 210, so that it becomes 4 + 210 = 214. This antenna will cover interval [300 - 214; 300 + 214], which is [86; 514] Increase the scope of the third antenna by 31, so that it becomes 10 + 31 = 41. This antenna will cover interval [554 - 41; 554 + 41], which is [513; 595] Total cost is 40 + 210 + 31 = 281. We can prove that it's the minimum cost required to make all positions from 1 to 595 covered by at least one antenna.Note that positions 513 and 514 are in this solution covered by two different antennas, but it's not important.—In the second example, the first antenna already covers an interval [0; 2] so we have nothing to do.Note that the only position that we needed to cover was position 1; positions 0 and 2 are covered, but it's not important. | 3 595
43 2
300 4
554 10
| 281 | 3 seconds | 256 megabytes | ['data structures', 'dp', 'greedy', 'sortings', '*2200'] |
D. Harmonious Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an undirected graph with n nodes and m edges. Nodes are numbered from 1 to n.The graph is considered harmonious if and only if the following property holds: For every triple of integers (l, m, r) such that 1 \le l < m < r \le n, if there exists a path going from node l to node r, then there exists a path going from node l to node m. In other words, in a harmonious graph, if from a node l we can reach a node r through edges (l < r), then we should able to reach nodes (l+1), (l+2), \ldots, (r-1) too.What is the minimum number of edges we need to add to make the graph harmonious? InputThe first line contains two integers n and m (3 \le n \le 200\ 000 and 1 \le m \le 200\ 000).The i-th of the next m lines contains two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \neq v_i), that mean that there's an edge between nodes u and v.It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes).OutputPrint the minimum number of edges we have to add to the graph to make it harmonious.ExamplesInput
14 8
1 2
2 7
3 4
6 3
5 7
3 8
6 8
11 12
Output
1
Input
200000 3
7 9
9 8
4 5
Output
0
NoteIn the first example, the given graph is not harmonious (for instance, 1 < 6 < 7, node 1 can reach node 7 through the path 1 \rightarrow 2 \rightarrow 7, but node 1 can't reach node 6). However adding the edge (2, 4) is sufficient to make it harmonious.In the second example, the given graph is already harmonious. | 14 8
1 2
2 7
3 4
6 3
5 7
3 8
6 8
11 12
| 1 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'sortings', '*1700'] |
C. Sweets Eatingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTsumugi brought n delicious sweets to the Light Music Club. They are numbered from 1 to n, where the i-th sweet has a sugar concentration described by an integer a_i.Yui loves sweets, but she can eat at most m sweets each day for health reasons.Days are 1-indexed (numbered 1, 2, 3, \ldots). Eating the sweet i at the d-th day will cause a sugar penalty of (d \cdot a_i), as sweets become more sugary with time. A sweet can be eaten at most once.The total sugar penalty will be the sum of the individual penalties of each sweet eaten.Suppose that Yui chooses exactly k sweets, and eats them in any order she wants. What is the minimum total sugar penalty she can get?Since Yui is an undecided girl, she wants you to answer this question for every value of k between 1 and n.InputThe first line contains two integers n and m (1 \le m \le n \le 200\ 000).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 200\ 000).OutputYou have to output n integers x_1, x_2, \ldots, x_n on a single line, separed by spaces, where x_k is the minimum total sugar penalty Yui can get if she eats exactly k sweets.ExamplesInput
9 2
6 19 3 4 4 2 6 7 8
Output
2 5 11 18 30 43 62 83 121
Input
1 1
7
Output
7
NoteLet's analyze the answer for k = 5 in the first example. Here is one of the possible ways to eat 5 sweets that minimize total sugar penalty: Day 1: sweets 1 and 4 Day 2: sweets 5 and 3 Day 3 : sweet 6 Total penalty is 1 \cdot a_1 + 1 \cdot a_4 + 2 \cdot a_5 + 2 \cdot a_3 + 3 \cdot a_6 = 6 + 4 + 8 + 6 + 6 = 30. We can prove that it's the minimum total sugar penalty Yui can achieve if she eats 5 sweets, hence x_5 = 30. | 9 2
6 19 3 4 4 2 6 7 8
| 2 5 11 18 30 43 62 83 121 | 1 second | 256 megabytes | ['dp', 'greedy', 'math', 'sortings', '*1500'] |
B. Silly Mistaketime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Central Company has an office with a sophisticated security system. There are 10^6 employees, numbered from 1 to 10^6.The security system logs entrances and departures. The entrance of the i-th employee is denoted by the integer i, while the departure of the i-th employee is denoted by the integer -i.The company has some strict rules about access to its office: An employee can enter the office at most once per day. He obviously can't leave the office if he didn't enter it earlier that day. In the beginning and at the end of every day, the office is empty (employees can't stay at night). It may also be empty at any moment of the day. Any array of events satisfying these conditions is called a valid day.Some examples of valid or invalid days: [1, 7, -7, 3, -1, -3] is a valid day (1 enters, 7 enters, 7 leaves, 3 enters, 1 leaves, 3 leaves). [2, -2, 3, -3] is also a valid day. [2, 5, -5, 5, -5, -2] is not a valid day, because 5 entered the office twice during the same day. [-4, 4] is not a valid day, because 4 left the office without being in it. [4] is not a valid day, because 4 entered the office and didn't leave it before the end of the day. There are n events a_1, a_2, \ldots, a_n, in the order they occurred. This array corresponds to one or more consecutive days. The system administrator erased the dates of events by mistake, but he didn't change the order of the events.You must partition (to cut) the array a of events into contiguous subarrays, which must represent non-empty valid days (or say that it's impossible). Each array element should belong to exactly one contiguous subarray of a partition. Each contiguous subarray of a partition should be a valid day.For example, if n=8 and a=[1, -1, 1, 2, -1, -2, 3, -3] then he can partition it into two contiguous subarrays which are valid days: a = [1, -1~ \boldsymbol{|}~ 1, 2, -1, -2, 3, -3].Help the administrator to partition the given array a in the required way or report that it is impossible to do. Find any required partition, you should not minimize or maximize the number of parts.InputThe first line contains a single integer n (1 \le n \le 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (-10^6 \le a_i \le 10^6 and a_i \neq 0).OutputIf there is no valid partition, print -1. Otherwise, print any valid partition in the following format: On the first line print the number d of days (1 \le d \le n). On the second line, print d integers c_1, c_2, \ldots, c_d (1 \le c_i \le n and c_1 + c_2 + \ldots + c_d = n), where c_i is the number of events in the i-th day. If there are many valid solutions, you can print any of them. You don't have to minimize nor maximize the number of days.ExamplesInput
6
1 7 -7 3 -1 -3
Output
1
6
Input
8
1 -1 1 2 -1 -2 3 -3
Output
2
2 6
Input
6
2 5 -5 5 -5 -2
Output
-1
Input
3
-8 1 1
Output
-1
NoteIn the first example, the whole array is a valid day.In the second example, one possible valid solution is to split the array into [1, -1] and [1, 2, -1, -2, 3, -3] (d = 2 and c = [2, 6]). The only other valid solution would be to split the array into [1, -1], [1, 2, -1, -2] and [3, -3] (d = 3 and c = [2, 4, 2]). Both solutions are accepted.In the third and fourth examples, we can prove that there exists no valid solution. Please note that the array given in input is not guaranteed to represent a coherent set of events. | 6
1 7 -7 3 -1 -3
| 1 6 | 1 second | 256 megabytes | ['greedy', 'implementation', '*1400'] |
A. Single Pushtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given two arrays a[1 \dots n] and b[1 \dots n], both of the same length n.In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 \le l \le r \le n and k > 0. Then, you will add k to elements a_l, a_{l+1}, \ldots, a_r.For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2].You can do this operation at most once. Can you make array a equal to array b?(We consider that a = b if and only if, for every 1 \le i \le n, a_i = b_i)InputThe first line contains a single integer t (1 \le t \le 20) — the number of test cases in the input.The first line of each test case contains a single integer n (1 \le n \le 100\ 000) — the number of elements in each array.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 1000).The third line of each test case contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le 1000).It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.OutputFor each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible.You can print each letter in any case (upper or lower).ExampleInput
4
6
3 7 1 4 1 2
3 7 3 6 3 2
5
1 1 1 1 1
1 2 1 3 1
2
42 42
42 42
1
7
6
Output
YES
NO
YES
NO
NoteThe first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b.In the second test case, we would need at least two operations to make a equal to b.In the third test case, arrays a and b are already equal.In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. | 4
6
3 7 1 4 1 2
3 7 3 6 3 2
5
1 1 1 1 1
1 2 1 3 1
2
42 42
42 42
1
7
6
| YES NO YES NO | 1 second | 256 megabytes | ['implementation', '*1000'] |
L. Road Constructiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are N cities in the country of Numbata, numbered from 1 to N. Currently, there is no road connecting them. Therefore, each of these N cities proposes a road candidate to be constructed.City i likes to connect with city A_i, so city i proposes to add a direct bidirectional road connecting city i and city A_i. It is guaranteed that no two cities like to connect with each other. In other words, there is no pair of integers i and j where A_i = j and A_j = i. It is also guaranteed that any pair of cities are connected by a sequence of road proposals. In other words, if all proposed roads are constructed, then any pair of cities are connected by a sequence of constructed road.City i also prefers the road to be constructed using a specific material. Each material can be represented by an integer (for example, 0 for asphalt, 1 for wood, etc.). The material that can be used for the road connecting city i and city A_i is represented by an array B_i containing M_i integers: [(B_i)_1, (B_i)_2, \dots, (B_i)_{M_i}]. This means that the road connecting city i and city A_i can be constructed with either of the material in B_i.There are K workers to construct the roads. Each worker is only familiar with one material, thus can only construct a road with a specific material. In particular, the i^{th} worker can only construct a road with material C_i. Each worker can only construct at most one road. You want to assign each worker to construct a road such that any pair of cities are connected by a sequence of constructed road.InputInput begins with a line containing two integers: N K (3 \le N \le 2000; 1 \le K \le 2000) representing the number of cities and the number of workers, respectively. The next N lines each contains several integers: A_i M_i (B_i)_1, (B_i)_2, \cdots, (B_i)_{M_i} (1 \le A_i \le N; A_i \ne i; 1 \le M_i \le 10\,000; 0 \le (B_i)_1 < (B_i)_2 < \dots < (B_i)_{M_i} \le 10^9) representing the bidirectional road that city i likes to construct. It is guaranteed that the sum of M_i does not exceed 10\,000. It is also guaranteed that no two cities like to connect with each other and any pair of cities are connected by a sequence of road proposals. The next line contains K integers: C_i (0 \le C_i \le 10^9) representing the material that is familiarized by the workers.OutputIf it is not possible to assign each worker to construct a road such that any pair of cities are connected by a sequence of constructed road, simply output -1 in a line. Otherwise, for each worker in the same order as input, output in a line two integers (separated by a single space): u and v in any order. This means that the worker constructs a direct bidirectional road connecting city u and v. If the worker does not construct any road, output "0 0" (without quotes) instead. Each pair of cities can only be assigned to at most one worker. You may output any assignment as long as any pair of cities are connected by a sequence of constructed road.ExamplesInput
4 5
2 2 1 2
3 2 2 3
4 2 3 4
2 2 4 5
1 2 3 4 5
Output
1 2
2 3
3 4
0 0
4 2
Input
4 5
2 2 10 20
3 2 2 3
4 2 3 4
2 2 4 5
1 2 3 4 5
Output
-1
NoteExplanation for the sample input/output #1We can assign the workers to construct the following roads: The first worker constructs a road connecting city 1 and city 2. The second worker constructs a road connecting city 2 and city 3. The third worker constructs a road connecting city 3 and city 4. The fourth worker does not construct any road. The fifth worker constructs a road connecting city 4 and city 2. Therefore, any pair of cities are now connected by a sequence of constructed road.Explanation for the sample input/output #2There is no worker that can construct a road connecting city 1, thus city 1 is certainly isolated. | 4 5
2 2 1 2
3 2 2 3
4 2 3 4
2 2 4 5
1 2 3 4 5
| 1 2 2 3 3 4 0 0 4 2 | 2 seconds | 256 megabytes | ['flows', 'graphs', '*2300'] |
K. Addition Robottime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdding two numbers several times is a time-consuming task, so you want to build a robot. The robot should have a string S = S_1 S_2 \dots S_N of N characters on its memory that represents addition instructions. Each character of the string, S_i, is either 'A' or 'B'.You want to be able to give Q commands to the robot, each command is either of the following types: 1 L R. The robot should toggle all the characters of S_i where L \le i \le R. Toggling a character means changing it to 'A' if it was previously 'B', or changing it to 'B' if it was previously 'A'. 2 L R A B. The robot should call f(L, R, A, B) and return two integers as defined in the following pseudocode: function f(L, R, A, B): FOR i from L to R if S[i] = 'A' A = A + B else B = A + B return (A, B) You want to implement the robot's expected behavior.InputInput begins with a line containing two integers: N Q (1 \le N, Q \le 100\,000) representing the number of characters in the robot's memory and the number of commands, respectively. The next line contains a string S containing N characters (each either 'A' or 'B') representing the initial string in the robot's memory. The next Q lines each contains a command of the following types. 1 L R (1 \le L \le R \le N) 2 L R A B (1 \le L \le R \le N; 0 \le A, B \le 10^9) There is at least one command of the second type.OutputFor each command of the second type in the same order as input, output in a line two integers (separated by a single space), the value of A and B returned by f(L, R, A, B), respectively. As this output can be large, you need to modulo the output by 1\,000\,000\,007.ExampleInput
5 3
ABAAA
2 1 5 1 1
1 3 5
2 2 5 0 1000000000
Output
11 3
0 1000000000
NoteExplanation for the sample input/output #1For the first command, calling f(L, R, A, B) causes the following: Initially, A = 1 and B = 1. At the end of i = 1, A = 2 and B = 1. At the end of i = 2, A = 2 and B = 3. At the end of i = 3, A = 5 and B = 3. At the end of i = 4, A = 8 and B = 3. At the end of i = 5, A = 11 and B = 3. Therefore, f(L, R, A, B) will return (11, 3).For the second command, string S will be updated to "ABBBB".For the third command, the value of A will always be 0 and the value of B will always be 1\,000\,000\,000. Therefore, f(L, R, A, B) will return (0, 1\,000\,000\,000). | 5 3
ABAAA
2 1 5 1 1
1 3 5
2 2 5 0 1000000000
| 11 3 0 1000000000 | 3 seconds | 256 megabytes | ['data structures', 'math', 'matrices', '*2100'] |
J. Tiling Terracetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTalia has just bought an abandoned house in the outskirt of Jakarta. The house has a nice and long yard which can be represented as a one-dimensional grid containing 1 \times N cells. To beautify the house, Talia is going to build a terrace on the yard by tiling the cells. Each cell on the yard contains either soil (represented by the character '.') or rock (represented by the character '#'), and there are at most 50 cells containing rocks.Being a superstitious person, Talia wants to tile the terrace with mystical tiles that have the power to repel ghosts. There are three types of mystical tiles: Type-1: Covers 1 \times 1 cell and can only be placed on a soil cell ("."). Type-2: Covers 1 \times 2 cells and can only be placed on two consecutive soil cells (".."). Type-3: Covers 1 \times 3 cells and can only be placed on consecutive soil-rock-soil cells (".#."). Each tile of Type-1, Type-2, and Type-3 has the power to repel G_1, G_2, and G_3 ghosts per day, respectively. There are also some mystical rules which must be followed for the power to be effective: There should be no overlapping tiles, i.e. each cell is covered by at most one tile. There should be at most K tiles of Type-1, while there are no limitations for tiles of Type-2 and Type-3. Talia is scared of ghosts, thus, the terrace (which is tiled by mystical tiles) should be able to repel as many ghosts as possible. Help Talia to find the maximum number of ghosts that can be repelled per day by the terrace. Note that Talia does not need to tile all the cells on the yard as long as the number of ghosts that can be repelled by the terrace is maximum.InputInput begins with a line containing five integers: N K G_1 G_2 G_3 (1 \le N \le 100\,000; 0 \le K \le N; 0 \le G_1, G_2, G_3 \le 1000) representing the number of cells, the maximum number of tiles of Type-1, the number of ghosts repelled per day by a tile of Type-1, the number of ghosts repelled per day by a tile of Type-2, and the number of ghosts repelled by a tile of Type-3, respectively. The next line contains a string of N characters representing the yard. Each character in the string is either '.' which represents a soil cell or '#' which represents a rock cell. There are at most 50 rock cells.OutputOutput in a line an integer representing the maximum number of ghosts that can be repelled per day.ExamplesInput
6 4 10 25 40
..#...
Output
75
Input
6 4 10 100 40
..#...
Output
210
Input
7 2 30 10 100
..#...#
Output
160
NoteExplanation for the sample input/output #1Let "A" be a tile of Type-1, "BB" be a tile of Type-2, and "CCC" be a tile of Type-3. The tiling "ACCCBB" in this case produces the maximum number of ghosts that can be repelled, i.e. 10 + 40 + 25 = 75Explanation for the sample input/output #2This sample input has the same yard with the previous sample input, but each tile of Type-2 can repel more ghosts per day. The tiling "BB#BBA" or "BB#ABB" produces the maximum number of ghosts that can be repelled, i.e. 100 + 100 + 10 = 210. Observe that the third cell is left untiled.Explanation for the sample input/output #3The tiling "ACCCA.#", "ACCC.A#", or ".CCCAA#" produces the maximum number of ghosts that can be repelled, i.e. 30 + 100 + 30 = 160. Observe that there is no way to tile the last cell. | 6 4 10 25 40
..#...
| 75 | 1 second | 256 megabytes | ['brute force', 'dp', '*2300'] |
I. Mission Possibletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAllen, a government secret service, has been assigned to infiltrate a mafia secret base to uncover crucial information regarding the mafia's operations.The secret base is a rectangular bounded by (x_L,y_L), (x_L,y_R), (x_R,y_L), and (x_R,y_R) in a Cartesian coordinate system where x_L < x_R and y_L < y_R. There are N sensors placed inside the secret base. The i^{th} sensor is located at (x_i, y_i) and has an effective sensing radius of r_i which can detect any person who is strictly within the radius of r_i from (x_i, y_i). In other words, the i^{th} sensor can detect a person at location (x_a, y_a) if and only if the Euclidean distance of (x_i, y_i) and (x_a, y_a) is strictly less than r_i. It is also known that the Euclidean distance of any two sensors i and j is strictly larger than r_i + r_j. Note that the Euclidean distance of two points, (x_a, y_a) and (x_b, y_b), is \sqrt{|x_a - x_b|^2 + |y_a - y_b|^2}.Allen begins his infiltration mission at location (x_s, y_s), and his target is located at (x_t, y_t). Allen has the power to run extremely fast in a straight line while he needs to spend extra time to change his running trajectory (to adjust his footing). Although he is a fast runner, he still needs to make sure that none of the sensors detect him while he is running, i.e. there is no point in his running trajectory which is strictly within a sensor effective sensing radius.Let P = \{(x_{p_1}, y_{p_1}), \dots, (x_{p_{|P|}}, y_{p_{|P|}})\} be the set of locations where Allen changes his running trajectory, thus, Allen's running trajectory with P is (x_s, y_s) \rightarrow (x_{p_1}, y_{p_1}) \rightarrow \dots \rightarrow (x_{p_{|P|}}, y_{p_{|P|}}) \rightarrow (x_t, y_t) where (x_a,y_a) \rightarrow (x_b,y_b) implies that Allen is running from (x_a,y_a) to (x_b,y_b) in a straight line. The set P is feasible if and only if with P, Allen is not detected by any sensor and is not running out of the secret base (although, Allen is allowed to run along the secret base perimeter). Note that x_p and y_p, (x_p,y_p) \in P, are not necessarily integers; they can be real numbers.Your task in this problem is to find any one feasible P which contains no more than 1000 points.InputInput begins with a line containing five integers: N x_L y_L x_R y_R (0 \le N \le 50; 0 \le x_L < x_R \le 1000; 0 \le y_L < y_R \le 1000) representing the number of sensors and the secret base (x_L, y_L, x_R, y_R), respectively. The next line contains two integers: x_s y_s (x_L < x_s < x_R; y_L < y_s < y_R) representing Allen's initial location. The next line contains two integers: x_t y_t (x_L < x_t < x_R; y_L < y_t < y_R) representing Allen's target location. It is guaranteed that x_s \ne x_t or y_s \ne y_t. The next N lines each contains three integers: x_i y_i r_i (x_L < x_i - r_i < x_i + r_i < x_R; y_L < y_i - r_i < y_i + r_i < y_R; 1 \le r_i \le 1000) representing a sensor at location (x_i, y_i) with an effective sensing radius of r_i. It is guaranteed that the Euclidean distance of any two sensors i and j is larger than r_i + r_j. It is also guaranteed that the Euclidean distance of (x_s,y_s) and (x_t,y_t) to any sensor i is larger than r_i.OutputOutput in a line an integer representing the size of a feasible P. The next |P| lines each contains two real numbers (separated by a single space); the j^{th} line contains x_j y_j representing the j^{th} point in P. You may output any feasible P with no more than 1000 points.Due to the nature of the output (floating point), let us define an epsilon \epsilon to be 10^{-6} to verify the output. Consider Q_1 = (x_s, y_s), Q_{j+1} = P_j for all 1 \le j \le |P|, and Q_{|P|+2} = (x_t, y_t). Then, P is considered correct if and only if P contains no more than 1000 points and all of the following are satisfied: x_L - \epsilon \le x_{p_k} \le x_R + \epsilon and y_L - \epsilon \le y_{p_k} \le y_R + \epsilon for all 1 \le k \le |P| (Allen is not running out of the secret base). For all 1 \le k < |Q|, let S_k be the line segment connecting Q_k and Q_{k+1} (Allen is running in straight line). For all 1 \le i \le N, let (x_{k,i},y_{k,i}) be the point along S_k that is the closest to the i^{th} sensor's location, (x_i,y_i). Let d_{k,i} be the Euclidean distance between (x_{k,i},y_{k,i}) and (x_i,y_i). Then, the constraint r_i \le d_{k,i} + \epsilon should be satisfied (Allen is not detected by any sensor). All points in Q are distinct. Two points, (x_a,y_a) and (x_b,y_b), are considered distinct if and only if |x_a - x_b| > \epsilon or |y_a - y_b| > \epsilon. ExamplesInput
3 2 2 50 26
4 14
48 14
15 13 7
36 16 6
46 18 3
Output
2
13.25 23.1234567
36.591003 7.1
Input
1 0 0 1000 1000
100 501
900 501
500 251 250
Output
0
NoteExplanation for the sample input/output #1The figure above shows the P from the sample output. Note that there exists a feasible P with only one point in this sample, although you are not required to find such P. | 3 2 2 50 26
4 14
48 14
15 13 7
36 16 6
46 18 3
| 2 13.25 23.1234567 36.591003 7.1 | 1 second | 256 megabytes | ['*3000'] |
H. Twin Buildingstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you might already know, space has always been a problem in ICPC Jakarta. To cope with this, ICPC Jakarta is planning to build two new buildings. These buildings should have a shape of a rectangle of the same size. Now, their problem is to find land to build the buildings.There are N lands available for sale. The i^{th} land has a rectangular shape of size L_i \times W_i. For a good feng shui, the building's side should be parallel to the land's sides.One way is to build the two buildings on two different lands, one on each land (not necessarily with the same orientation). A building of size A \times B can be build on the i^{th} land if and only if at least one of the following is satisfied: A \le L_i and B \le W_i, or A \le W_i and B \le L_i. Alternatively, it is also possible to build two buildings of A \times B on the i^{th} land with the same orientation. Formally, it is possible to build two buildings of A \times B on the i^{th} land if and only if at least one of the following is satisfied: A \times 2 \le L_i and B \le W_i, or A \times 2 \le W_i and B \le L_i, or A \le L_i and B \times 2 \le W_i, or A \le W_i and B \times 2 \le L_i. Your task in this problem is to help ICPC Jakarta to figure out the largest possible buildings they can build given N available lands. Note that ICPC Jakarta has to build two buildings of A \times B; output the largest possible for A \times B.InputInput begins with a line containing an integer: N (1 \le N \le 100\,000) representing the number of available lands. The next N lines each contains two integers: L_i W_i (1 \le L_i, W_i \le 10^9) representing the size of the land.OutputOutput in a line a number representing the largest building that ICPC Jakarta can build with exactly one decimal point (see sample input/output for clarity).ExamplesInput
2
5 5
3 4
Output
12.5
Input
2
2 5
4 3
Output
8.0
Input
3
10 1
9 8
7 6
Output
42.0
NoteExplanation for the sample input/output #1Two buildings of 2.5 \times 5 can be built both on the first land.Explanation for the sample input/output #2Two buildings of 2 \times 4 can be built each on the first and second lands.Explanation for the sample input/output #3Two buildings of 7 \times 6 can be built each on the second and third lands. | 2
5 5
3 4
| 12.5 | 1 second | 256 megabytes | ['greedy', 'implementation', '*1800'] |
G. Performance Reviewtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRandall is a software engineer at a company with N employees. Every year, the company re-evaluates its employees. At the end of every year, the company replaces its several worst-performing employees and replaces with the same number of new employees, so that the company keeps having N employees. Each person has a constant performance and can be represented by an integer (higher integer means better performance), and no two people have the same performance.The performance of the initial employees are represented by an array of integers A = [A_1, A_2, \dots, A_N] where A_i is the performance of the i^{th} employee. Randall is employee 1, so his performance is A_1. We will consider the first M years. At the end of the i^{th} year, the company replaces its R_i worst-performing employees and replaces with R_i new employees. The performance of these new employees are represented by an array of integers B_i = [(B_i)_1, (B_i)_2, \dots, (B_i)_{R_i}] where (B_i)_j is the performance of the j^{th} new employee.He will consider Q scenarios. On the i^{th} scenario, he will change the value of (B_{X_i})_{Y_i} to Z_i. For each scenario, Randall is wondering whether he will still be in the company after M years. Note that the changes in each scenario are kept for the subsequent scenarios.InputInput begins with a line containing three integers: N M Q (2 \le N \le 100\,000; 1 \le M, Q \le 100\,000) representing the number of employees, the number of years to be considered, and the number of scenarios, respectively. The next line contains N integers: A_i (0 \le A_i \le 10^9) representing the performance of the initial employees. The next M lines each contains several integers: R_i (B_i)_1, (B_i)_2, \cdots, (B_i)_{R_i} (1 \le R_i < N; 0 \le (B_i)_j \le 10^9) representing the number of employees replaced and the performance of the new employees, respectively. It is guaranteed that the sum of R_i does not exceed 10^6. The next Q lines each contains three integers: X_i Y_i Z_i (1 \le X_i \le M; 1 \le Y_i \le R_{(X_i)}; 0 \le Z_i \le 10^9) representing a scenario. It is guaranteed that all integers in all A_i, (B_i)_j, and Z_i (combined together) are distinct.OutputFor each scenario in the same order as input, output in a line an integer 0 if Randall will not be in the company after M years, or 1 if Randall will still be in the company after M years.ExampleInput
5 3 3
50 40 30 20 10
4 1 2 3 100
1 4
2 6 7
1 3 300
2 1 400
2 1 5
Output
1
0
1
NoteExplanation for the sample input/output #1Randall performance is represented by 50. For the first scenario, the value of (B_1)_3 is updated to 300, causes the following: Initially, the performance of the employees is [50, 40, 30, 20, 10]. At the end of the first year, 4 worst-performing employees are replaced by employees with performance [300, 100, 2, 1]. Therefore, the performance of the employees is [300, 100, 50, 2, 1]. At the end of the second year, the performance of the employees is [300, 100, 50, 4, 2]. At the end of the third year, the performance of the employees is [300, 100, 50, 7, 6]. Therefore, Randall will still be in the company after 3 years.For the second scenario, the value of (B_2)_1 is updated to 400, causes the following: Initially, the performance of the employees is [50, 40, 30, 20, 10]. At the end of the first year, the performance of the employees is [300, 100, 50, 2, 1]. Recall that the change in the first scenario is kept for this scenario as well. At the end of the second year, the performance of the employees is [400, 300, 100, 50, 2]. At the end of the third year, the performance of the employees is [400, 300, 100, 7, 6]. Therefore, Randall will not be in the company after 3 years. | 5 3 3
50 40 30 20 10
4 1 2 3 100
1 4
2 6 7
1 3 300
2 1 400
2 1 5
| 1 0 1 | 2 seconds | 256 megabytes | ['data structures', '*2100'] |
F. Regular Forestationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA forestation is an act of planting a bunch of trees to grow a forest, usually to replace a forest that had been cut down. Strangely enough, graph theorists have another idea on how to make a forest, i.e. by cutting down a tree!A tree is a graph of N nodes connected by N - 1 edges. Let u be a node in a tree U which degree is at least 2 (i.e. directly connected to at least 2 other nodes in U). If we remove u from U, then we will get two or more disconnected (smaller) trees, or also known as forest by graph theorists. In this problem, we are going to investigate a special forestation of a tree done by graph theorists.Let V(S) be the set of nodes in a tree S and V(T) be the set of nodes in a tree T. Tree S and tree T are identical if there exists a bijection f : V(S) \rightarrow V(T) such that for all pairs of nodes (s_i, s_j) in V(S), s_i and s_j is connected by an edge in S if and only if node f(s_i) and f(s_j) is connected by an edge in T. Note that f(s) = t implies node s in S corresponds to node t in T.We call a node u in a tree U as a good cutting point if and only if the removal of u from U causes two or more disconnected trees, and all those disconnected trees are pairwise identical.Given a tree U, your task is to determine whether there exists a good cutting point in U. If there is such a node, then you should output the maximum number of disconnected trees that can be obtained by removing exactly one good cutting point.For example, consider the following tree of 13 nodes.There is exactly one good cutting point in this tree, i.e. node 4. Observe that by removing node 4, we will get three identical trees (in this case, line graphs), i.e. \{5, 1, 7, 13\}, \{8, 2, 11, 6\}, and \{3, 12, 9, 10\}, which are denoted by A, B, and C respectively in the figure. The bijection function between A and B: f(5) = 8, f(1) = 2, f(7) = 11, and f(13) = 6. The bijection function between A and C: f(5) = 3, f(1) = 12, f(7) = 9, and f(13) = 10. The bijection function between B and C: f(8) = 3, f(2) = 12, f(11) = 9, and f(6) = 10. Of course, there exists other bijection functions for those trees.InputInput begins with a line containting an integer: N (3 \le N \le 4000) representing the number of nodes in the given tree. The next N - 1 lines each contains two integers: a_i b_i (1 \le a_i < b_i \le N) representing an edge (a_i,b_i) in the given tree. It is guaranteed that any two nodes in the given tree are connected to each other by a sequence of edges.OutputOutput in a line an integer representing the maximum number of disconnected trees that can be obtained by removing exactly one good cutting point, or output -1 if there is no such good cutting point.ExamplesInput
13
1 5
1 7
2 4
2 8
2 11
3 12
4 7
4 12
6 11
7 13
9 10
9 12
Output
3
Input
6
1 2
1 3
2 4
3 5
3 6
Output
-1
NoteExplanation for the sample input/output #1This is the example from the problem description. | 13
1 5
1 7
2 4
2 8
2 11
3 12
4 7
4 12
6 11
7 13
9 10
9 12
| 3 | 1 second | 256 megabytes | ['hashing', 'trees', '*2400'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.