problem_statement
stringlengths 147
8.53k
| input
stringlengths 1
771
| output
stringlengths 1
592
⌀ | time_limit
stringclasses 32
values | memory_limit
stringclasses 21
values | tags
stringlengths 6
168
|
---|---|---|---|---|---|
D. Martial Arts Tournamenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is planning to host a martial arts tournament. There will be three divisions based on weight: lightweight, middleweight and heavyweight. The winner of each division will be determined by a single elimination system.In particular, that implies that the number of participants in each division should be a power of two. Additionally, each division should have a non-zero amount of participants.n participants have registered for the tournament so far, the i-th of them weighs a_i. To split participants into divisions, Monocarp is going to establish two integer weight boundaries x and y (x < y). All participants who weigh strictly less than x will be considered lightweight. All participants who weigh greater or equal to y will be considered heavyweight. The remaining participants will be considered middleweight.It's possible that the distribution doesn't make the number of participants in each division a power of two. It can also lead to empty divisions. To fix the issues, Monocarp can invite an arbitrary number of participants to each division.Note that Monocarp can't kick out any of the n participants who have already registered for the tournament.However, he wants to invite as little extra participants as possible. Help Monocarp to choose x and y in such a way that the total amount of extra participants required is as small as possible. Output that amount.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of the registered participants.The second line of each testcase contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — the weights of the registered participants.The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the smallest number of extra participants Monocarp is required to invite after he chooses the weight boundaries x and y.ExampleInput
443 1 2 11162 2 2 1 1 186 3 6 3 6 3 6 6Output
0
2
3
2
NoteIn the first testcase of the example, Monocarp can choose x=2 and y=3. Lightweight, middleweight and heavyweight divisions will have 2, 1 and 1 participants, respectively. They all are powers of two, so no extra participants are required.In the second testcase of the example, regardless of the choice of x and y, one division will have 1 participant, the rest will have 0. Thus, Monocarp will have to invite 1 participant into both of the remaining divisions.In the third testcase of the example, Monocarp can choose x=1 and y=2. Lightweight, middleweight and heavyweight divisions will have 0, 3 and 3 participants, respectively. So an extra participant is needed in each division.In the fourth testcase of the example, Monocarp can choose x=8 and y=9. Lightweight, middleweight and heavyweight divisions will have 8, 0 and 0 participants, respectively. Middleweight and heavyweight division need an extra participant each. | 443 1 2 11162 2 2 1 1 186 3 6 3 6 3 6 6 | 0 2 3 2 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'greedy', 'math', '*2100'] |
C. Monsters And Spellstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is playing a computer game once again. He is a wizard apprentice, who only knows a single spell. Luckily, this spell can damage the monsters.The level he's currently on contains n monsters. The i-th of them appears k_i seconds after the start of the level and has h_i health points. As an additional constraint, h_i \le k_i for all 1 \le i \le n. All k_i are different.Monocarp can cast the spell at moments which are positive integer amounts of second after the start of the level: 1, 2, 3, \dots The damage of the spell is calculated as follows. If he didn't cast the spell at the previous second, the damage is 1. Otherwise, let the damage at the previous second be x. Then he can choose the damage to be either x + 1 or 1. A spell uses mana: casting a spell with damage x uses x mana. Mana doesn't regenerate.To kill the i-th monster, Monocarp has to cast a spell with damage at least h_i at the exact moment the monster appears, which is k_i.Note that Monocarp can cast the spell even when there is no monster at the current second.The mana amount required to cast the spells is the sum of mana usages for all cast spells. Calculate the least amount of mana required for Monocarp to kill all monsters.It can be shown that it's always possible to kill all monsters under the constraints of the problem.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of the testcase contains a single integer n (1 \le n \le 100) — the number of monsters in the level.The second line of the testcase contains n integers k_1 < k_2 < \dots < k_n (1 \le k_i \le 10^9) — the number of second from the start the i-th monster appears at. All k_i are different, k_i are provided in the increasing order.The third line of the testcase contains n integers h_1, h_2, \dots, h_n (1 \le h_i \le k_i \le 10^9) — the health of the i-th monster.The sum of n over all testcases doesn't exceed 10^4.OutputFor each testcase, print a single integer — the least amount of mana required for Monocarp to kill all monsters.ExampleInput
316424 52 235 7 92 1 2Output
10
6
7
NoteIn the first testcase of the example, Monocarp can cast spells 3, 4, 5 and 6 seconds from the start with damages 1, 2, 3 and 4, respectively. The damage dealt at 6 seconds is 4, which is indeed greater than or equal to the health of the monster that appears.In the second testcase of the example, Monocarp can cast spells 3, 4 and 5 seconds from the start with damages 1, 2 and 3, respectively.In the third testcase of the example, Monocarp can cast spells 4, 5, 7, 8 and 9 seconds from the start with damages 1, 2, 1, 1 and 2, respectively. | 316424 52 235 7 92 1 2 | 10 6 7 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dp', 'greedy', 'implementation', 'math', 'two pointers', '*1700'] |
B. Minor Reductiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a decimal representation of an integer x without leading zeros.You have to perform the following reduction on it exactly once: take two neighboring digits in x and replace them with their sum without leading zeros (if the sum is 0, it's represented as a single 0).For example, if x = 10057, the possible reductions are: choose the first and the second digits 1 and 0, replace them with 1+0=1; the result is 1057; choose the second and the third digits 0 and 0, replace them with 0+0=0; the result is also 1057; choose the third and the fourth digits 0 and 5, replace them with 0+5=5; the result is still 1057; choose the fourth and the fifth digits 5 and 7, replace them with 5+7=12; the result is 10012. What's the largest number that can be obtained?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.Each testcase consists of a single integer x (10 \le x < 10^{200000}). x doesn't contain leading zeros.The total length of the decimal representations of x over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the largest number that can be obtained after the reduction is applied exactly once. The number should not contain leading zeros.ExampleInput
2
10057
90
Output
10012
9
NoteThe first testcase of the example is already explained in the statement.In the second testcase, there is only one possible reduction: the first and the second digits. | 2
10057
90
| 10012 9 | 2 seconds | 256 megabytes | ['greedy', 'strings', '*1100'] |
A. Equidistant Letterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting of lowercase Latin letters. Every letter appears in it no more than twice.Your task is to rearrange the letters in the string in such a way that for each pair of letters that appear exactly twice, the distance between the letters in the pair is the same. You are not allowed to add or remove letters.It can be shown that the answer always exists. If there are multiple answers, print any of them.InputThe first line contains a single integer t (1 \le t \le 10^3) — the number of testcases.Each testcase consists of a non-empty string s, consisting of lowercase Latin letters. Every letter appears in the string no more than twice. The length of the string doesn't exceed 52.OutputFor each testcase, print a single string. Every letter should appear in it the same number of times as it appears in string s. For each pair of letters that appear exactly twice, the distance between the letters in the pair should be the same.If there are multiple answers, print any of them.ExampleInput
3
oelhl
abcdcba
ac
Output
hello
ababcdc
ac
NoteIn the first testcase of the example, the only letter that appears exactly twice is letter 'l'. You can rearrange the letters arbitrarily, since there are no distances to compare.In the second testcase of the example, the letters that appear exactly twice are 'a', 'b' and 'c'. Initially, letters 'a' are distance 6 apart, letters 'b' are distance 4 apart and letters 'c' are distance 2 apart. They are not the same, so we have to rearrange the letters. After rearrangement, letters 'a' are distance 2 apart, letters 'b' are distance 2 apart and letters 'c' are distance 2 apart. They are all the same, so the answer is valid.In the third testcase of the example, there are no letters that appear exactly twice. Thus, any rearrangement is valid. Including not changing the string at all. | 3
oelhl
abcdcba
ac
| hello ababcdc ac | 2 seconds | 256 megabytes | ['constructive algorithms', 'sortings', '*800'] |
E2. Cats on the Upgrade (hard version)time limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference between the easy and the hard versions are removal queries, they are present only in the hard version."Interplanetary Software, Inc." together with "Robots of Cydonia, Ltd." has developed and released robot cats. These electronic pets can meow, catch mice and entertain the owner in various ways.The developers from "Interplanetary Software, Inc." have recently decided to release a software update for these robots. After the update, the cats must solve the problems about bracket sequences. One of the problems is described below. First, we need to learn a bit of bracket sequence theory. Consider the strings that contain characters "(", ")" and ".". Call a string regular bracket sequence (RBS), if it can be transformed to an empty string by one or more operations of removing either single "." characters, or a continuous substring "()". For instance, the string "(()(.))" is an RBS, as it can be transformed to an empty string with the following sequence of removals: "(()(.))" \rightarrow "(()())" \rightarrow "(())" \rightarrow "()" \rightarrow "". We got an empty string, so the initial string was an RBS. At the same time, the string ")(" is not an RBS, as it is not possible to apply such removal operations to it.An RBS is simple if this RBS is not empty, doesn't start with ".", and doesn't end with ".".Denote the substring of the string s as its sequential subsegment. In particular, s[l\dots r] = s_ls_{l+1}\dots s_r, where s_i is the i-th character of the string s.Now, move on to the problem statement itself. You are given a string s, initially consisting of characters "(" and ")". You need to answer the following queries: Given two indices, l and r (1 \le l < r \le n). It's guaranteed that the l-th character is equal to "(", the r-th character is equal to ")", and the characters between them are equal to ".". Then the l-th and the r-th characters must be set to ".". Given two indices, l and r (1 \le l < r \le n), and it's guaranteed that the substring s[l\dots r] is a simple RBS. You need to find the number of substrings in s[l\dots r] such that they are simple RBS. In other words, find the number of index pairs i, j such that l \le i < j \le r and s[i\dots j] is a simple RBS. You are an employee in "Interplanetary Software, Inc." and you were given the task to teach the cats to solve the problem above, after the update.InputThe first line contains two integers n and q (2 \le n \le 3\cdot10^5, 1 \le q \le 3\cdot10^5), the length of the string, and the number of queries.The second line contains the string s, consisting of n characters "(" and ")".Each of the following q lines contains three integers t, l and r (t \in \{1, 2\}, 1 \le l < r \le n), the queries you need to answer. It is guaranteed that all the queries are valid and correspond to the problem statements.OutputFor each query, print a single integer in a separate line, the number of substrings that are simple RBS. The answers must be printed in the same order as the queries are specified in the input.ExampleInput
9 8
)(()())()
2 3 6
2 2 7
1 3 4
2 2 7
2 2 9
1 5 6
1 2 7
2 8 9
Output
3
4
2
4
1
NoteConsider the example test case.The answer to the first query is 3, as there are three suitable substrings: s[3\dots6], s[3\dots4] and s[5\dots6].The answer to the second query is 4. The substrings are s[3\dots6], s[3\dots4], s[5\dots6] and s[2\dots7].After the third query, the string becomes ")(..())()".The answer to the fourth query is 2. The substrings are s[5\dots6] and s[2\dots7]. Note that s[3\dots6] is not a simple RBS anymore, as it starts with ".".The answer to the fifth query is 4. The substrings are s[5\dots6], s[2\dots7], s[8\dots9] and s[2\dots9].After the sixth query, the string becomes ")(....)()".After the seventh query, the string becomes ")......()".The answer to the eighth query is 1. The substring is s[8\dots9]. | 9 8
)(()())()
2 3 6
2 2 7
1 3 4
2 2 7
2 2 9
1 5 6
1 2 7
2 8 9
| 3 4 2 4 1 | 6 seconds | 256 megabytes | ['binary search', 'data structures', 'dfs and similar', 'graphs', 'trees', '*2800'] |
E1. Cats on the Upgrade (easy version)time limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference between the easy and the hard versions are removal queries, they are present only in the hard version."Interplanetary Software, Inc." together with "Robots of Cydonia, Ltd." has developed and released robot cats. These electronic pets can meow, catch mice and entertain the owner in various ways.The developers from "Interplanetary Software, Inc." have recently decided to release a software update for these robots. After the update, the cats must solve the problems about bracket sequences. One of the problems is described below. First, we need to learn a bit of bracket sequence theory. Consider the strings that contain characters "(", ")" and ".". Call a string regular bracket sequence (RBS), if it can be transformed to an empty string by one or more operations of removing either single "." characters, or a continuous substring "()". For instance, the string "(()(.))" is an RBS, as it can be transformed to an empty string with the following sequence of removals: "(()(.))" \rightarrow "(()())" \rightarrow "(())" \rightarrow "()" \rightarrow "". We got an empty string, so the initial string was an RBS. At the same time, the string ")(" is not an RBS, as it is not possible to apply such removal operations to it.An RBS is simple if this RBS is not empty, doesn't start with ".", and doesn't end with ".".Denote the substring of the string s as its sequential subsegment. In particular, s[l\dots r] = s_ls_{l+1}\dots s_r, where s_i is the i-th character of the string s.Now, move on to the problem statement itself. You are given a string s, initially consisting of characters "(" and ")". You need to answer the queries of the following kind.Given two indices, l and r (1 \le l < r \le n), and it's guaranteed that the substring s[l\dots r] is a simple RBS. You need to find the number of substrings in s[l\dots r] such that they are simple RBS. In other words, find the number of index pairs i, j such that l \le i < j \le r and s[i\dots j] is a simple RBS.You are an employee in "Interplanetary Software, Inc." and you were given the task to teach the cats to solve the problem above, after the update.Note that the "." character cannot appear in the string in this version of the problem. It is only needed for the hard version.InputThe first line contains two integers n and q (2 \le n \le 3\cdot10^5, 1 \le q \le 3\cdot10^5), the length of the string, and the number of queries.The second line contains the string s, consisting of n characters "(" and ")".Each of the following q lines contains three integers t, l and r (t = 2, 1 \le l < r \le n), the queries you need to answer. It is guaranteed that all the queries are valid and correspond to the problem statements. Note that t is unused and always equal to two in this problem. It is required for the hard version of the problem.OutputFor each query, print a single integer in a separate line, the number of substrings that are simple RBS. The answers must be printed in the same order as the queries are specified in the input.ExampleInput
9 4
)(()())()
2 3 6
2 2 7
2 8 9
2 2 9
Output
3
4
1
6
NoteConsider the example test case.The answer to the first query is 3, as there are three suitable substrings: s[3\dots6], s[3\dots4] and s[5\dots6].The answer to the second query is 4. The substrings are s[3\dots6], s[3\dots4], s[5\dots6] and s[2\dots7].The answer to the third query is 1. The substring is s[8\dots9].The answer to the fourth query is 6. The substrings are s[3\dots6], s[3\dots4], s[5\dots6], s[2\dots7], s[8\dots9] and s[2\dots9]. | 9 4
)(()())()
2 3 6
2 2 7
2 8 9
2 2 9
| 3 4 1 6 | 6 seconds | 256 megabytes | ['brute force', 'data structures', 'dfs and similar', 'divide and conquer', 'dp', 'graphs', 'trees', '*2500'] |
D. Binary Spiderstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBinary Spiders are species of spiders that live on Mars. These spiders weave their webs to defend themselves from enemies.To weave a web, spiders join in pairs. If the first spider in pair has x legs, and the second spider has y legs, then they weave a web with durability x \oplus y. Here, \oplus means bitwise XOR.Binary Spiders live in large groups. You observe a group of n spiders, and the i-th spider has a_i legs.When the group is threatened, some of the spiders become defenders. Defenders are chosen in the following way. First, there must be at least two defenders. Second, any pair of defenders must be able to weave a web with durability at least k. Third, there must be as much defenders as possible.Scientists have researched the behaviour of Binary Spiders for a long time, and now they have a hypothesis that they can always choose the defenders in an optimal way, satisfying the conditions above. You need to verify this hypothesis on your group of spiders. So, you need to understand how many spiders must become defenders. You are not a Binary Spider, so you decided to use a computer to solve this problem.InputThe first line contains two integers n and k (2 \le n \le 3\cdot10^5, 0 \le k \le 2^{30} - 1), the amount of spiders in the group and the minimal allowed durability of a web.The second line contains n integers a_i (0 \le a_i \le 2^{30}-1) — the number of legs the i-th spider has.OutputIn the first line, print a single integer \ell (2 \le \ell \le n), the maximum possible amount of defenders.In the second line, print \ell integers b_i, separated by a single space (1 \le b_i \le n) — indices of spiders that will become defenders.If there exists more than one way to choose the defenders, print any of them.Unfortunately, it may appear that it's impossible to choose the defenders. In this case, print a single integer -1.ExamplesInput
6 8
2 8 4 16 10 14
Output
3
1 5 4
Input
6 1024
1 2 3 1 4 0
Output
-1
NoteConsider the examples above.In the first example, the group of spiders is illustrated on the picture below: We choose the two-legged, the ten-legged and the 16-legged spiders. It's not hard to see that each pair may weave a web with enough durability, as 2 \oplus 10 = 8 \ge 8, 2 \oplus 16 = 18 \ge 8 and 10 \oplus 16 = 26 \ge 8.This is not the only way, as you can also choose, for example, the spiders with indices 3, 4, and 6.In the second example, no pair of spiders can weave the web with durability 1024 or more, so the answer is -1. | 6 8
2 8 4 16 10 14
| 3 1 5 4 | 2 seconds | 256 megabytes | ['bitmasks', 'data structures', 'implementation', 'math', 'sortings', 'trees', '*2300'] |
C. Road Optimizationtime limit per test3 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputThe Government of Mars is not only interested in optimizing space flights, but also wants to improve the road system of the planet.One of the most important highways of Mars connects Olymp City and Kstolop, the capital of Cydonia. In this problem, we only consider the way from Kstolop to Olymp City, but not the reverse path (i. e. the path from Olymp City to Kstolop).The road from Kstolop to Olymp City is \ell kilometers long. Each point of the road has a coordinate x (0 \le x \le \ell), which is equal to the distance from Kstolop in kilometers. So, Kstolop is located in the point with coordinate 0, and Olymp City is located in the point with coordinate \ell.There are n signs along the road, i-th of which sets a speed limit a_i. This limit means that the next kilometer must be passed in a_i minutes and is active until you encounter the next along the road. There is a road sign at the start of the road (i. e. in the point with coordinate 0), which sets the initial speed limit.If you know the location of all the signs, it's not hard to calculate how much time it takes to drive from Kstolop to Olymp City. Consider an example: Here, you need to drive the first three kilometers in five minutes each, then one kilometer in eight minutes, then four kilometers in three minutes each, and finally the last two kilometers must be passed in six minutes each. Total time is 3\cdot 5 + 1\cdot 8 + 4\cdot 3 + 2\cdot 6 = 47 minutes.To optimize the road traffic, the Government of Mars decided to remove no more than k road signs. It cannot remove the sign at the start of the road, otherwise, there will be no limit at the start. By removing these signs, the Government also wants to make the time needed to drive from Kstolop to Olymp City as small as possible.The largest industrial enterprises are located in Cydonia, so it's the priority task to optimize the road traffic from Olymp City. So, the Government of Mars wants you to remove the signs in the way described above.InputThe first line contains three integers n, \ell, k (1 \le n \le 500, 1 \le \ell \le 10^5, 0 \le k \le n-1), the amount of signs on the road, the distance between the cities and the maximal number of signs you may remove.The second line contains n integers d_i (d_1 = 0, d_i < d_{i+1}, 0 \le d_i \le \ell - 1) — coordinates of all signs.The third line contains n integers a_i (1 \le a_i \le 10^4) — speed limits.OutputPrint a single integer — minimal possible time to drive from Kstolop to Olymp City in minutes, if you remove no more than k road signs.ExamplesInput
4 10 0
0 3 4 8
5 8 3 6
Output
47
Input
4 10 2
0 3 4 8
5 8 3 6
Output
38
NoteIn the first example, you cannot remove the signs. So the answer is 47, as it's said in the statements above.In the second example, you may remove the second and the fourth sign. In this case, you need to drive four kilometers in 4\cdot5 = 20 minutes, and then six kilometers in 6\cdot3 = 18, so the total time is 4\cdot5 + 6\cdot3 = 38 minutes. | 4 10 0
0 3 4 8
5 8 3 6
| 47 | 3 seconds | 128 megabytes | ['dp', '*1700'] |
B. Elementary Particlestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMartians are actively engaged in interplanetary trade. Olymp City, the Martian city known for its spaceport, has become a place where goods from all the corners of our Galaxy come. To deliver even more freight from faraway planets, Martians need fast spaceships.A group of scientists conducts experiments to build a fast engine for the new spaceship. In the current experiment, there are n elementary particles, the i-th of them has type a_i.Denote a subsegment of the particle sequence (a_1, a_2, \dots, a_n) as a sequence (a_l, a_{l+1}, \dots, a_r) for some left bound l and right bound r (1 \le l \le r \le n). For instance, the sequence (1\ 4\ 2\ 8\ 5\ 7) for l=2 and r=4 has the sequence (4\ 2\ 8) as a subsegment. Two subsegments are considered different if at least one bound of those subsegments differs.Note that the subsegments can be equal as sequences but still considered different. For example, consider the sequence (1\ 1\ 1\ 1\ 1) and two of its subsegments: one with l=1 and r=3 and another with l=2 and r=4. Both subsegments are equal to (1\ 1\ 1), but still considered different, as their left and right bounds differ.The scientists want to conduct a reaction to get two different subsegments of the same length. Denote this length k. The resulting pair of subsegments must be harmonious, i. e. for some i (1 \le i \le k) it must be true that the types of particles on the i-th position are the same for these two subsegments. For example, the pair (1\ 7\ 3) and (4\ 7\ 8) is harmonious, as both subsegments have 7 on the second position. The pair (1\ 2\ 3) and (3\ 1\ 2) is not harmonious.The longer are harmonious subsegments, the more chances for the scientists to design a fast engine. So, they asked you to calculate the maximal possible length of harmonious pair made of different subsegments.InputThe first line contains an integer t (1 \le t \le 100) — the number of test cases. The following are descriptions of the test cases.The first line contains an integer n (2 \le n \le 150\,000) — the amount of elementary particles in the sequence.The second line contains n integers a_i (1 \le a_i \le 150\,000) — types of elementary particles.It is guaranteed that the sum of n over all test cases does not exceed 3\cdot10^5.OutputFor each test, print a single integer, maximal possible length of harmonious pair made of different subsegments. If such pair does not exist, print -1 instead.ExampleInput
473 1 5 2 1 3 461 1 1 1 1 161 4 2 8 5 7215 15Output
4
5
-1
1
NoteThe first test case is shown on the picture below: As you can see from it, you may choose the subsegments (2\ 1\ 3\ 4) and (3\ 1\ 5\ 2), which are a harmonious pair. Their length is equal to 4, so the answer is 4.In the second test case, you need to take two subsegments: one with l=1 and r=5, and one with l=2 and r=6. It's not hard to observe that these segments are a harmonious pair and considered different even though they are both equal to (1\ 1\ 1\ 1\ 1).In the third test case, you cannot make a harmonious pair, so the answer is -1. | 473 1 5 2 1 3 461 1 1 1 1 161 4 2 8 5 7215 15 | 4 5 -1 1 | 2 seconds | 256 megabytes | ['brute force', 'greedy', 'sortings', '*1100'] |
A. Ancient Civilizationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMartian scientists explore Ganymede, one of Jupiter's numerous moons. Recently, they have found ruins of an ancient civilization. The scientists brought to Mars some tablets with writings in a language unknown to science.They found out that the inhabitants of Ganymede used an alphabet consisting of two letters, and each word was exactly \ell letters long. So, the scientists decided to write each word of this language as an integer from 0 to 2^{\ell} - 1 inclusively. The first letter of the alphabet corresponds to zero bit in this integer, and the second letter corresponds to one bit.The same word may have various forms in this language. Then, you need to restore the initial form. The process of doing it is described below.Denote the distance between two words as the amount of positions, in which these words differ. For example, the distance between 1001_2 and 1100_2 (in binary) is equal to two, as these words have different letters in the second and the fourth positions, counting from left to right. Further, denote the distance between words x and y as d(x, y).Let the word have n forms, the i-th of which is described with an integer x_i. All the x_i are not necessarily different, as two various forms of the word can be written the same. Consider some word y. Then, closeness of the word y is equal to the sum of distances to each of the word forms, i. e. the sum d(x_i, y) over all 1 \le i \le n.The initial form is the word y with minimal possible nearness.You need to help the scientists and write the program which finds the initial form of the word given all its known forms. Note that the initial form is not necessarily equal to any of the n given forms.InputThe first line contains an integer t (1 \le t \le 100) — the number of test cases. The following are descriptions of the test cases.The first line contains two integers n and \ell (1 \le n \le 100, 1 \le \ell \le 30) — the amount of word forms, and the number of letters in one word.The second line contains n integers x_i (0 \le x_i \le 2^\ell - 1) — word forms. The integers are not necessarily different.OutputFor each test, print a single integer, the initial form of the word, i. e. such y (0 \le y \le 2^\ell - 1) that the sum d(x_i, y) over all 1 \le i \le n is minimal possible. Note that y can differ from all the integers x_i.If there are multiple ways to restore the initial form, print any.ExampleInput
7
3 5
18 9 21
3 5
18 18 18
1 1
1
5 30
1 2 3 4 5
6 10
99 35 85 46 78 55
2 1
0 1
8 8
5 16 42 15 83 65 78 42
Output
17
18
1
1
39
0
2
NoteIn the first test case, the words can be written as x_1 = 10010_2, x_2 = 01001_2 and x_3 = 10101_2 in binary. Let y = 10001_2. Then, d(x_1, y) = 2 (the difference is in the fourth and the fifth positions), d(x_2, y) = 2 (the difference is in the first and the second positions), d(x_3, y) = 1 (the difference is in the third position). So, the closeness is 2 + 2 + 1 = 5. It can be shown that you cannot achieve smaller closeness.In the second test case, all the forms are equal to 18 (10010_2 in binary), so the initial form is also 18. It's easy to see that closeness is equal to zero in this case. | 7
3 5
18 9 21
3 5
18 18 18
1 1
1
5 30
1 2 3 4 5
6 10
99 35 85 46 78 55
2 1
0 1
8 8
5 16 42 15 83 65 78 42
| 17 18 1 1 39 0 2 | 1 second | 256 megabytes | ['bitmasks', 'greedy', 'math', '*800'] |
G. MinOr Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Vlad has been carried away by spanning trees, so his friends, without hesitation, gave him a connected weighted undirected graph of n vertices and m edges for his birthday.Vlad defined the ority of a spanning tree as the bitwise OR of all its weights, and now he is interested in what is the minimum possible ority that can be achieved by choosing a certain spanning tree. A spanning tree is a connected subgraph of a given graph that does not contain cycles.In other words, you want to keep n-1 edges so that the graph remains connected and the bitwise OR weights of the edges are as small as possible. You have to find the minimum bitwise OR itself.InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases in the input.An empty line is written in front of each test case.This is followed by two numbers n and m (3 \le n \le 2 \cdot 10^5, n - 1 \le m \le 2 \cdot 10^5) — the number of vertices and edges of the graph, respectively.The next m lines contain the description of the edges. Line i contains three numbers v_i, u_i and w_i (1 \le v_i, u_i \le n, 1 \le w_i \le 10^9, v_i \neq u_i) — the vertices that the edge connects and its weight.It is guaranteed that the sum m and the sum n over all test cases does not exceed 2 \cdot 10^5 and each test case contains a connected graph.OutputPrint t lines, each of which contains the answer to the corresponding set of input data — the minimum possible spanning tree ority.ExampleInput
3
3 3
1 2 1
2 3 2
1 3 2
5 7
4 2 7
2 5 8
3 4 2
3 2 1
2 4 2
4 1 2
1 2 2
3 4
1 2 1
2 3 2
1 3 3
3 1 4
Output
2
10
3
Note Graph from the first test case. Ority of this tree equals to 2 or 2 = 2 and it's minimal. Without excluding edge with weight 1 ority is 1 or 2 = 3. | 3
3 3
1 2 1
2 3 2
1 3 2
5 7
4 2 7
2 5 8
3 4 2
3 2 1
2 4 2
4 1 2
1 2 2
3 4
1 2 1
2 3 2
1 3 3
3 1 4
| 2 10 3 | 2 seconds | 256 megabytes | ['bitmasks', 'dfs and similar', 'dsu', 'graphs', 'greedy', '*1900'] |
F. Interacdive Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We decided to play a game with you and guess the number x (1 \le x < n), where you know the number n.You can make queries like this: + c: this command assigns x = x + c (1 \le c < n) and then returns you the value \lfloor\frac{x}{n}\rfloor (x divide by n and round down).You win if you guess the current number with no more than 10 queries.InteractionThe interaction begins by reading an integer n (2 < n \le 1000), which is written in the input data on its own line.Then you can make no more than 10 queries. To make a query, print on a separate line: + c: this command will assign x = x + c (1 \le c < n) and then print \lfloor\frac{x}{n}\rfloor (divide x by n and round down) on a separate line. Print the answer, like the queries, on a separate line. The answer doesn't count in number of queries. To output it, use the following format: ! x: the current value of x. After that, your program should exit.You have to use a flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java — System.out.flush(), in Pascal — flush(output) and in Python — sys.stdout.flush().Note that the interactor is not responsive.To make a hack, use the following format: a single line must contain two numbers x and n, separated by a space.ExamplesInput
3
1Output
+ 1
! 3Input
5
0
0
1
Output
+ 1
+ 1
+ 1
! 5
Input
10
0
0
1
2Output
+ 2
+ 2
+ 3
+ 8
! 20NoteIn the first sample initially x = 2. After the first query x = 3, \lfloor\frac{x}{n}\rfloor = 1.In the second sample also initially x = 2. After the first query x = 3, \lfloor\frac{x}{n}\rfloor = 0. After the second query x = 4, \lfloor\frac{x}{n}\rfloor = 0. After the third query x=5, \lfloor\frac{x}{n}\rfloor = 1. | 3
1 | + 1 ! 3 | 1 second | 256 megabytes | ['binary search', 'constructive algorithms', 'interactive', '*2000'] |
E. Masha-forgetfultime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha meets a new friend and learns his phone number — s. She wants to remember it as soon as possible. The phone number — is a string of length m that consists of digits from 0 to 9. The phone number may start with 0.Masha already knows n phone numbers (all numbers have the same length m). It will be easier for her to remember a new number if the s is represented as segments of numbers she already knows. Each such segment must be of length at least 2, otherwise there will be too many segments and Masha will get confused.For example, Masha needs to remember the number: s = '12345678' and she already knows n = 4 numbers: '12340219', '20215601', '56782022', '12300678'. You can represent s as a 3 segment: '1234' of number one, '56' of number two, and '78' of number three. There are other ways to represent s.Masha asks you for help, she asks you to break the string s into segments of length 2 or more of the numbers she already knows. If there are several possible answers, print any of them.InputThe first line of input data contains an integer t (1 \le t \le 10^4) —the number of test cases.Before each test case there is a blank line. Then there is a line containing integers n and m (1 \le n, m \le 10^3) —the number of phone numbers that Masha knows and the number of digits in each phone number. Then follow n line, i-th of which describes the i-th number that Masha knows. The next line contains the phone number of her new friend s.Among the given n+1 phones, there may be duplicates (identical phones).It is guaranteed that the sum of n \cdot m (n multiplied by m) values over all input test cases does not exceed 10^6.OutputYou need to print the answers to t test cases. The first line of the answer should contain one number k, corresponding to the number of segments into which you split the phone number s. Print -1 if you cannot get such a split.If the answer is yes, then follow k lines containing triples of numbers l, r, i. Such triplets mean that the next r-l+1 digits of number s are equal to a segment (substring) with boundaries [l, r] of the phone under number i. Both the phones and the digits in them are numbered from 1. Note that r-l+1 \ge 2 for all k lines.ExampleInput
5
4 8
12340219
20215601
56782022
12300678
12345678
2 3
134
126
123
1 4
1210
1221
4 3
251
064
859
957
054
4 7
7968636
9486033
4614224
5454197
9482268
Output
3
1 4 1
5 6 2
3 4 3
-1
2
1 2 1
2 3 1
-1
3
1 3 2
5 6 3
3 4 1
NoteThe example from the statement.In the second case, it is impossible to represent by segments of known numbers of length 2 or more.In the third case, you can get the segments '12' and '21' from the first phone number. | 5
4 8
12340219
20215601
56782022
12300678
12345678
2 3
134
126
123
1 4
1210
1221
4 3
251
064
859
957
054
4 7
7968636
9486033
4614224
5454197
9482268
| 3 1 4 1 5 6 2 3 4 3 -1 2 1 2 1 2 3 1 -1 3 1 3 2 5 6 3 3 4 1 | 3 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'dp', 'hashing', 'implementation', 'strings', '*2000'] |
D. Palindromes Coloringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a string s consisting of lowercase Latin alphabet letters. You can color some letters in colors from 1 to k. It is not necessary to paint all the letters. But for each color, there must be a letter painted in that color.Then you can swap any two symbols painted in the same color as many times as you want. After that, k strings will be created, i-th of them will contain all the characters colored in the color i, written in the order of their sequence in the string s.Your task is to color the characters of the string so that all the resulting k strings are palindromes, and the length of the shortest of these k strings is as large as possible.Read the note for the first test case of the example if you need a clarification.Recall that a string is a palindrome if it reads the same way both from left to right and from right to left. For example, the strings abacaba, cccc, z and dxd are palindromes, but the strings abab and aaabaa — are not.InputThe first line of input data contains a single integer t (1 \le t \le 10^4) — the number of input data sets in the test. The descriptions of the input data sets follow.The first line of the description of each input data set contains two integers n and k (1 \le k \le n \le 2 \cdot 10^5) — the length of the string and the number of colors in which its letters can be painted. The second line of the description of each input data set contains a string s of length n consisting of lowercase letters of the Latin alphabet.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each set of input data, output a single integer — the maximum length of the shortest palindrome string that can be obtained.ExampleInput
10
8 2
bxyaxzay
6 3
aaaaaa
6 1
abcdef
6 6
abcdef
3 2
dxd
11 2
abcabcabcac
6 6
sipkic
7 2
eatoohd
3 1
llw
6 2
bfvfbv
Output
3
2
1
1
1
5
1
1
3
3
Note In the first test case, s="bxyaxzay", k=2. We use indices in the string from 1 to 8. The following coloring will work: \mathtt{\mathbf{\color{red}{b}\color{blue}{xy}\color{red}{a}\color{blue}{x}z\color{red}{a}\color{blue}{y}}} (the letter z remained uncolored). After painting: swap two red characters (with the indices 1 and 4), we get \mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}; swap two blue characters (with the indices 5 and 8), we get \mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{y}z\color{red}{a}\color{blue}{x}}}. Now, for each of the two colors we write out the corresponding characters from left to right, we get two strings \mathtt{\mathbf{\color{red}{aba}}} and \mathtt{\mathbf{\color{blue}{xyyx}}}. Both of them are palindromes, the length of the shortest is 3. It can be shown that the greatest length of the shortest palindrome cannot be achieved. In the second set of input data, the following coloring is suitable: [1, 1, 2, 2, 3, 3]. There is no need to swap characters. Both received strings are equal to aa, they are palindromes and their length is 2. In the third set of input data, you can color any character and take it into a string. In the fourth set of input data, you can color the ith character in the color i. In the fifth set of input data can be colored in each of the colors of one character. In the sixth set of input data, the following coloring is suitable: [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0]. Rearrange the characters so as to get the palindromes abcba and acbca. | 10
8 2
bxyaxzay
6 3
aaaaaa
6 1
abcdef
6 6
abcdef
3 2
dxd
11 2
abcabcabcac
6 6
sipkic
7 2
eatoohd
3 1
llw
6 2
bfvfbv
| 3 2 1 1 1 5 1 1 3 3 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'sortings', 'strings', '*1400'] |
C. Division by Two and Permutationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n positive integers. You can perform operations on it.In one operation you can replace any element of the array a_i with \lfloor \frac{a_i}{2} \rfloor, that is, by an integer part of dividing a_i by 2 (rounding down).See if you can apply the operation some number of times (possible 0) to make the array a become a permutation of numbers from 1 to n —that is, so that it contains all numbers from 1 to n, each exactly once.For example, if a = [1, 8, 25, 2], n = 4, then the answer is yes. You could do the following: Replace 8 with \lfloor \frac{8}{2} \rfloor = 4, then a = [1, 4, 25, 2]. Replace 25 with \lfloor \frac{25}{2} \rfloor = 12, then a = [1, 4, 12, 2]. Replace 12 with \lfloor \frac{12}{2} \rfloor = 6, then a = [1, 4, 6, 2]. Replace 6 with \lfloor \frac{6}{2} \rfloor = 3, then a = [1, 4, 3, 2]. InputThe first line of input data contains an integer t (1 \le t \le 10^4) —the number of test cases.Each test case contains exactly two lines. The first one contains an integer n (1 \le n \le 50), the second one contains integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).OutputFor each test case, output on a separate line: YES if you can make the array a become a permutation of numbers from 1 to n, NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).ExampleInput
6
4
1 8 25 2
2
1 1
9
9 8 3 4 2 7 1 5 6
3
8 2 1
4
24 7 16 7
5
22 6 22 4 22
Output
YES
NO
YES
NO
NO
YES
NoteThe first test case is explained in the text of the problem statement.In the second test case, it is not possible to get a permutation. | 6
4
1 8 25 2
2
1 1
9
9 8 3 4 2 7 1 5 6
3
8 2 1
4
24 7 16 7
5
22 6 22 4 22
| YES NO YES NO NO YES | 3 seconds | 256 megabytes | ['constructive algorithms', 'flows', 'graph matchings', 'greedy', 'math', '*1100'] |
B. Make APtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has 3 positive integers a, b and c. He can perform the following operation exactly once. Choose a positive integer m and multiply exactly one of the integers a, b or c by m. Can Polycarp make it so that after performing the operation, the sequence of three numbers a, b, c (in this order) forms an arithmetic progression? Note that you cannot change the order of a, b and c.Formally, a sequence x_1, x_2, \dots, x_n is called an arithmetic progression (AP) if there exists a number d (called "common difference") such that x_{i+1}=x_i+d for all i from 1 to n-1. In this problem, n=3.For example, the following sequences are AP: [5, 10, 15], [3, 2, 1], [1, 1, 1], and [13, 10, 7]. The following sequences are not AP: [1, 2, 4], [0, 1, 0] and [1, 3, 2].You need to answer t independent test cases.InputThe first line contains the number t (1 \le t \le 10^4) — the number of test cases.Each of the following t lines contains 3 integers a, b, c (1 \le a, b, c \le 10^8).OutputFor each test case print "YES" (without quotes) if Polycarp can choose a positive integer m and multiply exactly one of the integers a, b or c by m to make [a, b, c] be an arithmetic progression. Print "NO" (without quotes) otherwise.You can print YES and NO in any (upper or lower) case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer).ExampleInput
11
10 5 30
30 5 10
1 2 3
1 6 3
2 6 3
1 1 1
1 1 2
1 1 3
1 100000000 1
2 1 1
1 2 2
Output
YES
YES
YES
YES
NO
YES
NO
YES
YES
NO
YES
NoteIn the first and second test cases, you can choose the number m=4 and multiply the second number (b=5) by 4.In the first test case the resulting sequence will be [10, 20, 30]. This is an AP with a difference d=10.In the second test case the resulting sequence will be [30, 20, 10]. This is an AP with a difference d=-10.In the third test case, you can choose m=1 and multiply any number by 1. The resulting sequence will be [1, 2, 3]. This is an AP with a difference d=1.In the fourth test case, you can choose m=9 and multiply the first number (a=1) by 9. The resulting sequence will be [9, 6, 3]. This is an AP with a difference d=-3.In the fifth test case, it is impossible to make an AP. | 11
10 5 30
30 5 10
1 2 3
1 6 3
2 6 3
1 1 1
1 1 2
1 1 3
1 100000000 1
2 1 1
1 2 2
| YES YES YES YES NO YES NO YES YES NO YES | 2 seconds | 256 megabytes | ['implementation', 'math', '*900'] |
A. Plus One on the Subsettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp got an array of integers a[1 \dots n] as a gift. Now he wants to perform a certain number of operations (possibly zero) so that all elements of the array become the same (that is, to become a_1=a_2=\dots=a_n). In one operation, he can take some indices in the array and increase the elements of the array at those indices by 1.For example, let a=[4,2,1,6,2]. He can perform the following operation: select indices 1, 2, and 4 and increase elements of the array in those indices by 1. As a result, in one operation, he can get a new state of the array a=[5,3,1,7,2].What is the minimum number of operations it can take so that all elements of the array become equal to each other (that is, to become a_1=a_2=\dots=a_n)?InputThe first line of the input contains a single integer t (1 \le t \le 10^4) — the number of test cases in the test.The following are descriptions of the input test cases.The first line of the description of each test case contains one integer n (1 \le n \le 50) — the array a.The second line of the description of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — elements of the array a.OutputFor each test case, print one integer — the minimum number of operations to make all elements of the array a equal.ExampleInput
3
6
3 4 2 4 1 2
3
1000 1002 998
2
12 11
Output
3
4
1
NoteFirst test case: a=[3,4,2,4,1,2] take a_3, a_5 and perform an operation plus one on them, as a result we get a=[3,4,3,4,2,2]. a=[3,4,3,4,2,2] we take a_1, a_5, a_6 and perform an operation on them plus one, as a result we get a=[4,4,3,4,3,3]. a=[4,4,3,4,3,3] we take a_3, a_5, a_6 and perform an operation on them plus one, as a result we get a=[4,4,4,4,4,4]. There are other sequences of 3 operations, after the application of which all elements become equal.Second test case: a=[1000,1002,998] 2 times we take a_1, a_3 and perform an operation plus one on them, as a result we get a=[1002,1002,1000]. a=[1002,1002,1000] also take a_3 2 times and perform an operation plus one on it, as a result we get a=[1002,1002,1002]. Third test case: a=[12,11] take a_2 and perform an operation plus one on it, as a result we get a=[12,12]. | 3
6
3 4 2 4 1 2
3
1000 1002 998
2
12 11
| 3 4 1 | 2 seconds | 256 megabytes | ['math', '*800'] |
E. Middle Duplicationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA binary tree of n nodes is given. Nodes of the tree are numbered from 1 to n and the root is the node 1. Each node can have no child, only one left child, only one right child, or both children. For convenience, let's denote l_u and r_u as the left and the right child of the node u respectively, l_u = 0 if u does not have the left child, and r_u = 0 if the node u does not have the right child.Each node has a string label, initially is a single character c_u. Let's define the string representation of the binary tree as the concatenation of the labels of the nodes in the in-order. Formally, let f(u) be the string representation of the tree rooted at the node u. f(u) is defined as follows: f(u) = \begin{cases} \texttt{<empty string>}, & \text{if }u = 0; \\ f(l_u) + c_u + f(r_u) & \text{otherwise}, \end{cases} where + denotes the string concatenation operation.This way, the string representation of the tree is f(1).For each node, we can duplicate its label at most once, that is, assign c_u with c_u + c_u, but only if u is the root of the tree, or if its parent also has its label duplicated.You are given the tree and an integer k. What is the lexicographically smallest string representation of the tree, if we can duplicate labels of at most k nodes?A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. InputThe first line contains two integers n and k (1 \le k \le n \le 2 \cdot 10^5).The second line contains a string c of n lower-case English letters, where c_i is the initial label of the node i for 1 \le i \le n. Note that the given string c is not the initial string representation of the tree.The i-th of the next n lines contains two integers l_i and r_i (0 \le l_i, r_i \le n). If the node i does not have the left child, l_i = 0, and if the node i does not have the right child, r_i = 0.It is guaranteed that the given input forms a binary tree, rooted at 1.OutputPrint a single line, containing the lexicographically smallest string representation of the tree if at most k nodes have their labels duplicated.ExamplesInput
4 3
abab
2 3
0 0
0 4
0 0
Output
baaaabInput
8 2
kadracyn
2 5
3 4
0 0
0 0
6 8
0 7
0 0
0 0
Output
daarkkcyanInput
8 3
kdaracyn
2 5
0 3
0 4
0 0
6 8
0 7
0 0
0 0
Output
darkcyanNoteThe images below present the tree for the examples. The number in each node is the node number, while the subscripted letter is its label. To the right is the string representation of the tree, with each letter having the same color as the corresponding node.Here is the tree for the first example. Here we duplicated the labels of nodes 1 and 3. We should not duplicate the label of node 2 because it would give us the string "bbaaab", which is lexicographically greater than "baaaab". In the second example, we can duplicate the labels of nodes 1 and 2. Note that only duplicating the label of the root will produce a worse result than the initial string. In the third example, we should not duplicate any character at all. Even though we would want to duplicate the label of the node 3, by duplicating it we must also duplicate the label of the node 2, which produces a worse result. There is no way to produce string "darkkcyan" from a tree with the initial string representation "darkcyan" :(. | 4 3
abab
2 3
0 0
0 4
0 0
| baaaab | 1 second | 256 megabytes | ['data structures', 'dfs and similar', 'greedy', 'strings', 'trees', '*2500'] |
D. Robot Cleaner Revisittime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe statement of this problem shares a lot with problem A. The differences are that in this problem, the probability is introduced, and the constraint is different.A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of n rows and m columns. The rows of the floor are numbered from 1 to n from top to bottom, and columns of the floor are numbered from 1 to m from left to right. The cell on the intersection of the r-th row and the c-th column is denoted as (r,c). The initial position of the robot is (r_b, c_b).In one second, the robot moves by dr rows and dc columns, that is, after one second, the robot moves from the cell (r, c) to (r + dr, c + dc). Initially dr = 1, dc = 1. If there is a vertical wall (the left or the right walls) in the movement direction, dc is reflected before the movement, so the new value of dc is -dc. And if there is a horizontal wall (the upper or lower walls), dr is reflected before the movement, so the new value of dr is -dr.Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at (r_d, c_d). The job of the robot is to clean that dirty cell. After a lot of testings in problem A, the robot is now broken. It cleans the floor as described above, but at each second the cleaning operation is performed with probability \frac p {100} only, and not performed with probability 1 - \frac p {100}. The cleaning or not cleaning outcomes are independent each second.Given the floor size n and m, the robot's initial position (r_b, c_b) and the dirty cell's position (r_d, c_d), find the expected time for the robot to do its job.It can be shown that the answer can be expressed as an irreducible fraction \frac x y, where x and y are integers and y \not \equiv 0 \pmod{10^9 + 7} . Output the integer equal to x \cdot y^{-1} \bmod (10^9 + 7). In other words, output such an integer a that 0 \le a < 10^9 + 7 and a \cdot y \equiv x \pmod {10^9 + 7}.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10). Description of the test cases follows.A test case consists of only one line, containing n, m, r_b, c_b, r_d, c_d, and p (4 \le n \cdot m \le 10^5, n, m \ge 2, 1 \le r_b, r_d \le n, 1 \le c_b, c_d \le m, 1 \le p \le 99) — the sizes of the room, the initial position of the robot, the position of the dirt cell and the probability of cleaning in percentage.OutputFor each test case, print a single integer — the expected time for the robot to clean the dirty cell, modulo 10^9 + 7.ExampleInput
6
2 2 1 1 2 1 25
3 3 1 2 2 2 25
10 10 1 1 10 10 75
10 10 10 10 1 1 75
5 5 1 3 2 2 10
97 98 3 5 41 43 50
Output
3
3
15
15
332103349
99224487
NoteIn the first test case, the robot has the opportunity to clean the dirty cell every second. Using the geometric distribution, we can find out that with the success rate of 25\%, the expected number of tries to clear the dirty cell is \frac 1 {0.25} = 4. But because the first moment the robot has the opportunity to clean the cell is before the robot starts moving, the answer is 3. Illustration for the first example. The blue arc is the robot. The red star is the target dirt cell. The purple square is the initial position of the robot. Each second the robot has an opportunity to clean a row and a column, denoted by yellow stripes. In the second test case, the board size and the position are different, but the robot still has the opportunity to clean the dirty cell every second, and it has the same probability of cleaning. Therefore the answer is the same as in the first example. Illustration for the second example. The third and the fourth case are almost the same. The only difference is that the position of the dirty cell and the robot are swapped. But the movements in both cases are identical, hence the same result. | 6
2 2 1 1 2 1 25
3 3 1 2 2 2 25
10 10 1 1 10 10 75
10 10 10 10 1 1 75
5 5 1 3 2 2 10
97 98 3 5 41 43 50
| 3 3 15 15 332103349 99224487 | 3 seconds | 256 megabytes | ['implementation', 'math', 'probabilities', '*2300'] |
C. Balanced Stone Heapstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n heaps of stone. The i-th heap has h_i stones. You want to change the number of stones in the heap by performing the following process once: You go through the heaps from the 3-rd heap to the n-th heap, in this order. Let i be the number of the current heap. You can choose a number d (0 \le 3 \cdot d \le h_i), move d stones from the i-th heap to the (i - 1)-th heap, and 2 \cdot d stones from the i-th heap to the (i - 2)-th heap. So after that h_i is decreased by 3 \cdot d, h_{i - 1} is increased by d, and h_{i - 2} is increased by 2 \cdot d. You can choose different or same d for different operations. Some heaps may become empty, but they still count as heaps. What is the maximum number of stones in the smallest heap after the process?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 2\cdot 10^5). Description of the test cases follows.The first line of each test case contains a single integer n (3 \le n \le 2 \cdot 10^5).The second lines of each test case contains n integers h_1, h_2, h_3, \ldots, h_n (1 \le h_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print the maximum number of stones that the smallest heap can contain.ExampleInput
4
4
1 2 10 100
4
100 100 100 1
5
5 1 1 1 8
6
1 2 3 4 5 6
Output
7
1
1
3
NoteIn the first test case, the initial heap sizes are [1, 2, 10, 100]. We can move the stones as follows. move 3 stones and 6 from the 3-rd heap to the 2-nd and 1 heap respectively. The heap sizes will be [7, 5, 1, 100]; move 6 stones and 12 stones from the last heap to the 3-rd and 2-nd heap respectively. The heap sizes will be [7, 17, 7, 82]. In the second test case, the last heap is 1, and we can not increase its size.In the third test case, it is better not to move any stones.In the last test case, the final achievable configuration of the heaps can be [3, 5, 3, 4, 3, 3]. | 4
4
1 2 10 100
4
100 100 100 1
5
5 1 1 1 8
6
1 2 3 4 5 6
| 7 1 1 3 | 1 second | 256 megabytes | ['binary search', 'greedy', '*1600'] |
B. Game on Rangestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob play the following game. Alice has a set S of disjoint ranges of integers, initially containing only one range [1, n]. In one turn, Alice picks a range [l, r] from the set S and asks Bob to pick a number in the range. Bob chooses a number d (l \le d \le r). Then Alice removes [l, r] from S and puts into the set S the range [l, d - 1] (if l \le d - 1) and the range [d + 1, r] (if d + 1 \le r). The game ends when the set S is empty. We can show that the number of turns in each game is exactly n.After playing the game, Alice remembers all the ranges [l, r] she picked from the set S, but Bob does not remember any of the numbers that he picked. But Bob is smart, and he knows he can find out his numbers d from Alice's ranges, and so he asks you for help with your programming skill.Given the list of ranges that Alice has picked ([l, r]), for each range, help Bob find the number d that Bob has picked.We can show that there is always a unique way for Bob to choose his number for a list of valid ranges picked by Alice.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 1000).Each of the next n lines contains two integers l and r (1 \le l \le r \le n), denoting the range [l, r] that Alice picked at some point.Note that the ranges are given in no particular order.It is guaranteed that the sum of n over all test cases does not exceed 1000, and the ranges for each test case are from a valid game.OutputFor each test case print n lines. Each line should contain three integers l, r, and d, denoting that for Alice's range [l, r] Bob picked the number d.You can print the lines in any order. We can show that the answer is unique.It is not required to print a new line after each test case. The new lines in the output of the example are for readability only. ExampleInput
4
1
1 1
3
1 3
2 3
2 2
6
1 1
3 5
4 4
3 6
4 5
1 6
5
1 5
1 2
4 5
2 2
4 4
Output
1 1 1
1 3 1
2 2 2
2 3 3
1 1 1
3 5 3
4 4 4
3 6 6
4 5 5
1 6 2
1 5 3
1 2 1
4 5 5
2 2 2
4 4 4
NoteIn the first test case, there is only 1 range [1, 1]. There was only one range [1, 1] for Alice to pick, and there was only one number 1 for Bob to pick.In the second test case, n = 3. Initially, the set contains only one range [1, 3]. Alice picked the range [1, 3]. Bob picked the number 1. Then Alice put the range [2, 3] back to the set, which after this turn is the only range in the set. Alice picked the range [2, 3]. Bob picked the number 3. Then Alice put the range [2, 2] back to the set. Alice picked the range [2, 2]. Bob picked the number 2. The game ended. In the fourth test case, the game was played with n = 5. Initially, the set contains only one range [1, 5]. The game's turn is described in the following table. Game turnAlice's picked rangeBob's picked numberThe range set afterBefore the game start \{ [1, 5] \} 1[1, 5]3 \{ [1, 2], [4, 5] \}2[1, 2]1 \{ [2, 2], [4, 5] \} 3[4, 5]5 \{ [2, 2], [4, 4] \} 4[2, 2]2 \{ [4, 4] \} 5[4, 4]4 \{ \} (empty set) | 4
1
1 1
3
1 3
2 3
2 2
6
1 1
3 5
4 4
3 6
4 5
1 6
5
1 5
1 2
4 5
2 2
4 4
| 1 1 1 1 3 1 2 2 2 2 3 3 1 1 1 3 5 3 4 4 4 3 6 6 4 5 5 1 6 2 1 5 3 1 2 1 4 5 5 2 2 2 4 4 4 | 1 second | 256 megabytes | ['brute force', 'dfs and similar', 'implementation', 'sortings', '*1100'] |
A. Robot Cleanertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of n rows and m columns. The rows of the floor are numbered from 1 to n from top to bottom, and columns of the floor are numbered from 1 to m from left to right. The cell on the intersection of the r-th row and the c-th column is denoted as (r,c). The initial position of the robot is (r_b, c_b).In one second, the robot moves by dr rows and dc columns, that is, after one second, the robot moves from the cell (r, c) to (r + dr, c + dc). Initially dr = 1, dc = 1. If there is a vertical wall (the left or the right walls) in the movement direction, dc is reflected before the movement, so the new value of dc is -dc. And if there is a horizontal wall (the upper or lower walls), dr is reflected before the movement, so the new value of dr is -dr.Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at (r_d, c_d). The job of the robot is to clean that dirty cell. Illustration for the first example. The blue arc is the robot. The red star is the target dirty cell. Each second the robot cleans a row and a column, denoted by yellow stripes. Given the floor size n and m, the robot's initial position (r_b, c_b) and the dirty cell's position (r_d, c_d), find the time for the robot to do its job.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). Description of the test cases follows.A test case consists of only one line, containing six integers n, m, r_b, c_b, r_d, and c_d (1 \le n, m \le 100, 1 \le r_b, r_d \le n, 1 \le c_b, c_d \le m) — the sizes of the room, the initial position of the robot and the position of the dirt cell.OutputFor each test case, print an integer — the time for the robot to clean the dirty cell. We can show that the robot always cleans the dirty cell eventually.ExampleInput
5
10 10 6 1 2 8
10 10 9 9 1 1
9 8 5 6 2 1
6 9 2 2 5 8
2 2 1 1 2 1
Output
7
10
9
3
0
NoteIn the first example, the floor has the size of 10\times 10. The initial position of the robot is (6, 1) and the position of the dirty cell is (2, 8). See the illustration of this example in the problem statement.In the second example, the floor is the same, but the initial position of the robot is now (9, 9), and the position of the dirty cell is (1, 1). In this example, the robot went straight to the dirty cell and clean it. In the third example, the floor has the size 9 \times 8. The initial position of the robot is (5, 6), and the position of the dirty cell is (2, 1). In the fourth example, the floor has the size 6 \times 9. The initial position of the robot is (2, 2) and the position of the dirty cell is (5, 8). In the last example, the robot was already standing in the same column as the dirty cell, so it can clean the cell right away. | 5
10 10 6 1 2 8
10 10 9 9 1 1
9 8 5 6 2 1
6 9 2 2 5 8
2 2 1 1 2 1
| 7 10 9 3 0 | 1 second | 256 megabytes | ['brute force', 'implementation', 'math', '*800'] |
F. Quadratic Settime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a set of positive integers a_1, a_2, \dots, a_k quadratic if the product of the factorials of its elements is a square of an integer, i. e. \prod\limits_{i=1}^{k} a_i! = m^2, for some integer m.You are given a positive integer n.Your task is to find a quadratic subset of a set 1, 2, \dots, n of maximum size. If there are multiple answers, print any of them.InputA single line contains a single integer n (1 \le n \le 10^6).OutputIn the first line, print a single integer — the size of the maximum subset. In the second line, print the subset itself in an arbitrary order.ExamplesInput
1
Output
1
1
Input
4
Output
3
1 3 4
Input
7
Output
4
1 4 5 6
Input
9
Output
7
1 2 4 5 6 7 9
| 1
| 1 1 | 4 seconds | 256 megabytes | ['constructive algorithms', 'hashing', 'math', 'number theory', '*2900'] |
E. Math Testtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya is a math teacher. n of his students has written a test consisting of m questions. For each student, it is known which questions he has answered correctly and which he has not.If the student answers the j-th question correctly, he gets p_j points (otherwise, he gets 0 points). Moreover, the points for the questions are distributed in such a way that the array p is a permutation of numbers from 1 to m.For the i-th student, Petya knows that he expects to get x_i points for the test. Petya wonders how unexpected the results could be. Petya believes that the surprise value of the results for students is equal to \sum\limits_{i=1}^{n} |x_i - r_i|, where r_i is the number of points that the i-th student has got for the test.Your task is to help Petya find such a permutation p for which the surprise value of the results is maximum possible. If there are multiple answers, print any of them.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains two integers n and m (1 \le n \le 10; 1 \le m \le 10^4) — the number of students and the number of questions, respectively.The second line contains n integers x_1, x_2, \dots, x_n (0 \le x_i \le \frac{m(m+1)}{2}), where x_i is the number of points that the i-th student expects to get.This is followed by n lines, the i-th line contains the string s_i (|s_i| = m; s_{i, j} \in \{0, 1\}), where s_{i, j} is 1 if the i-th student has answered the j-th question correctly, and 0 otherwise.The sum of m for all test cases does not exceed 10^4.OutputFor each test case, print m integers — a permutation p for which the surprise value of the results is maximum possible. If there are multiple answers, print any of them.ExampleInput
3
4 3
5 1 2 2
110
100
101
100
4 4
6 2 0 10
1001
0010
0110
0101
3 6
20 3 15
010110
000101
111111
Output
3 1 2
2 3 4 1
3 1 4 5 2 6
| 3
4 3
5 1 2 2
110
100
101
100
4 4
6 2 0 10
1001
0010
0110
0101
3 6
20 3 15
010110
000101
111111
| 3 1 2 2 3 4 1 3 1 4 5 2 6 | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', 'greedy', '*2200'] |
D. Shuffletime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a binary string (i. e. a string consisting of characters 0 and/or 1) s of length n. You can perform the following operation with the string s at most once: choose a substring (a contiguous subsequence) of s having exactly k characters 1 in it, and shuffle it (reorder the characters in the substring as you wish).Calculate the number of different strings which can be obtained from s by performing this operation at most once.InputThe first line contains two integers n and k (2 \le n \le 5000; 0 \le k \le n).The second line contains the string s of length n, consisting of characters 0 and/or 1.OutputPrint one integer — the number of different strings which can be obtained from s by performing the described operation at most once. Since the answer can be large, output it modulo 998244353.ExamplesInput
7 2
1100110
Output
16
Input
5 0
10010
Output
1
Input
8 1
10001000
Output
10
Input
10 8
0010011000
Output
1
NoteSome strings you can obtain in the first example: to obtain 0110110, you can take the substring from the 1-st character to the 4-th character, which is 1100, and reorder its characters to get 0110; to obtain 1111000, you can take the substring from the 3-rd character to the 7-th character, which is 00110, and reorder its characters to get 11000; to obtain 1100101, you can take the substring from the 5-th character to the 7-th character, which is 110, and reorder its characters to get 101. In the second example, k = 0 so you can only choose the substrings consisting only of 0 characters. Reordering them doesn't change the string at all, so the only string you can obtain is 10010. | 7 2
1100110
| 16 | 2 seconds | 512 megabytes | ['combinatorics', 'math', 'two pointers', '*2000'] |
C. Set or Decreasetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer array a_1, a_2, \dots, a_n and integer k.In one step you can either choose some index i and decrease a_i by one (make a_i = a_i - 1); or choose two indices i and j and set a_i equal to a_j (make a_i = a_j). What is the minimum number of steps you need to make the sum of array \sum\limits_{i=1}^{n}{a_i} \le k? (You are allowed to make values of array negative).InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains two integers n and k (1 \le n \le 2 \cdot 10^5; 1 \le k \le 10^{15}) — the size of array a and upper bound on its sum.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the array itself.It's guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the minimum number of steps to make \sum\limits_{i=1}^{n}{a_i} \le k.ExampleInput
4
1 10
20
2 69
6 9
7 8
1 2 1 3 1 2 1
10 1
1 2 3 1 2 6 1 6 8 10
Output
10
0
2
7
NoteIn the first test case, you should decrease a_1 10 times to get the sum lower or equal to k = 10.In the second test case, the sum of array a is already less or equal to 69, so you don't need to change it.In the third test case, you can, for example: set a_4 = a_3 = 1; decrease a_4 by one, and get a_4 = 0. As a result, you'll get array [1, 2, 1, 0, 1, 2, 1] with sum less or equal to 8 in 1 + 1 = 2 steps.In the fourth test case, you can, for example: choose a_7 and decrease in by one 3 times; you'll get a_7 = -2; choose 4 elements a_6, a_8, a_9 and a_{10} and them equal to a_7 = -2. As a result, you'll get array [1, 2, 3, 1, 2, -2, -2, -2, -2, -2] with sum less or equal to 1 in 3 + 4 = 7 steps. | 4
1 10
20
2 69
6 9
7 8
1 2 1 3 1 2 1
10 1
1 2 3 1 2 6 1 6 8 10
| 10 0 2 7 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'greedy', 'sortings', '*1600'] |
B. Berland Musictime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland Music is a music streaming service built specifically to support Berland local artist. Its developers are currently working on a song recommendation module.So imagine Monocarp got recommended n songs, numbered from 1 to n. The i-th song had its predicted rating equal to p_i, where 1 \le p_i \le n and every integer from 1 to n appears exactly once. In other words, p is a permutation.After listening to each of them, Monocarp pressed either a like or a dislike button. Let his vote sequence be represented with a string s, such that s_i=0 means that he disliked the i-th song, and s_i=1 means that he liked it.Now the service has to re-evaluate the song ratings in such a way that: the new ratings q_1, q_2, \dots, q_n still form a permutation (1 \le q_i \le n; each integer from 1 to n appears exactly once); every song that Monocarp liked should have a greater rating than every song that Monocarp disliked (formally, for all i, j such that s_i=1 and s_j=0, q_i>q_j should hold). Among all valid permutations q find the one that has the smallest value of \sum\limits_{i=1}^n |p_i-q_i|, where |x| is an absolute value of x.Print the permutation q_1, q_2, \dots, q_n. If there are multiple answers, you can print any of them.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of songs.The second line of each testcase contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n) — the permutation of the predicted ratings.The third line contains a single string s, consisting of n characters. Each character is either a 0 or a 1. 0 means that Monocarp disliked the song, and 1 means that he liked it.The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a permutation q — the re-evaluated ratings of the songs. If there are multiple answers such that \sum\limits_{i=1}^n |p_i-q_i| is minimum possible, you can print any of them.ExampleInput
3
2
1 2
10
3
3 1 2
111
8
2 3 1 8 5 4 7 6
01110001
Output
2 1
3 1 2
1 6 5 8 3 2 4 7
NoteIn the first testcase, there exists only one permutation q such that each liked song is rating higher than each disliked song: song 1 gets rating 2 and song 2 gets rating 1. \sum\limits_{i=1}^n |p_i-q_i|=|1-2|+|2-1|=2.In the second testcase, Monocarp liked all songs, so all permutations could work. The permutation with the minimum sum of absolute differences is the permutation equal to p. Its cost is 0. | 3
2
1 2
10
3
3 1 2
111
8
2 3 1 8 5 4 7 6
01110001
| 2 1 3 1 2 1 6 5 8 3 2 4 7 | 2 seconds | 256 megabytes | ['data structures', 'greedy', 'math', 'sortings', '*1000'] |
A. Construct a Rectangletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are three sticks with integer lengths l_1, l_2 and l_3.You are asked to break exactly one of them into two pieces in such a way that: both pieces have positive (strictly greater than 0) integer length; the total length of the pieces is equal to the original length of the stick; it's possible to construct a rectangle from the resulting four sticks such that each stick is used as exactly one of its sides. A square is also considered a rectangle.Determine if it's possible to do that.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The only line of each testcase contains three integers l_1, l_2, l_3 (1 \le l_i \le 10^8) — the lengths of the sticks.OutputFor each testcase, print "YES" if it's possible to break one of the sticks into two pieces with positive integer length in such a way that it's possible to construct a rectangle from the resulting four sticks. Otherwise, print "NO".You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as a positive answer).ExampleInput
4
6 1 5
2 5 2
2 4 2
5 5 4
Output
YES
NO
YES
YES
NoteIn the first testcase, the first stick can be broken into parts of length 1 and 5. We can construct a rectangle with opposite sides of length 1 and 5.In the second testcase, breaking the stick of length 2 can only result in sticks of lengths 1, 1, 2, 5, which can't be made into a rectangle. Breaking the stick of length 5 can produce results 2, 3 or 1, 4 but neither of them can't be put into a rectangle.In the third testcase, the second stick can be broken into parts of length 2 and 2. The resulting rectangle has opposite sides 2 and 2 (which is a square).In the fourth testcase, the third stick can be broken into parts of length 2 and 2. The resulting rectangle has opposite sides 2 and 5. | 4
6 1 5
2 5 2
2 4 2
5 5 4
| YES NO YES YES | 2 seconds | 256 megabytes | ['geometry', 'math', '*800'] |
I. Two Sequencestime limit per test8 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider an array of integers C = [c_1, c_2, \ldots, c_n] of length n. Let's build the sequence of arrays D_0, D_1, D_2, \ldots, D_{n} of length n+1 in the following way: The first element of this sequence will be equals C: D_0 = C. For each 1 \leq i \leq n array D_i will be constructed from D_{i-1} in the following way: Let's find the lexicographically smallest subarray of D_{i-1} of length i. Then, the first n-i elements of D_i will be equals to the corresponding n-i elements of array D_{i-1} and the last i elements of D_i will be equals to the corresponding elements of the found subarray of length i. Array x is subarray of array y, if x can be obtained by deletion of several (possibly, zero or all) elements from the beginning of y and several (possibly, zero or all) elements from the end of y.For array C let's denote array D_n as op(C).Alice has an array of integers A = [a_1, a_2, \ldots, a_n] of length n. She will build the sequence of arrays B_0, B_1, \ldots, B_n of length n+1 in the following way: The first element of this sequence will be equals A: B_0 = A. For each 1 \leq i \leq n array B_i will be equals op(B_{i-1}), where op is the transformation described above. She will ask you q queries about elements of sequence of arrays B_0, B_1, \ldots, B_n. Each query consists of two integers i and j, and the answer to this query is the value of the j-th element of array B_i.InputThe first line contains the single integer n (1 \leq n \leq 10^5) — the length of array A.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq n) — the array A.The third line contains the single integer q (1 \leq q \leq 10^6) — the number of queries.Each of the next q lines contains two integers i, j (1 \leq i, j \leq n) — parameters of queries.OutputOutput q integers: values of B_{i, j} for required i, j.ExampleInput
4
2 1 3 1
4
1 1
1 2
1 3
1 4
Output
2
1
1
3
NoteIn the first test case B_0 = A = [2, 1, 3, 1].B_1 is constructed in the following way: Initially, D_0 = [2, 1, 3, 1]. For i=1 the lexicographically smallest subarray of D_0 of length 1 is [1], so D_1 will be [2, 1, 3, 1]. For i=2 the lexicographically smallest subarray of D_1 of length 2 is [1, 3], so D_2 will be [2, 1, 1, 3]. For i=3 the lexicographically smallest subarray of D_2 of length 3 is [1, 1, 3], so D_3 will be [2, 1, 1, 3]. For i=4 the lexicographically smallest subarray of D_3 of length 4 is [2, 1, 1, 3], so D_4 will be [2, 1, 1, 3]. So, B_1 = op(B_0) = op([2, 1, 3, 1]) = [2, 1, 1, 3]. | 4
2 1 3 1
4
1 1
1 2
1 3
1 4
| 2 1 1 3 | 8 seconds | 256 megabytes | ['data structures', 'hashing', 'string suffix structures', '*3500'] |
H. Trains and Airplanestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRailway network of one city consists of n stations connected by n-1 roads. These stations and roads forms a tree. Station 1 is a city center. For each road you know the time trains spend to pass this road. You can assume that trains don't spend time on stops. Let's define dist(v) as the time that trains spend to get from the station v to the station 1.This railway network is splitted into zones named by first k capital latin letters. The zone of the i-th station is z_i. City center is in the zone A. For all other stations it is guaranteed that the first station on the road from this station to the city center is either in the same zone or in the zone with lexicographically smaller name. Any road is completely owned by the zone of the most distant end from the city center.Tourist will arrive at the airport soon and then he will go to the city center. Here's how the trip from station v to station 1 happends: At the moment 0, tourist enters the train that follows directly from the station v to the station 1. The trip will last for dist(v) minutes. Tourist can buy tickets for any subset of zones at any moment. Ticket for zone i costs pass_i euro. Every T minutes since the start of the trip (that is, at the moments T, 2T, \ldots) the control system will scan tourist. If at the moment of scan tourist is in the zone i without zone i ticket, he should pay fine_i euro. Formally, the zone of tourist is determined in the following way: If tourist is at the station 1, then he already at the city center so he shouldn't pay fine. If tourist is at the station u \neq 1, then he is in the zone z_u. If tourist is moving from the station x to the station y that are directly connected by road, then he is in the zone z_x. Note, that tourist can pay fine multiple times in the same zone. Tourist always selects such way to buy tickets and pay fines that minimizes the total cost of trip. Let f(v) be such cost for station v.Unfortunately, tourist doesn't know the current values of pass_i and fine_i for different zones and he has forgot the location of the airport. He will ask you queries of 3 types: 1 i c — the cost of ticket in zone i has changed. Now pass_i is c. 2 i c — the cost of fine in zone i has changed. Now fine_i is c. 3 u — solve the following problem for current values of pass and fine: You are given the station u. Consider all the stations v that satisfy the following conditions: z_v = z_u The station u is on the path from the station v to the station 1. Find the value of \min(f(v)) over all such stations v with the following assumption: tourist has the ticket for the zone of station z_u. InputThe first line contains the single integer n (2 \leq n \leq 2 \cdot 10^5) — the number of stations.Each of the next n - 1 lines contains three integers v_i, u_i, t_i (1 \leq v_i, u_i \leq n, 1 \leq t_i \leq 10^9) — the ends of the i-th road and the time it takes a train to pass this road. It is guaranteed that this roads forms a tree.The next line contains the single integer k (1 \leq k \leq 26) — the number of zones.The next line contains n symbols z_1z_2 \ldots z_n — z_i is the name of the zone of the i-th station. It is guaranteed that the conditions from the second paragraph are satisfied.The next line contains k integers pass_1, pass_2, \ldots, pass_k (1 \leq pass_i \leq 10^9) — initial costs of tickets.The next line contains k integers fine_1, fine_2, \ldots, fine_k (1 \leq fine_i \leq 10^9) — initial fines.The next line contains the single integer T (1 \leq T \leq 10^9) — the time gap between scans of control system.The next line contains the single integer q (1 \leq q \leq 2 \cdot 10^5) — the number of queries.Next q lines contains queries as described in the statement. It is guaranteed that in the queries of the first and the second type i is a correct name of the zone (one of the first k capital latin letters) and 1 \leq c \leq 10^9, and in the queries of the third type 1 \leq u \leq n.OutputFor each query of the third type print the answer to it.ExampleInput
8
1 2 7
2 3 4
2 4 3
4 5 1
5 6 6
4 7 10
6 8 6
4
AABABBDB
11 12 10 42
16 15 15 30
4
6
3 2
1 A 10
3 3
2 A 3
3 7
3 6
Output
0
10
6
6
NoteNote, that the fine can be cheaper than the pass. The railway network from the example. Green color is used for stations and roads of zone A, blue color is used for zone B and red color is used for zone D. The integer near each road is time that trains spend to pass it. In the first query, the airport can be located near the station 2 or near the station 4. During the trip, tourist will always stay in the zone A. He already has the pass for this zone so the answer is 0.After the second query, the cost of the pass in the zone A has become 10.In the third query, the airport can be located only near the station 3. Optimal solution will be to buy the pass for zone A. During the first 3 seconds of trip tourist will be in the zone B. Then he will move to the zone A and will be scanned there on the 4-th and the 8-th second of his ride. Since he have a pass for this zone, he won't pay fines.After the forth query, the fine in the zone A has become 3.In the fifth query, the airport can be located only near the station 7 and f(7) = 6.In the sixth query, the airport can be located near the station 6 or near the station 8. Since f(6)=9 and f(8)=6 the answer is 6. | 8
1 2 7
2 3 4
2 4 3
4 5 1
5 6 6
4 7 10
6 8 6
4
AABABBDB
11 12 10 42
16 15 15 30
4
6
3 2
1 A 10
3 3
2 A 3
3 7
3 6
| 0 10 6 6 | 4 seconds | 512 megabytes | ['dfs and similar', 'graphs', 'shortest paths', 'trees', '*3500'] |
G. Weighted Increasing Subsequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given the sequence of integers a_1, a_2, \ldots, a_n of length n. The sequence of indices i_1 < i_2 < \ldots < i_k of length k denotes the subsequence a_{i_1}, a_{i_2}, \ldots, a_{i_k} of length k of sequence a.The subsequence a_{i_1}, a_{i_2}, \ldots, a_{i_k} of length k of sequence a is called increasing subsequence if a_{i_j} < a_{i_{j+1}} for each 1 \leq j < k.The weight of the increasing subsequence a_{i_1}, a_{i_2}, \ldots, a_{i_k} of length k of sequence a is the number of 1 \leq j \leq k, such that exists index i_k < x \leq n and a_x > a_{i_j}.For example, if a = [6, 4, 8, 6, 5], then the sequence of indices i = [2, 4] denotes increasing subsequence [4, 6] of sequence a. The weight of this increasing subsequence is 1, because for j = 1 exists x = 5 and a_5 = 5 > a_{i_1} = 4, but for j = 2 such x doesn't exist.Find the sum of weights of all increasing subsequences of a modulo 10^9+7.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains the single integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the sequence a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the sequence a.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print the sum of weights of all increasing subsequences a modulo 10^9+7.ExampleInput
4
5
6 4 8 6 5
4
1 2 3 4
3
3 2 2
4
4 5 6 5
Output
4
12
0
6
NoteIn the first test case the following increasing subsequences of a have not zero weight: The weight of [a_1] = [6] is 1. The weight of [a_2] = [4] is 1. The weight of [a_2, a_3] = [4, 8] is 1. The weight of [a_2, a_4] = [4, 6] is 1. The sum of weights of increasing subsequences is 4.In the second test case there are 7 increasing subsequences of a with not zero weight: 3 with weight 1, 3 with weight 2 and 1 with weight 3. The sum of weights is 12. | 4
5
6 4 8 6 5
4
1 2 3 4
3
3 2 2
4
4 5 6 5
| 4 12 0 6 | 1 second | 256 megabytes | ['data structures', 'dp', 'math', '*3200'] |
F. Strange Instructionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDasha has 10^{100} coins. Recently, she found a binary string s of length n and some operations that allows to change this string (she can do each operation any number of times): Replace substring 00 of s by 0 and receive a coins. Replace substring 11 of s by 1 and receive b coins. Remove 0 from any position in s and pay c coins. It turned out that while doing this operations Dasha should follow the rule: It is forbidden to do two operations with the same parity in a row. Operations are numbered by integers 1-3 in the order they are given above. Please, calculate what is the maximum profit Dasha can get by doing these operations and following this rule.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases.The first line of each test case contains four integers n, a, b, c (1 \leq n \leq 10^5, 1 \leq a, b, c \leq 10^9).The second line of each test case contains a binary string s of length n.It is guaranteed that the total sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case print the answer.ExampleInput
3
5 2 2 1
01101
6 4 3 5
110001
6 3 2 1
011110
Output
3
11
4
NoteIn the first test case one of the optimal sequences of operations is 01101 \rightarrow 0101 \rightarrow 011 \rightarrow 01. This sequence of operations consists of operations 2, 3 and 2 in this order. It satisfies all rules and gives profit 3. It can be shown that it is impossible to achieve higher profit in this test case, so the answer is 3.In the second test case one of the optimal sequences of operations is 110001 \rightarrow 11001 \rightarrow 1001 \rightarrow 101.In the third test case one of the optimal sequences of operations is 011110 \rightarrow 01110 \rightarrow 1110 \rightarrow 110 \rightarrow 11 \rightarrow 1. | 3
5 2 2 1
01101
6 4 3 5
110001
6 3 2 1
011110
| 3 11 4 | 2 seconds | 256 megabytes | ['data structures', 'greedy', 'implementation', '*2700'] |
E. New Schooltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have decided to open a new school. You have already found n teachers and m groups of students. The i-th group of students consists of k_i \geq 2 students. You know age of each teacher and each student. The ages of teachers are a_1, a_2, \ldots, a_n and the ages of students of the i-th group are b_{i, 1}, b_{i, 2}, \ldots, b_{i, k_i}.To start lessons you should assign the teacher to each group of students. Such assignment should satisfy the following requirements: To each group exactly one teacher assigned. To each teacher at most 1 group of students assigned. The average of students' ages in each group doesn't exceed the age of the teacher assigned to this group. The average of set x_1, x_2, \ldots, x_k of k integers is \frac{x_1 + x_2 + \ldots + x_k}{k}.Recently you have heard that one of the students will refuse to study in your school. After this, the size of one group will decrease by 1 while all other groups will remain unchanged.You don't know who will refuse to study. For each student determine if you can start lessons in case of his refusal.Note, that it is not guaranteed that it is possible to start lessons before any refusal.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains two integers n and m (1 \leq m \leq n \leq 10^5) — the number of teachers and the number of groups of students.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^5) — the ages of teachers.The next 2m lines contains descriptions of groups. The first line of description of group contains a single integer k_i (2 \leq k_i \leq 10^5) — the number of students in this group. The second line of description of group contains k_i integers b_{i, 1}, b_{i, 2}, \ldots, b_{i, k_i} (1 \leq b_{i, j} \leq 10^5) — the ages of students of this group.It is guaranteed that the total sum of n over all test cases doesn't exceed 10^5 and that the total sum of k_1 + k_2 + \ldots + k_m over all test cases doesn't exceed 2 \cdot 10^5OutputFor each test case output string of symbols 0 and 1 of length k_1 + k_2 + \ldots + k_m. The i-th symbol of this string should be equals 1 if it is possible to start lessons in case of the i-th student refuse and it should be equals 0 otherwise.Students are numbered by integers from 1 to k_1 + k_2 + \ldots + k_m in the order they appear in the input. Thus, students of the 1-st group are numbered by integers 1, 2, \ldots, k_1, students of the 2-nd group are numbered by integers k_1 + 1, k_1 + 2, \ldots, k_1 + k_2 and so on.ExampleInput
2
1 1
30
3
25 16 37
4 2
9 12 12 6
2
4 5
3
111 11 11
Output
101
00100
NoteIn the first test case there is one group of students with average age \frac{25+16+37}{3}=26 and one teacher with age 30. There exists only one assignment that allows to start lessons.If the student with age 16 will refuse to study, the average age of students in this group will become \frac{25+37}{2}=31 so there won't be any assignment that allows to start lessons.In the second test case it is impossible to start lessons initially. However, if the 3-rd student with age 111 will refuse to study, the average ages of groups will become \frac{4 + 5}{2}=4.5 and \frac{11+11}{2} = 11 correspondingly. Then it is possible to assing the first group to the first teacher and the second group to the third teacher. | 2
1 1
30
3
25 16 37
4 2
9 12 12 6
2
4 5
3
111 11 11
| 101 00100 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dp', 'greedy', 'implementation', 'sortings', '*2300'] |
D. The Winter Hiketime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCircular land is an 2n \times 2n grid. Rows of this grid are numbered by integers from 1 to 2n from top to bottom and columns of this grid are numbered by integers from 1 to 2n from left to right. The cell (x, y) is the cell on the intersection of row x and column y for 1 \leq x \leq 2n and 1 \leq y \leq 2n.There are n^2 of your friends in the top left corner of the grid. That is, in each cell (x, y) with 1 \leq x, y \leq n there is exactly one friend. Some of the other cells are covered with snow.Your friends want to get to the bottom right corner of the grid. For this in each cell (x, y) with n+1 \leq x, y \leq 2n there should be exactly one friend. It doesn't matter in what cell each of friends will be.You have decided to help your friends to get to the bottom right corner of the grid.For this, you can give instructions of the following types: You select a row x. All friends in this row should move to the next cell in this row. That is, friend from the cell (x, y) with 1 \leq y < 2n will move to the cell (x, y + 1) and friend from the cell (x, 2n) will move to the cell (x, 1). You select a row x. All friends in this row should move to the previous cell in this row. That is, friend from the cell (x, y) with 1 < y \leq 2n will move to the cell (x, y - 1) and friend from the cell (x, 1) will move to the cell (x, 2n). You select a column y. All friends in this column should move to the next cell in this column. That is, friend from the cell (x, y) with 1 \leq x < 2n will move to the cell (x + 1, y) and friend from the cell (2n, y) will move to the cell (1, y). You select a column y. All friends in this column should move to the previous cell in this column. That is, friend from the cell (x, y) with 1 < x \leq 2n will move to the cell (x - 1, y) and friend from the cell (1, y) will move to the cell (2n, y). Note how friends on the grid border behave in these instructions. Example of applying the third operation to the second column. Here, colorful circles denote your friends and blue cells are covered with snow. You can give such instructions any number of times. You can give instructions of different types. If after any instruction one of your friends is in the cell covered with snow he becomes ill.In order to save your friends you can remove snow from some cells before giving the first instruction: You can select the cell (x, y) that is covered with snow now and remove snow from this cell for c_{x, y} coins. You can do this operation any number of times.You want to spend the minimal number of coins and give some instructions to your friends. After this, all your friends should be in the bottom right corner of the grid and none of them should be ill.Please, find how many coins you will spend.InputThe first line contains a single integer t (1 \leq t \leq 100) — the number of test cases.The first line of each test case contains the single integer n (1 \leq n \leq 250).Each of the next 2n lines contains 2n integers c_{i, 1}, c_{i, 2}, \ldots, c_{i, 2n} (0 \leq c_{i, j} \leq 10^9) — costs of removing snow from cells. If c_{i, j} = 0 for some i, j than there is no snow in cell (i, j). Otherwise, cell (i, j) is covered with snow.It is guaranteed that c_{i, j} = 0 for 1 \leq i, j \leq n.It is guaranteed that the sum of n over all test cases doesn't exceed 250.OutputFor each test case output one integer — the minimal number of coins you should spend.ExampleInput
4
1
0 8
1 99
2
0 0 0 0
0 0 0 0
9 9 2 2
9 9 9 9
2
0 0 4 2
0 0 2 4
4 2 4 2
2 4 2 4
4
0 0 0 0 0 0 0 2
0 0 0 0 0 0 2 0
0 0 0 0 0 2 0 0
0 0 0 0 2 0 0 0
0 0 0 2 2 0 2 2
0 0 2 0 1 6 2 1
0 2 0 0 2 4 7 4
2 0 0 0 2 0 1 6
Output
100
22
14
42
NoteIn the first test case you can remove snow from the cells (2, 1) and (2, 2) for 100 coins. Then you can give instructions All friends in the first collum should move to the previous cell. After this, your friend will be in the cell (2, 1). All friends in the second row should move to the next cell. After this, your friend will be in the cell (2, 2). In the second test case you can remove all snow from the columns 3 and 4 for 22 coins. Then you can give instructions All friends in the first row should move to the next cell. All friends in the first row should move to the next cell. All friends in the second row should move to the next cell. All friends in the second row should move to the next cell. All friends in the third column should move to the next cell. All friends in the third column should move to the next cell. All friends in the fourth column should move to the next cell. All friends in the fourth column should move to the next cell. It can be shown that none of the friends will become ill and that it is impossible to spend less coins. | 4
1
0 8
1 99
2
0 0 0 0
0 0 0 0
9 9 2 2
9 9 9 9
2
0 0 4 2
0 0 2 4
4 2 4 2
2 4 2 4
4
0 0 0 0 0 0 0 2
0 0 0 0 0 0 2 0
0 0 0 0 0 2 0 0
0 0 0 0 2 0 0 0
0 0 0 2 2 0 2 2
0 0 2 0 1 6 2 1
0 2 0 0 2 4 7 4
2 0 0 0 2 0 1 6
| 100 22 14 42 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*2100'] |
C. Hidden Permutationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.The jury has a permutation p of length n and wants you to guess it. For this, the jury created another permutation q of length n. Initially, q is an identity permutation (q_i = i for all i).You can ask queries to get q_i for any i you want. After each query, the jury will change q in the following way: At first, the jury will create a new permutation q' of length n such that q'_i = q_{p_i} for all i. Then the jury will replace permutation q with pemutation q'. You can make no more than 2n queries in order to quess p.InputThe first line of input contains a single integer t (1 \leq t \leq 1000) — the number of test cases.InteractionInteraction in each test case starts after reading the single integer n (1 \leq n \leq 10^4) — the length of permutations p and q.To get the value of q_i, output the query in the format ? i (1 \leq i \leq n). After that you will receive the value of q_i.You can make at most 2n queries. After the incorrect query you will receive 0 and you should exit immediately to get Wrong answer verdict.When you will be ready to determine p, output p in format ! p_1 p_2 \ldots p_n. After this you should go to the next test case or exit if it was the last test case. Printing the permutation is not counted as one of 2n queries.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. It is guaranteed that the sum of n over all test cases doesn't exceed 10^4. The interactor is not adaptive in this problem.Hacks:To hack, use the following format:The first line contains the single integer t — the number of test cases.The first line of each test case contains the single integer n — the length of the permutations p and q. The second line of each test case contains n integers p_1, p_2, \ldots, p_n — the hidden permutation for this test case.ExampleInput
2
4
3
2
1
4
2
4
4Output
? 3
? 2
? 4
! 4 2 1 3
? 2
? 3
? 2
! 1 3 4 2NoteIn the first test case the hidden permutation p = [4, 2, 1, 3].Before the first query q = [1, 2, 3, 4] so answer for the query will be q_3 = 3.Before the second query q = [4, 2, 1, 3] so answer for the query will be q_2 = 2.Before the third query q = [3, 2, 4, 1] so answer for the query will be q_4 = 1.In the second test case the hidden permutation p = [1, 3, 4, 2].Empty strings are given only for better readability. There will be no empty lines in the testing system. | 2
4
3
2
1
4
2
4
4 | ? 3 ? 2 ? 4 ! 4 2 1 3 ? 2 ? 3 ? 2 ! 1 3 4 2 | 1 second | 256 megabytes | ['dfs and similar', 'interactive', 'math', '*1700'] |
B. Integers Shoptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe integers shop sells n segments. The i-th of them contains all integers from l_i to r_i and costs c_i coins.Tomorrow Vasya will go to this shop and will buy some segments there. He will get all integers that appear in at least one of bought segments. The total cost of the purchase is the sum of costs of all segments in it.After shopping, Vasya will get some more integers as a gift. He will get integer x as a gift if and only if all of the following conditions are satisfied: Vasya hasn't bought x. Vasya has bought integer l that is less than x. Vasya has bought integer r that is greater than x. Vasya can get integer x as a gift only once so he won't have the same integers after receiving a gift.For example, if Vasya buys segment [2, 4] for 20 coins and segment [7, 8] for 22 coins, he spends 42 coins and receives integers 2, 3, 4, 7, 8 from these segments. He also gets integers 5 and 6 as a gift.Due to the technical issues only the first s segments (that is, segments [l_1, r_1], [l_2, r_2], \ldots, [l_s, r_s]) will be available tomorrow in the shop.Vasya wants to get (to buy or to get as a gift) as many integers as possible. If he can do this in differents ways, he selects the cheapest of them.For each s from 1 to n, find how many coins will Vasya spend if only the first s segments will be available.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains the single integer n (1 \leq n \leq 10^5) — the number of segments in the shop.Each of next n lines contains three integers l_i, r_i, c_i (1 \leq l_i \leq r_i \leq 10^9, 1 \leq c_i \leq 10^9) — the ends of the i-th segments and its cost.It is guaranteed that the total sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case output n integers: the s-th (1 \leq s \leq n) of them should be the number of coins Vasia will spend in the shop if only the first s segments will be available.ExampleInput
3
2
2 4 20
7 8 22
2
5 11 42
5 11 42
6
1 4 4
5 8 9
7 8 7
2 10 252
1 11 271
1 10 1
Output
20
42
42
42
4
13
11
256
271
271
NoteIn the first test case if s = 1 then Vasya can buy only the segment [2, 4] for 20 coins and get 3 integers.The way to get 7 integers for 42 coins in case s = 2 is described in the statement.In the second test case note, that there can be the same segments in the shop. | 3
2
2 4 20
7 8 22
2
5 11 42
5 11 42
6
1 4 4
5 8 9
7 8 7
2 10 252
1 11 271
1 10 1
| 20 42 42 42 4 13 11 256 271 271 | 2 seconds | 256 megabytes | ['data structures', 'greedy', 'implementation', '*1500'] |
A. Stable Arrangement of Rookstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an n \times n chessboard and k rooks. Rows of this chessboard are numbered by integers from 1 to n from top to bottom and columns of this chessboard are numbered by integers from 1 to n from left to right. The cell (x, y) is the cell on the intersection of row x and collumn y for 1 \leq x \leq n and 1 \leq y \leq n.The arrangement of rooks on this board is called good, if no rook is beaten by another rook.A rook beats all the rooks that shares the same row or collumn with it.The good arrangement of rooks on this board is called not stable, if it is possible to move one rook to the adjacent cell so arrangement becomes not good. Otherwise, the good arrangement is stable. Here, adjacent cells are the cells that share a side. Such arrangement of 3 rooks on the 4 \times 4 chessboard is good, but it is not stable: the rook from (1, 1) can be moved to the adjacent cell (2, 1) and rooks on cells (2, 1) and (2, 4) will beat each other. Please, find any stable arrangement of k rooks on the n \times n chessboard or report that there is no such arrangement.InputThe first line contains a single integer t (1 \leq t \leq 100) — the number of test cases.The first line of each test case contains two integers n, k (1 \leq k \leq n \leq 40) — the size of the chessboard and the number of rooks.OutputIf there is a stable arrangement of k rooks on the n \times n chessboard, output n lines of symbols . and R. The j-th symbol of the i-th line should be equals R if and only if there is a rook on the cell (i, j) in your arrangement.If there are multiple solutions, you may output any of them.If there is no stable arrangement, output -1.ExampleInput
5
3 2
3 3
1 1
5 2
40 33
Output
..R
...
R..
-1
R
.....
R....
.....
....R
.....
-1NoteIn the first test case, you should find stable arrangement of 2 rooks on the 3 \times 3 chessboard. Placing them in cells (3, 1) and (1, 3) gives stable arrangement.In the second test case it can be shown that it is impossbile to place 3 rooks on the 3 \times 3 chessboard to get stable arrangement. | 5
3 2
3 3
1 1
5 2
40 33
| ..R ... R.. -1 R ..... R.... ..... ....R ..... -1 | 1 second | 256 megabytes | ['constructive algorithms', '*800'] |
G. Subsequences Galoretime limit per test10 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFor a sequence of strings [t_1, t_2, \dots, t_m], let's define the function f([t_1, t_2, \dots, t_m]) as the number of different strings (including the empty string) that are subsequences of at least one string t_i. f([]) = 0 (i. e. the number of such strings for an empty sequence is 0).You are given a sequence of strings [s_1, s_2, \dots, s_n]. Every string in this sequence consists of lowercase Latin letters and is sorted (i. e., each string begins with several (maybe zero) characters a, then several (maybe zero) characters b, ..., ends with several (maybe zero) characters z).For each of 2^n subsequences of [s_1, s_2, \dots, s_n], calculate the value of the function f modulo 998244353.InputThe first line contains one integer n (1 \le n \le 23) — the number of strings.Then n lines follow. The i-th line contains the string s_i (1 \le |s_i| \le 2 \cdot 10^4), consisting of lowercase Latin letters. Each string s_i is sorted.OutputSince printing up to 2^{23} integers would be really slow, you should do the following:For each of the 2^n subsequences (which we denote as [s_{i_1}, s_{i_2}, \dots, s_{i_k}]), calculate f([s_{i_1}, s_{i_2}, \dots, s_{i_k}]), take it modulo 998244353, then multiply it by k \cdot (i_1 + i_2 + \dots + i_k). Print the XOR of all 2^n integers you get.The indices i_1, i_2, \dots, i_k in the description of each subsequences are 1-indexed (i. e. are from 1 to n).ExamplesInput
3
a
b
c
Output
92
Input
2
aa
a
Output
21
Input
2
a
a
Output
10
Input
2
abcd
aabb
Output
124
Input
3
ddd
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaabbbbbbbbbbbcccccccccccciiiiiiiiiiiiiiiiiiiiiiooooooooooqqqqqqqqqqqqqqqqqqvvvvvzzzzzzzzzzzz
Output
15706243380
| 3
a
b
c
| 92 | 10 seconds | 1024 megabytes | ['bitmasks', 'combinatorics', 'dp', '*2400'] |
F. Bipartite Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p consisting of n integers 1, 2, \dots, n (a permutation is an array where each element from 1 to n occurs exactly once).Let's call an array a bipartite if the following undirected graph is bipartite: the graph consists of n vertices; two vertices i and j are connected by an edge if i < j and a_i > a_j. Your task is to find a bipartite array of integers a of size n, such that a_i = p_i or a_i = -p_i, or report that no such array exists. If there are multiple answers, print any of them.InputThe first line contains a single integer t (1 \le t \le 2 \cdot 10^5) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 10^6) — the size of the permutation.The second line contains n integers p_1, p_2, \dots, p_n.The sum of n over all test cases doesn't exceed 10^6.OutputFor each test case, print the answer in the following format. If such an array a does not exist, print "NO" in a single line. Otherwise, print "YES" in the first line and n integers — array a in the second line.ExampleInput
4
3
1 2 3
6
1 3 2 6 5 4
4
4 1 3 2
8
3 2 1 6 7 8 5 4
Output
YES
1 2 3
NO
YES
-4 -1 -3 -2
YES
-3 -2 1 6 7 -8 -5 -4
| 4
3
1 2 3
6
1 3 2 6 5 4
4
4 1 3 2
8
3 2 1 6 7 8 5 4
| YES 1 2 3 NO YES -4 -1 -3 -2 YES -3 -2 1 6 7 -8 -5 -4 | 2 seconds | 256 megabytes | ['dp', 'greedy', '*2800'] |
E. Replace the Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array of integers (initially empty).You have to perform q queries. Each query is of one of two types: "1 x" — add the element x to the end of the array; "2 x y" — replace all occurrences of x in the array with y. Find the resulting array after performing all the queries.InputThe first line contains a single integer q (1 \le q \le 5 \cdot 10^5) — the number of queries.Next q lines contain queries (one per line). Each query is of one of two types: "1 x" (1 \le x \le 5 \cdot 10^5); "2 x y" (1 \le x, y \le 5 \cdot 10^5). It's guaranteed that there is at least one query of the first type.OutputIn a single line, print k integers — the resulting array after performing all the queries, where k is the number of queries of the first type.ExamplesInput
7
1 3
1 1
2 1 2
1 2
1 1
1 2
2 1 3
Output
3 2 2 3 2 Input
4
1 1
1 2
1 1
2 2 2
Output
1 2 1 Input
8
2 1 4
1 1
1 4
1 2
2 2 4
2 4 3
1 2
2 2 7
Output
1 3 3 7 NoteIn the first example, the array changes as follows:[] \rightarrow [3] \rightarrow [3, 1] \rightarrow [3, 2] \rightarrow [3, 2, 2] \rightarrow [3, 2, 2, 1] \rightarrow [3, 2, 2, 1, 2] \rightarrow [3, 2, 2, 3, 2].In the second example, the array changes as follows:[] \rightarrow [1] \rightarrow [1, 2] \rightarrow [1, 2, 1] \rightarrow [1, 2, 1].In the third example, the array changes as follows:[] \rightarrow [] \rightarrow [1] \rightarrow [1, 4] \rightarrow [1, 4, 2] \rightarrow [1, 4, 4] \rightarrow [1, 3, 3] \rightarrow [1, 3, 3, 2] \rightarrow [1, 3, 3, 7]. | 7
1 3
1 1
2 1 2
1 2
1 1
1 2
2 1 3
| 3 2 2 3 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'dsu', 'implementation', '*1900'] |
D. Exact Changetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, early in the morning, you decided to buy yourself a bag of chips in the nearby store. The store has chips of n different flavors. A bag of the i-th flavor costs a_i burles.The store may run out of some flavors, so you'll decide which one to buy after arriving there. But there are two major flaws in this plan: you have only coins of 1, 2 and 3 burles; since it's morning, the store will ask you to pay in exact change, i. e. if you choose the i-th flavor, you'll have to pay exactly a_i burles. Coins are heavy, so you'd like to take the least possible number of coins in total. That's why you are wondering: what is the minimum total number of coins you should take with you, so you can buy a bag of chips of any flavor in exact change?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains the single integer n (1 \le n \le 100) — the number of flavors in the store.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the cost of one bag of each flavor.OutputFor each test case, print one integer — the minimum number of coins you need to buy one bag of any flavor you'll choose in exact change.ExampleInput
4
1
1337
3
10 8 10
5
1 2 3 4 5
3
7 77 777
Output
446
4
3
260
NoteIn the first test case, you should, for example, take with you 445 coins of value 3 and 1 coin of value 2. So, 1337 = 445 \cdot 3 + 1 \cdot 2.In the second test case, you should, for example, take 2 coins of value 3 and 2 coins of value 2. So you can pay either exactly 8 = 2 \cdot 3 + 1 \cdot 2 or 10 = 2 \cdot 3 + 2 \cdot 2.In the third test case, it's enough to take 1 coin of value 3 and 2 coins of value 1. | 4
1
1337
3
10 8 10
5
1 2 3 4 5
3
7 77 777
| 446 4 3 260 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', '*2000'] |
C. BA-Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer k and a string s that consists only of characters 'a' (a lowercase Latin letter) and '*' (an asterisk).Each asterisk should be replaced with several (from 0 to k inclusive) lowercase Latin letters 'b'. Different asterisk can be replaced with different counts of letter 'b'.The result of the replacement is called a BA-string.Two strings a and b are different if they either have different lengths or there exists such a position i that a_i \neq b_i.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. Now consider all different BA-strings and find the x-th lexicographically smallest of them.InputThe first line contains a single integer t (1 \le t \le 2000) — the number of testcases.The first line of each testcase contains three integers n, k and x (1 \le n \le 2000; 0 \le k \le 2000; 1 \le x \le 10^{18}). n is the length of string s.The second line of each testcase is a string s. It consists of n characters, each of them is either 'a' (a lowercase Latin letter) or '*' (an asterisk).The sum of n over all testcases doesn't exceed 2000. For each testcase x doesn't exceed the total number of different BA-strings. String s contains at least one character 'a'.OutputFor each testcase, print a single string, consisting only of characters 'b' and 'a' (lowercase Latin letters) — the x-th lexicographically smallest BA-string.ExampleInput
3
2 4 3
a*
4 1 3
a**a
6 3 20
**a***
Output
abb
abba
babbbbbbbbb
NoteIn the first testcase of the example, BA-strings ordered lexicographically are: a ab abb abbb abbbb In the second testcase of the example, BA-strings ordered lexicographically are: aa aba abba Note that string "aba" is only counted once, even though there are two ways to replace asterisks with characters 'b' to get it. | 3
2 4 3
a*
4 1 3
a**a
6 3 20
**a***
| abb abba babbbbbbbbb | 2 seconds | 256 megabytes | ['brute force', 'dp', 'greedy', 'implementation', 'math', '*1800'] |
B. Triangles on a Rectangletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA rectangle with its opposite corners in (0, 0) and (w, h) and sides parallel to the axes is drawn on a plane.You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.Your task is to choose three points in such a way that: exactly two of them belong to the same side of a rectangle; the area of a triangle formed by them is maximum possible. Print the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains two integers w and h (3 \le w, h \le 10^6) — the coordinates of the corner of a rectangle.The next two lines contain the description of the points on two horizontal sides. First, an integer k (2 \le k \le 2 \cdot 10^5) — the number of points. Then, k integers x_1 < x_2 < \dots < x_k (0 < x_i < w) — the x coordinates of the points in the ascending order. The y coordinate for the first line is 0 and for the second line is h.The next two lines contain the description of the points on two vertical sides. First, an integer k (2 \le k \le 2 \cdot 10^5) — the number of points. Then, k integers y_1 < y_2 < \dots < y_k (0 < y_i < h) — the y coordinates of the points in the ascending order. The x coordinate for the first line is 0 and for the second line is w.The total number of points on all sides in all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase print a single integer — the doubled maximum area of a triangle formed by such three points that exactly two of them belong to the same side.ExampleInput
3
5 8
2 1 2
3 2 3 4
3 1 4 6
2 4 5
10 7
2 3 9
2 1 7
3 1 3 4
3 4 5 6
11 5
3 1 6 8
3 3 6 8
3 1 3 4
2 2 4
Output
25
42
35
NoteThe points in the first testcase of the example: (1, 0), (2, 0); (2, 8), (3, 8), (4, 8); (0, 1), (0, 4), (0, 6); (5, 4), (5, 5). The largest triangle is formed by points (0, 1), (0, 6) and (5, 4) — its area is \frac{25}{2}. Thus, the doubled area is 25. Two points that are on the same side are: (0, 1) and (0, 6). | 3
5 8
2 1 2
3 2 3 4
3 1 4 6
2 4 5
10 7
2 3 9
2 1 7
3 1 3 4
3 4 5 6
11 5
3 1 6 8
3 3 6 8
3 1 3 4
2 2 4
| 25 42 35 | 2 seconds | 256 megabytes | ['geometry', 'greedy', 'math', '*1000'] |
A. Equal or Not Equaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou had n positive integers a_1, a_2, \dots, a_n arranged in a circle. For each pair of neighboring numbers (a_1 and a_2, a_2 and a_3, ..., a_{n - 1} and a_n, and a_n and a_1), you wrote down: are the numbers in the pair equal or not.Unfortunately, you've lost a piece of paper with the array a. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array a which is consistent with information you have about equality or non-equality of corresponding pairs?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Next t cases follow.The first and only line of each test case contains a non-empty string s consisting of characters E and/or N. The length of s is equal to the size of array n and 2 \le n \le 50. For each i from 1 to n: if s_i = E then a_i is equal to a_{i + 1} (a_n = a_1 for i = n); if s_i = N then a_i is not equal to a_{i + 1} (a_n \neq a_1 for i = n). OutputFor each test case, print YES if it's possible to choose array a that are consistent with information from s you know. Otherwise, print NO.It can be proved, that if there exists some array a, then there exists an array a of positive integers with values less or equal to 10^9.ExampleInput
4
EEE
EN
ENNEENE
NENN
Output
YES
NO
YES
YES
NoteIn the first test case, you can choose, for example, a_1 = a_2 = a_3 = 5.In the second test case, there is no array a, since, according to s_1, a_1 is equal to a_2, but, according to s_2, a_2 is not equal to a_1.In the third test case, you can, for example, choose array a = [20, 20, 4, 50, 50, 50, 20].In the fourth test case, you can, for example, choose a = [1, 3, 3, 7]. | 4
EEE
EN
ENNEENE
NENN
| YES NO YES YES | 2 seconds | 256 megabytes | ['constructive algorithms', 'dsu', 'implementation', '*800'] |
H. Permutation and Queriestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p of n elements. A permutation of n elements is an array of length n containing each integer from 1 to n exactly once. For example, [1, 2, 3] and [4, 3, 5, 1, 2] are permutations, but [1, 2, 4] and [4, 3, 2, 1, 2] are not permutations. You should perform q queries.There are two types of queries: 1 x y — swap p_x and p_y. 2 i k — print the number that i will become if we assign i = p_i k times. InputThe first line contains two integers n and q (1 \le n, q \le 10^5).The second line contains n integers p_1, p_2, \dots, p_n.Each of the next q lines contains three integers. The first integer is t (1 \le t \le 2) — type of query. If t = 1, then the next two integers are x and y (1 \le x, y \le n; x \ne y) — first-type query. If t = 2, then the next two integers are i and k (1 \le i, k \le n) — second-type query.It is guaranteed that there is at least one second-type query.OutputFor every second-type query, print one integer in a new line — answer to this query.ExamplesInput
5 4
5 3 4 2 1
2 3 1
2 1 2
1 1 3
2 1 2
Output
4
1
2
Input
5 9
2 3 5 1 4
2 3 5
2 5 5
2 5 1
2 5 3
2 5 4
1 5 4
2 5 3
2 2 5
2 5 1
Output
3
5
4
2
3
3
3
1
NoteIn the first example p = \{5, 3, 4, 2, 1\}. The first query is to print p_3. The answer is 4.The second query is to print p_{p_1}. The answer is 1.The third query is to swap p_1 and p_3. Now p = \{4, 3, 5, 2, 1\}.The fourth query is to print p_{p_1}. The answer is 2. | 5 4
5 3 4 2 1
2 3 1
2 1 2
1 1 3
2 1 2
| 4 1 2 | 4 seconds | 256 megabytes | ['brute force', 'data structures', 'divide and conquer', 'two pointers', '*2400'] |
G. Unusual Minesweepertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is very fond of playing the game Minesweeper. Recently he found a similar game and there are such rules.There are mines on the field, for each the coordinates of its location are known (x_i, y_i). Each mine has a lifetime in seconds, after which it will explode. After the explosion, the mine also detonates all mines vertically and horizontally at a distance of k (two perpendicular lines). As a result, we get an explosion on the field in the form of a "plus" symbol ('+'). Thus, one explosion can cause new explosions, and so on.Also, Polycarp can detonate anyone mine every second, starting from zero seconds. After that, a chain reaction of explosions also takes place. Mines explode instantly and also instantly detonate other mines according to the rules described above.Polycarp wants to set a new record and asks you to help him calculate in what minimum number of seconds all mines can be detonated.InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases in the test.An empty line is written in front of each test suite.Next comes a line that contains integers n and k (1 \le n \le 2 \cdot 10^5, 0 \le k \le 10^9) — the number of mines and the distance that hit by mines during the explosion, respectively.Then n lines follow, the i-th of which describes the x and y coordinates of the i-th mine and the time until its explosion (-10^9 \le x, y \le 10^9, 0 \le timer \le 10^9). It is guaranteed that all mines have different coordinates.It is guaranteed that the sum of the values n over all test cases in the test does not exceed 2 \cdot 10^5.OutputPrint t lines, each of the lines must contain the answer to the corresponding set of input data — the minimum number of seconds it takes to explode all the mines.ExampleInput
3
5 0
0 0 1
0 1 4
1 0 2
1 1 3
2 2 9
5 2
0 0 1
0 1 4
1 0 2
1 1 3
2 2 9
6 1
1 -1 3
0 -1 9
0 1 7
-1 0 1
-1 1 9
-1 -1 7
Output
2
1
0
Note Picture from examples First example: 0 second: we explode a mine at the cell (2, 2), it does not detonate any other mine since k=0. 1 second: we explode the mine at the cell (0, 1), and the mine at the cell (0, 0) explodes itself. 2 second: we explode the mine at the cell (1, 1), and the mine at the cell (1, 0) explodes itself.Second example: 0 second: we explode a mine at the cell (2, 2) we get: 1 second: the mine at coordinate (0, 0) explodes and since k=2 the explosion detonates mines at the cells (0, 1) and (1, 0), and their explosions detonate the mine at the cell (1, 1) and there are no mines left on the field. | 3
5 0
0 0 1
0 1 4
1 0 2
1 1 3
2 2 9
5 2
0 0 1
0 1 4
1 0 2
1 1 3
2 2 9
6 1
1 -1 3
0 -1 9
0 1 7
-1 0 1
-1 1 9
-1 -1 7
| 2 1 0 | 2 seconds | 256 megabytes | ['binary search', 'dfs and similar', 'dsu', 'greedy', 'sortings', '*2000'] |
F. Let's Play the Hat?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Hat is a game of speedy explanation/guessing words (similar to Alias). It's fun. Try it! In this problem, we are talking about a variant of the game when the players are sitting at the table and everyone plays individually (i.e. not teams, but individual gamers play).n people gathered in a room with m tables (n \ge 2m). They want to play the Hat k times. Thus, k games will be played at each table. Each player will play in k games.To do this, they are distributed among the tables for each game. During each game, one player plays at exactly one table. A player can play at different tables.Players want to have the most "fair" schedule of games. For this reason, they are looking for a schedule (table distribution for each game) such that: At any table in each game there are either \lfloor\frac{n}{m}\rfloor people or \lceil\frac{n}{m}\rceil people (that is, either n/m rounded down, or n/m rounded up). Different numbers of people can play different games at the same table. Let's calculate for each player the value b_i — the number of times the i-th player played at a table with \lceil\frac{n}{m}\rceil persons (n/m rounded up). Any two values of b_imust differ by no more than 1. In other words, for any two players i and j, it must be true |b_i - b_j| \le 1. For example, if n=5, m=2 and k=2, then at the request of the first item either two players or three players should play at each table. Consider the following schedules: First game: 1, 2, 3 are played at the first table, and 4, 5 at the second one. The second game: at the first table they play 5, 1, and at the second — 2, 3, 4. This schedule is not "fair" since b_2=2 (the second player played twice at a big table) and b_5=0 (the fifth player did not play at a big table). First game: 1, 2, 3 are played at the first table, and 4, 5 at the second one. The second game: at the first table they play 4, 5, 2, and at the second one — 1, 3. This schedule is "fair": b=[1,2,1,1,1] (any two values of b_i differ by no more than 1). Find any "fair" game schedule for n people if they play on the m tables of k games.InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases in the test.Each test case consists of one line that contains three integers n, m and k (2 \le n \le 2\cdot10^5, 1 \le m \le \lfloor\frac{n}{2}\rfloor, 1 \le k \le 10^5) — the number of people, tables and games, respectively.It is guaranteed that the sum of nk (n multiplied by k) over all test cases does not exceed 2\cdot10^5.OutputFor each test case print a required schedule — a sequence of k blocks of m lines. Each block corresponds to one game, a line in a block corresponds to one table. In each line print the number of players at the table and the indices of the players (numbers from 1 to n) who should play at this table.If there are several required schedules, then output any of them. We can show that a valid solution always exists.You can output additional blank lines to separate responses to different sets of inputs.ExampleInput
3
5 2 2
8 3 1
2 1 3
Output
3 1 2 3
2 4 5
3 4 5 2
2 1 3
2 6 2
3 3 5 1
3 4 7 8
2 2 1
2 2 1
2 2 1
| 3
5 2 2
8 3 1
2 1 3
| 3 1 2 3 2 4 5 3 4 5 2 2 1 3 2 6 2 3 3 5 1 3 4 7 8 2 2 1 2 2 1 2 2 1 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', 'math', '*2000'] |
E. MEX and Incrementstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDmitry has an array of n non-negative integers a_1, a_2, \dots, a_n.In one operation, Dmitry can choose any index j (1 \le j \le n) and increase the value of the element a_j by 1. He can choose the same index j multiple times.For each i from 0 to n, determine whether Dmitry can make the \mathrm{MEX} of the array equal to exactly i. If it is possible, then determine the minimum number of operations to do it.The \mathrm{MEX} of the array is equal to the minimum non-negative integer that is not in the array. For example, the \mathrm{MEX} of the array [3, 1, 0] is equal to 2, and the array [3, 3, 1, 4] is equal to 0.InputThe first line of input data contains a single integer t (1 \le t \le 10^4) — the number of test cases in the input. The descriptions of the test cases follow.The first line of the description of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the array a.The second line of the description of each test case contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le n) — elements of the array a.It is guaranteed that the sum of the values n over all test cases in the test does not exceed 2\cdot10^5.OutputFor each test case, output n + 1 integer — i-th number is equal to the minimum number of operations for which you can make the array \mathrm{MEX} equal to i (0 \le i \le n), or -1 if this cannot be done.ExampleInput
5
3
0 1 3
7
0 1 2 3 4 3 2
4
3 0 0 0
7
4 6 2 3 5 0 5
5
4 0 1 0 4
Output
1 1 0 -1
1 1 2 2 1 0 2 6
3 0 1 4 3
1 0 -1 -1 -1 -1 -1 -1
2 1 0 2 -1 -1
NoteIn the first set of example inputs, n=3: to get \mathrm{MEX}=0, it is enough to perform one increment: a_1++; to get \mathrm{MEX}=1, it is enough to perform one increment: a_2++; \mathrm{MEX}=2 for a given array, so there is no need to perform increments; it is impossible to get \mathrm{MEX}=3 by performing increments. | 5
3
0 1 3
7
0 1 2 3 4 3 2
4
3 0 0 0
7
4 6 2 3 5 0 5
5
4 0 1 0 4
| 1 1 0 -1 1 1 2 2 1 0 2 6 3 0 1 4 3 1 0 -1 -1 -1 -1 -1 -1 2 1 0 2 -1 -1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'dp', 'greedy', 'implementation', 'math', 'sortings', '*1700'] |
D. New Year's Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVlad has n friends, for each of whom he wants to buy one gift for the New Year.There are m shops in the city, in each of which he can buy a gift for any of his friends. If the j-th friend (1 \le j \le n) receives a gift bought in the shop with the number i (1 \le i \le m), then the friend receives p_{ij} units of joy. The rectangular table p_{ij} is given in the input.Vlad has time to visit at most n-1 shops (where n is the number of friends). He chooses which shops he will visit and for which friends he will buy gifts in each of them.Let the j-th friend receive a_j units of joy from Vlad's gift. Let's find the value \alpha=\min\{a_1, a_2, \dots, a_n\}. Vlad's goal is to buy gifts so that the value of \alpha is as large as possible. In other words, Vlad wants to maximize the minimum of the joys of his friends.For example, let m = 2, n = 2. Let the joy from the gifts that we can buy in the first shop: p_{11} = 1, p_{12}=2, in the second shop: p_{21} = 3, p_{22}=4.Then it is enough for Vlad to go only to the second shop and buy a gift for the first friend, bringing joy 3, and for the second — bringing joy 4. In this case, the value \alpha will be equal to \min\{3, 4\} = 3Help Vlad choose gifts for his friends so that the value of \alpha is as high as possible. Please note that each friend must receive one gift. Vlad can visit at most n-1 shops (where n is the number of friends). In the shop, he can buy any number of gifts.InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases in the input.An empty line is written before each test case. Then there is a line containing integers m and n (2 \le n, 2 \le n \cdot m \le 10^5) separated by a space — the number of shops and the number of friends, where n \cdot m is the product of n and m.Then m lines follow, each containing n numbers. The number in the i-th row of the j-th column p_{ij} (1 \le p_{ij} \le 10^9) is the joy of the product intended for friend number j in shop number i.It is guaranteed that the sum of the values n \cdot m over all test cases in the test does not exceed 10^5.OutputPrint t lines, each line must contain the answer to the corresponding test case — the maximum possible value of \alpha, where \alpha is the minimum of the joys from a gift for all of Vlad's friends.ExampleInput
5
2 2
1 2
3 4
4 3
1 3 1
3 1 1
1 2 2
1 1 3
2 3
5 3 4
2 5 1
4 2
7 9
8 1
9 6
10 8
2 4
6 5 2 1
7 9 7 2
Output
3
2
4
8
2
| 5
2 2
1 2
3 4
4 3
1 3 1
3 1 1
1 2 2
1 1 3
2 3
5 3 4
2 5 1
4 2
7 9
8 1
9 6
10 8
2 4
6 5 2 1
7 9 7 2
| 3 2 4 8 2 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'sortings', '*1800'] |
C. Wrong Additiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya is learning how to add numbers, but so far she is not doing it correctly. She is adding two numbers a and b using the following algorithm: If one of the numbers is shorter than the other, Tanya adds leading zeros so that the numbers are the same length. The numbers are processed from right to left (that is, from the least significant digits to the most significant). In the first step, she adds the last digit of a to the last digit of b and writes their sum in the answer. At each next step, she performs the same operation on each pair of digits in the same place and writes the result to the left side of the answer. For example, the numbers a = 17236 and b = 3465 Tanya adds up as follows: \large{ \begin{array}{r} + \begin{array}{r} 17236\\ 03465\\ \end{array} \\ \hline \begin{array}{r} 1106911 \end{array} \end{array}} calculates the sum of 6 + 5 = 11 and writes 11 in the answer. calculates the sum of 3 + 6 = 9 and writes the result to the left side of the answer to get 911. calculates the sum of 2 + 4 = 6 and writes the result to the left side of the answer to get 6911. calculates the sum of 7 + 3 = 10, and writes the result to the left side of the answer to get 106911. calculates the sum of 1 + 0 = 1 and writes the result to the left side of the answer and get 1106911. As a result, she gets 1106911.You are given two positive integers a and s. Find the number b such that by adding a and b as described above, Tanya will get s. Or determine that no suitable b exists.InputThe first line of input data contains an integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of a single line containing two positive integers a and s (1 \le a \lt s \le 10^{18}) separated by a space.OutputFor each test case print the answer on a separate line.If the solution exists, print a single positive integer b. The answer must be written without leading zeros. If multiple answers exist, print any of them.If no suitable number b exists, output -1.ExampleInput
6
17236 1106911
1 5
108 112
12345 1023412
1 11
1 20
Output
3465
4
-1
90007
10
-1
NoteThe first test case is explained in the main part of the statement.In the third test case, we cannot choose b that satisfies the problem statement. | 6
17236 1106911
1 5
108 112
12345 1023412
1 11
1 20
| 3465 4 -1 90007 10 -1 | 1 second | 256 megabytes | ['implementation', '*1200'] |
B. Squares and Cubestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp likes squares and cubes of positive integers. Here is the beginning of the sequence of numbers he likes: 1, 4, 8, 9, ....For a given number n, count the number of integers from 1 to n that Polycarp likes. In other words, find the number of such x that x is a square of a positive integer number or a cube of a positive integer number (or both a square and a cube simultaneously).InputThe first line contains an integer t (1 \le t \le 20) — the number of test cases.Then t lines contain the test cases, one per line. Each of the lines contains one integer n (1 \le n \le 10^9).OutputFor each test case, print the answer you are looking for — the number of integers from 1 to n that Polycarp likes.ExampleInput
6
10
1
25
1000000000
999999999
500000000
Output
4
1
6
32591
32590
23125
| 6
10
1
25
1000000000
999999999
500000000
| 4 1 6 32591 32590 23125 | 1 second | 256 megabytes | ['implementation', 'math', '*800'] |
A. Square String?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string is called square if it is some string written twice in a row. For example, the strings "aa", "abcabc", "abab" and "baabaa" are square. But the strings "aaa", "abaaab" and "abcdabc" are not square.For a given string s determine if it is square.InputThe first line of input data contains an integer t (1 \le t \le 100) —the number of test cases.This is followed by t lines, each containing a description of one test case. The given strings consist only of lowercase Latin letters and have lengths between 1 and 100 inclusive.OutputFor each test case, output on a separate line: YES if the string in the corresponding test case is square, NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).ExampleInput
10
a
aa
aaa
aaaa
abab
abcabc
abacaba
xxyy
xyyx
xyxy
Output
NO
YES
NO
YES
YES
YES
NO
NO
NO
YES
| 10
a
aa
aaa
aaaa
abab
abcabc
abacaba
xxyy
xyyx
xyxy
| NO YES NO YES YES YES NO NO NO YES | 1 second | 256 megabytes | ['implementation', 'strings', '*800'] |
G. Trader Problemtime limit per test4.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp plays a computer game (yet again!). This game has a unique trading mechanics.To trade with a character, Monocarp has to choose one of the items he possesses and trade it for some item the other character possesses. Each item has an integer price. If Monocarp's chosen item has price x, then he can trade it for any item (exactly one item) with price not greater than x+k.Monocarp initially has n items, the price of the i-th item he has is a_i. The character Monocarp is trading with has m items, the price of the i-th item they have is b_i. Monocarp can trade with this character as many times as he wants (possibly even zero times), each time exchanging one of his items with one of the other character's items according to the aforementioned constraints. Note that if Monocarp gets some item during an exchange, he can trade it for another item (since now the item belongs to him), and vice versa: if Monocarp trades one of his items for another item, he can get his item back by trading something for it.You have to answer q queries. Each query consists of one integer, which is the value of k, and asks you to calculate the maximum possible total cost of items Monocarp can have after some sequence of trades, assuming that he can trade an item of cost x for an item of cost not greater than x+k during each trade. Note that the queries are independent: the trades do not actually occur, Monocarp only wants to calculate the maximum total cost he can get.InputThe first line contains three integers n, m and q (1 \le n, m, q \le 2 \cdot 10^5).The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the prices of the items Monocarp has.The third line contains m integers b_1, b_2, \dots, b_m (1 \le b_i \le 10^9) — the prices of the items the other character has.The fourth line contains q integers, where the i-th integer is the value of k for the i-th query (0 \le k \le 10^9).OutputFor each query, print one integer — the maximum possible total cost of items Monocarp can have after some sequence of trades, given the value of k from the query.ExampleInput
3 4 5
10 30 15
12 31 14 18
0 1 2 3 4
Output
55
56
60
64
64
| 3 4 5
10 30 15
12 31 14 18
0 1 2 3 4
| 55 56 60 64 64 | 4.5 seconds | 512 megabytes | ['data structures', 'dsu', 'greedy', 'sortings', '*2200'] |
F. Reversetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers x and y. You can perform the following operation with x: write it in its binary form without leading zeros, add 0 or 1 to the right of it, reverse the binary form and turn it into a decimal number which is assigned as the new value of x.For example: 34 can be turned into 81 via one operation: the binary form of 34 is 100010, if you add 1, reverse it and remove leading zeros, you will get 1010001, which is the binary form of 81. 34 can be turned into 17 via one operation: the binary form of 34 is 100010, if you add 0, reverse it and remove leading zeros, you will get 10001, which is the binary form of 17. 81 can be turned into 69 via one operation: the binary form of 81 is 1010001, if you add 0, reverse it and remove leading zeros, you will get 1000101, which is the binary form of 69. 34 can be turned into 69 via two operations: first you turn 34 into 81 and then 81 into 69. Your task is to find out whether x can be turned into y after a certain number of operations (possibly zero).InputThe only line of the input contains two integers x and y (1 \le x, y \le 10^{18}).OutputPrint YES if you can make x equal to y and NO if you can't.ExamplesInput
3 3
Output
YES
Input
7 4
Output
NO
Input
2 8
Output
NO
Input
34 69
Output
YES
Input
8935891487501725 71487131900013807
Output
YES
NoteIn the first example, you don't even need to do anything.The fourth example is described in the statement. | 3 3
| YES | 2 seconds | 256 megabytes | ['bitmasks', 'constructive algorithms', 'dfs and similar', 'implementation', 'math', 'strings', '*2000'] |
E. Singers' Tourtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputn towns are arranged in a circle sequentially. The towns are numbered from 1 to n in clockwise order. In the i-th town, there lives a singer with a repertoire of a_i minutes for each i \in [1, n].Each singer visited all n towns in clockwise order, starting with the town he lives in, and gave exactly one concert in each town. In addition, in each town, the i-th singer got inspired and came up with a song that lasts a_i minutes. The song was added to his repertoire so that he could perform it in the rest of the cities.Hence, for the i-th singer, the concert in the i-th town will last a_i minutes, in the (i + 1)-th town the concert will last 2 \cdot a_i minutes, ..., in the ((i + k) \bmod n + 1)-th town the duration of the concert will be (k + 2) \cdot a_i, ..., in the town ((i + n - 2) \bmod n + 1) — n \cdot a_i minutes.You are given an array of b integer numbers, where b_i is the total duration of concerts in the i-th town. Reconstruct any correct sequence of positive integers a or say that it is impossible.InputThe first line contains one integer t (1 \le t \le 10^3) — the number of test cases. Then the test cases follow.Each test case consists of two lines. The first line contains a single integer n (1 \le n \le 4 \cdot 10^4) — the number of cities. The second line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^{9}) — the total duration of concerts in i-th city.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print the answer as follows:If there is no suitable sequence a, print NO. Otherwise, on the first line print YES, on the next line print the sequence a_1, a_2, \dots, a_n of n integers, where a_i (1 \le a_i \le 10^{9}) is the initial duration of repertoire of the i-th singer. If there are multiple answers, print any of them.ExampleInput
4
3
12 16 14
1
1
3
1 2 3
6
81 75 75 93 93 87
Output
YES
3 1 3
YES
1
NO
YES
5 5 4 1 4 5
NoteLet's consider the 1-st test case of the example: the 1-st singer in the 1-st city will give a concert for 3 minutes, in the 2-nd — for 6 minutes, in the 3-rd — for 9 minutes; the 2-nd singer in the 1-st city will give a concert for 3 minutes, in the 2-nd — for 1 minute, in the 3-rd - for 2 minutes; the 3-rd singer in the 1-st city will give a concert for 6 minutes, in the 2-nd — for 9 minutes, in the 3-rd — for 3 minutes. | 4
3
12 16 14
1
1
3
1 2 3
6
81 75 75 93 93 87
| YES 3 1 3 YES 1 NO YES 5 5 4 1 4 5 | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', '*1700'] |
D. Array and Operationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers, and another integer k such that 2k \le n.You have to perform exactly k operations with this array. In one operation, you have to choose two elements of the array (let them be a_i and a_j; they can be equal or different, but their positions in the array must not be the same), remove them from the array, and add \lfloor \frac{a_i}{a_j} \rfloor to your score, where \lfloor \frac{x}{y} \rfloor is the maximum integer not exceeding \frac{x}{y}.Initially, your score is 0. After you perform exactly k operations, you add all the remaining elements of the array to the score.Calculate the minimum possible score you can get.InputThe first line of the input contains one integer t (1 \le t \le 500) — the number of test cases.Each test case consists of two lines. The first line contains two integers n and k (1 \le n \le 100; 0 \le k \le \lfloor \frac{n}{2} \rfloor).The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 2 \cdot 10^5).OutputPrint one integer — the minimum possible score you can get.ExampleInput
5
7 3
1 1 1 2 1 3 1
5 1
5 5 5 5 5
4 2
1 3 3 7
2 0
4 2
9 2
1 10 10 1 10 2 7 10 3
Output
2
16
0
6
16
NoteLet's consider the example test.In the first test case, one way to obtain a score of 2 is the following one: choose a_7 = 1 and a_4 = 2 for the operation; the score becomes 0 + \lfloor \frac{1}{2} \rfloor = 0, the array becomes [1, 1, 1, 1, 3]; choose a_1 = 1 and a_5 = 3 for the operation; the score becomes 0 + \lfloor \frac{1}{3} \rfloor = 0, the array becomes [1, 1, 1]; choose a_1 = 1 and a_2 = 1 for the operation; the score becomes 0 + \lfloor \frac{1}{1} \rfloor = 1, the array becomes [1]; add the remaining element 1 to the score, so the resulting score is 2. In the second test case, no matter which operations you choose, the resulting score is 16.In the third test case, one way to obtain a score of 0 is the following one: choose a_1 = 1 and a_2 = 3 for the operation; the score becomes 0 + \lfloor \frac{1}{3} \rfloor = 0, the array becomes [3, 7]; choose a_1 = 3 and a_2 = 7 for the operation; the score becomes 0 + \lfloor \frac{3}{7} \rfloor = 0, the array becomes empty; the array is empty, so the score doesn't change anymore. In the fourth test case, no operations can be performed, so the score is the sum of the elements of the array: 4 + 2 = 6. | 5
7 3
1 1 1 2 1 3 1
5 1
5 5 5 5 5
4 2
1 3 3 7
2 0
4 2
9 2
1 10 10 1 10 2 7 10 3
| 2 16 0 6 16 | 2 seconds | 512 megabytes | ['dp', 'greedy', 'math', '*1300'] |
C. Paint the Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n positive integers. You have to choose a positive integer d and paint all elements into two colors. All elements which are divisible by d will be painted red, and all other elements will be painted blue.The coloring is called beautiful if there are no pairs of adjacent elements with the same color in the array. Your task is to find any value of d which yields a beautiful coloring, or report that it is impossible.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.The first line of each testcase contains one integer n (2 \le n \le 100) — the number of elements of the array.The second line of each testcase contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{18}).OutputFor each testcase print a single integer. If there is no such value of d that yields a beautiful coloring, print 0. Otherwise, print any suitable value of d (1 \le d \le 10^{18}).ExampleInput
5
5
1 2 3 4 5
3
10 5 15
3
100 10 200
10
9 8 2 6 6 2 8 6 5 4
2
1 3
Output
2
0
100
0
3
| 5
5
1 2 3 4 5
3
10 5 15
3
100 10 200
10
9 8 2 6 6 2 8 6 5 4
2
1 3
| 2 0 100 0 3 | 2 seconds | 256 megabytes | ['math', '*1100'] |
B. Missing Bigramtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has come up with a new game to play with you. He calls it "A missing bigram".A bigram of a word is a sequence of two adjacent letters in it.For example, word "abbaaba" contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba".The game goes as follows. First, Polycarp comes up with a word, consisting only of lowercase letters 'a' and 'b'. Then, he writes down all its bigrams on a whiteboard in the same order as they appear in the word. After that, he wipes one of them off the whiteboard.Finally, Polycarp invites you to guess what the word that he has come up with was.Your goal is to find any word such that it's possible to write down all its bigrams and remove one of them, so that the resulting sequence of bigrams is the same as the one Polycarp ended up with.The tests are generated in such a way that the answer exists. If there are multiple answers, you can print any of them.InputThe first line contains a single integer t (1 \le t \le 2000) — the number of testcases.The first line of each testcase contains a single integer n (3 \le n \le 100) — the length of the word Polycarp has come up with.The second line of each testcase contains n-2 bigrams of that word, separated by a single space. Each bigram consists of two letters, each of them is either 'a' or 'b'.Additional constraint on the input: there exists at least one string such that it is possible to write down all its bigrams, except one, so that the resulting sequence is the same as the sequence in the input. In other words, the answer exists.OutputFor each testcase print a word, consisting of n letters, each of them should be either 'a' or 'b'. It should be possible to write down all its bigrams and remove one of them, so that the resulting sequence of bigrams is the same as the one Polycarp ended up with.The tests are generated in such a way that the answer exists. If there are multiple answers, you can print any of them. ExampleInput
4
7
ab bb ba aa ba
7
ab ba aa ab ba
3
aa
5
bb ab bb
Output
abbaaba
abaabaa
baa
bbabb
NoteThe first two testcases from the example are produced from the word "abbaaba". As listed in the statement, it contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba".In the first testcase, the 5-th bigram is removed. In the second testcase, the 2-nd bigram is removed. However, that sequence could also have been produced from the word "abaabaa". It contains bigrams "ab", "ba", "aa", "ab", "ba" and "aa". The missing bigram is the 6-th one.In the third testcase, all of "baa", "aab" and "aaa" are valid answers. | 4
7
ab bb ba aa ba
7
ab ba aa ab ba
3
aa
5
bb ab bb
| abbaaba abaabaa baa bbabb | 2 seconds | 256 megabytes | ['implementation', '*800'] |
A. Polycarp and Sums of Subsequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp had an array a of 3 positive integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array b of 7 integers.For example, if a = \{1, 4, 3\}, then Polycarp wrote out 1, 4, 3, 1 + 4 = 5, 1 + 3 = 4, 4 + 3 = 7, 1 + 4 + 3 = 8. After sorting, he got an array b = \{1, 3, 4, 4, 5, 7, 8\}.Unfortunately, Polycarp lost the array a. He only has the array b left. Help him to restore the array a.InputThe first line contains one integer t (1 \le t \le 5000) — the number of test cases.Each test case consists of one line which contains 7 integers b_1, b_2, \dots, b_7 (1 \le b_i \le 10^9; b_i \le b_{i+1}). Additional constraint on the input: there exists at least one array a which yields this array b as described in the statement.OutputFor each test case, print 3 integers — a_1, a_2 and a_3. If there can be several answers, print any of them.ExampleInput
5
1 3 4 4 5 7 8
1 2 3 4 5 6 7
300000000 300000000 300000000 600000000 600000000 600000000 900000000
1 1 2 999999998 999999999 999999999 1000000000
1 2 2 3 3 4 5
Output
1 4 3
4 1 2
300000000 300000000 300000000
999999998 1 1
1 2 2
NoteThe subsequence of the array a is a sequence that can be obtained from a by removing zero or more of its elements.Two subsequences are considered different if index sets of elements included in them are different. That is, the values of the elements don't matter in the comparison of subsequences. In particular, any array of length 3 has exactly 7 different non-empty subsequences. | 5
1 3 4 4 5 7 8
1 2 3 4 5 6 7
300000000 300000000 300000000 600000000 600000000 600000000 900000000
1 1 2 999999998 999999999 999999999 1000000000
1 2 2 3 3 4 5
| 1 4 3 4 1 2 300000000 300000000 300000000 999999998 1 1 1 2 2 | 1 second | 256 megabytes | ['math', 'sortings', '*800'] |
E. Christmas Chocolatestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputChristmas is coming, Icy has just received a box of chocolates from her grandparents! The box contains n chocolates. The i-th chocolate has a non-negative integer type a_i.Icy believes that good things come in pairs. Unfortunately, all types of chocolates are distinct (all a_i are distinct). Icy wants to make at least one pair of chocolates the same type. As a result, she asks her grandparents to perform some chocolate exchanges. Before performing any chocolate exchanges, Icy chooses two chocolates with indices x and y (1 \le x, y \le n, x \ne y).In a chocolate exchange, Icy's grandparents choose a non-negative integer k, such that 2^k \ge a_x, and change the type of the chocolate x from a_x to 2^k - a_x (that is, perform a_x := 2^k - a_x).The chocolate exchanges will be stopped only when a_x = a_y. Note that other pairs of equal chocolate types do not stop the procedure.Icy's grandparents are smart, so they would choose the sequence of chocolate exchanges that minimizes the number of exchanges needed. Since Icy likes causing trouble, she wants to maximize the minimum number of exchanges needed by choosing x and y appropriately. She wonders what is the optimal pair (x, y) such that the minimum number of exchanges needed is maximized across all possible choices of (x, y).Since Icy is not good at math, she hopes that you can help her solve the problem.InputThe first line of the input contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of chocolates.The second line of the input contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^9).It is guaranteed that all a_i are distinct.OutputOutput three integers x, y, and m.x and y are indices of the optimal chocolates to perform exchanges on. Your output must satisfy 1 \le x, y \le n, x \ne y.m is the number of exchanges needed to obtain a_x = a_y. We can show that m \le 10^9 for any pair of chocolates.If there are multiple solutions, output any.ExamplesInput
5
5 6 7 8 9
Output
2 5 5
Input
2
4 8
Output
1 2 2NoteIn the first test case, the minimum number of exchanges needed to exchange a chocolate of type 6 to a chocolate of type 9 is 5. The sequence of exchanges is as follows: 6 \rightarrow 2 \rightarrow 0 \rightarrow 1 \rightarrow 7 \rightarrow 9.In the second test case, the minimum number of exchanges needed to exchange a chocolate of type 4 to a chocolate of type 8 is 2. The sequence of exchanges is as follows: 4 \rightarrow 0 \rightarrow 8. | 5
5 6 7 8 9
| 2 5 5 | 4 seconds | 512 megabytes | ['dfs and similar', 'dp', 'games', 'graphs', 'implementation', 'math', 'number theory', 'shortest paths', 'trees', '*2700'] |
D2. Too Many Impostors (hard version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. The only difference between the easy and hard version is the limit on number of questions.There are n players labelled from 1 to n. It is guaranteed that n is a multiple of 3.Among them, there are k impostors and n-k crewmates. The number of impostors, k, is not given to you. It is guaranteed that \frac{n}{3} < k < \frac{2n}{3}.In each question, you can choose three distinct integers a, b, c (1 \le a, b, c \le n) and ask: "Among the players labelled a, b and c, are there more impostors or more crewmates?" You will be given the integer 0 if there are more impostors than crewmates, and 1 otherwise.Find the number of impostors k and the indices of players that are impostors after asking at most n+6 questions.The jury is adaptive, which means the indices of impostors may not be fixed beforehand and can depend on your questions. It is guaranteed that there is at least one set of impostors which fulfills the constraints and the answers to your questions at any time.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first and only line of each test case contains a single integer n (6 \le n < 10^4, n is a multiple of 3) — the number of players.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^4.InteractionFor each test case, the interaction starts with reading n.Then you are allowed to make at most n+6 questions in the following way:"? a b c" (1 \le a, b, c \le n, a, b and c are pairwise distinct).After each one, you should read an integer r, which is equal to 0 if there are more impostors than crewmates among players labelled a, b and c, and equal to 1 otherwise.Answer -1 instead of 0 or 1 means that you made an invalid query. Exit immediately after receiving -1 and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.When you have found the indices of all impostors, print a single line "! " (without quotes), followed by the number of impostors k, followed by k integers representing the indices of the impostors. Please note that you must print all this information on the same line. After printing the answer, your program must then continue to solve the remaining test cases, or exit if all test cases have been solved.After printing the queries and answers do not forget to output end of line and flush the output buffer. Otherwise, you will get the Idleness limit exceeded verdict. To do flush use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; Read documentation for other languages. HacksYou cannot make hacks in this problem.ExampleInput
2
6
0
1
9
1Output
? 1 2 3
? 3 4 5
! 3 4 1 2
? 7 1 9
! 4 2 3 6 8NoteExplanation for example interaction (note that this example only exists to demonstrate the interaction procedure and does not provide any hint for the solution):For the first test case:Question "? 1 2 3" returns 0, so there are more impostors than crewmates among players 1, 2 and 3.Question "? 3 4 5" returns 1, so there are more crewmates than impostors among players 3, 4 and 5.Outputting "! 3 4 1 2" means that one has found all the impostors, by some miracle. There are k = 3 impostors. The players who are impostors are players 4, 1 and 2.For the second test case:Question "? 7 1 9" returns 1, so there are more crewmates than impostors among players 7, 1 and 9.Outputting "! 4 2 3 6 8" means that one has found all the impostors, by some miracle. There are k = 4 impostors. The players who are impostors are players 2, 3, 6 and 8. | 2
6
0
1
9
1 | ? 1 2 3 ? 3 4 5 ! 3 4 1 2 ? 7 1 9 ! 4 2 3 6 8 | 3 seconds | 256 megabytes | ['constructive algorithms', 'implementation', 'interactive', 'math', '*2400'] |
D1. Too Many Impostors (easy version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. The only difference between the easy and hard version is the limit on number of questions.There are n players labelled from 1 to n. It is guaranteed that n is a multiple of 3.Among them, there are k impostors and n-k crewmates. The number of impostors, k, is not given to you. It is guaranteed that \frac{n}{3} < k < \frac{2n}{3}.In each question, you can choose three distinct integers a, b, c (1 \le a, b, c \le n) and ask: "Among the players labelled a, b and c, are there more impostors or more crewmates?" You will be given the integer 0 if there are more impostors than crewmates, and 1 otherwise.Find the number of impostors k and the indices of players that are impostors after asking at most 2n questions.The jury is adaptive, which means the indices of impostors may not be fixed beforehand and can depend on your questions. It is guaranteed that there is at least one set of impostors which fulfills the constraints and the answers to your questions at any time.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first and only line of each test case contains a single integer n (6 \le n < 10^4, n is a multiple of 3) — the number of players.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^4.InteractionFor each test case, the interaction starts with reading n.Then you are allowed to make at most 2n questions in the following way:"? a b c" (1 \le a, b, c \le n, a, b and c are pairwise distinct).After each one, you should read an integer r, which is equal to 0 if there are more impostors than crewmates among players labelled a, b and c, and equal to 1 otherwise.Answer -1 instead of 0 or 1 means that you made an invalid query or exceeded the number of queries. Exit immediately after receiving -1 and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.When you have found the indices of all impostors, print a single line "! " (without quotes), followed by the number of impostors k, followed by k integers representing the indices of the impostors. Please note that you must print all this information on the same line. After printing the answer, your program must then continue to solve the remaining test cases, or exit if all test cases have been solved.After printing the queries and answers do not forget to output end of line and flush the output buffer. Otherwise, you will get the Idleness limit exceeded verdict. To do flush use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; Read documentation for other languages. HacksYou cannot make hacks in this problem.ExampleInput
2
6
0
1
9
1Output
? 1 2 3
? 3 4 5
! 3 4 1 2
? 7 1 9
! 4 2 3 6 8NoteExplanation for example interaction (note that this example only exists to demonstrate the interaction procedure and does not provide any hint for the solution):For the first test case:Question "? 1 2 3" returns 0, so there are more impostors than crewmates among players 1, 2 and 3.Question "? 3 4 5" returns 1, so there are more crewmates than impostors among players 3, 4 and 5.Outputting "! 3 4 1 2" means that one has found all the impostors, by some miracle. There are k = 3 impostors. The players who are impostors are players 4, 1 and 2.For the second test case:Question "? 7 1 9" returns 1, so there are more crewmates than impostors among players 7, 1 and 9.Outputting "! 4 2 3 6 8" means that one has found all the impostors, by some miracle. There are k = 4 impostors. The players who are impostors are players 2, 3, 6 and 8. | 2
6
0
1
9
1 | ? 1 2 3 ? 3 4 5 ! 3 4 1 2 ? 7 1 9 ! 4 2 3 6 8 | 3 seconds | 256 megabytes | ['constructive algorithms', 'implementation', 'interactive', '*1800'] |
C. Paprika and Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPaprika loves permutations. She has an array a_1, a_2, \dots, a_n. She wants to make the array a permutation of integers 1 to n.In order to achieve this goal, she can perform operations on the array. In each operation she can choose two integers i (1 \le i \le n) and x (x > 0), then perform a_i := a_i \bmod x (that is, replace a_i by the remainder of a_i divided by x). In different operations, the chosen i and x can be different.Determine the minimum number of operations needed to make the array a permutation of integers 1 to n. If it is impossible, output -1.A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 10^5).The second line of each test case contains n integers a_1, a_2, \dots, a_n. (1 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the minimum number of operations needed to make the array a permutation of integers 1 to n, or -1 if it is impossible.ExampleInput
4
2
1 7
3
1 5 4
4
12345678 87654321 20211218 23571113
9
1 2 3 4 18 19 5 6 7
Output
1
-1
4
2
NoteFor the first test, the only possible sequence of operations which minimizes the number of operations is: Choose i=2, x=5. Perform a_2 := a_2 \bmod 5 = 2. For the second test, it is impossible to obtain a permutation of integers from 1 to n. | 4
2
1 7
3
1 5 4
4
12345678 87654321 20211218 23571113
9
1 2 3 4 18 19 5 6 7
| 1 -1 4 2 | 1 second | 256 megabytes | ['binary search', 'greedy', 'math', 'sortings', '*1300'] |
B. GCD Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a positive integer n. Find three distinct positive integers a, b, c such that a + b + c = n and \operatorname{gcd}(a, b) = c, where \operatorname{gcd}(x, y) denotes the greatest common divisor (GCD) of integers x and y.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^5) — the number of test cases. Description of the test cases follows.The first and only line of each test case contains a single integer n (10 \le n \le 10^9).OutputFor each test case, output three distinct positive integers a, b, c satisfying the requirements. If there are multiple solutions, you can print any. We can show that an answer always exists.ExampleInput
6
18
63
73
91
438
122690412
Output
6 9 3
21 39 3
29 43 1
49 35 7
146 219 73
28622 122661788 2NoteIn the first test case, 6 + 9 + 3 = 18 and \operatorname{gcd}(6, 9) = 3.In the second test case, 21 + 39 + 3 = 63 and \operatorname{gcd}(21, 39) = 3.In the third test case, 29 + 43 + 1 = 73 and \operatorname{gcd}(29, 43) = 1. | 6
18
63
73
91
438
122690412
| 6 9 3 21 39 3 29 43 1 49 35 7 146 219 73 28622 122661788 2 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'math', 'number theory', '*900'] |
A. Forbidden Subsequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given strings S and T, consisting of lowercase English letters. It is guaranteed that T is a permutation of the string abc. Find string S', the lexicographically smallest permutation of S such that T is not a subsequence of S'.String a is a permutation of string b if the number of occurrences of each distinct character is the same in both strings.A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) elements.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Description of the test cases follows.The first line of each test case contains a string S (1 \le |S| \le 100), consisting of lowercase English letters.The second line of each test case contains a string T that is a permutation of the string abc. (Hence, |T| = 3).Note that there is no limit on the sum of |S| across all test cases.OutputFor each test case, output a single string S', the lexicographically smallest permutation of S such that T is not a subsequence of S'.ExampleInput
7
abacaba
abc
cccba
acb
dbsic
bac
abracadabra
abc
dddddddddddd
cba
bbc
abc
ac
abc
Output
aaaacbb
abccc
bcdis
aaaaacbbdrr
dddddddddddd
bbc
ac
NoteIn the first test case, both aaaabbc and aaaabcb are lexicographically smaller than aaaacbb, but they contain abc as a subsequence.In the second test case, abccc is the smallest permutation of cccba and does not contain acb as a subsequence.In the third test case, bcdis is the smallest permutation of dbsic and does not contain bac as a subsequence. | 7
abacaba
abc
cccba
acb
dbsic
bac
abracadabra
abc
dddddddddddd
cba
bbc
abc
ac
abc
| aaaacbb abccc bcdis aaaaacbbdrr dddddddddddd bbc ac | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'sortings', 'strings', '*800'] |
H. Keep XOR Lowtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \ldots, a_n and an integer x.Find the number of non-empty subsets of indices of this array 1 \leq b_1 < b_2 < \ldots < b_k \leq n, such that for all pairs (i, j) where 1 \leq i < j \leq k, the inequality a_{b_i} \oplus a_{b_j} \leq x is held. Here, \oplus denotes the bitwise XOR operation. As the answer may be very large, output it modulo 998\,244\,353.InputThe first line of the input contains two integers n and x (1 \leq n \leq 150\,000, 0 \leq x < 2^{30}). Here, n is the size of the array.The next line contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i < 2^{30}): the array itself.OutputPrint one integer: the number of non-empty subsets such that the bitwise XOR of every pair of elements is at most x, modulo 998\,244\,353.ExamplesInput
4 2
0 1 2 3
Output
8
Input
3 6
4 2 2
Output
7
Input
4 0
1 1 2 2
Output
6
| 4 2
0 1 2 3
| 8 | 1 second | 256 megabytes | ['bitmasks', 'combinatorics', 'data structures', 'divide and conquer', 'dp', 'math', '*3000'] |
G. Just Add an Edgetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a directed acyclic graph with n vertices and m edges. For all edges a \to b in the graph, a < b holds.You need to find the number of pairs of vertices x, y, such that x > y and after adding the edge x \to y to the graph, it has a Hamiltonian path. InputThe first line of input contains one integer t (1 \leq t \leq 5): the number of test cases.The next lines contains the descriptions of the test cases.In the first line you are given two integers n and m (1 \leq n \leq 150\,000, 0 \leq m \leq \min(150\,000, \frac{n(n-1)}{2})): the number of vertices and edges in the graph. Each of the next m lines contains two integers a, b (1 \leq a < b \leq n), specifying an edge a \to b in the graph. No edge a \to b appears more than once.OutputFor each test case, print one integer: the number of pairs of vertices x, y, x > y, such that after adding the edge x \to y to the graph, it has a Hamiltonian path. ExampleInput
3
3 2
1 2
2 3
4 3
1 2
3 4
1 4
4 4
1 3
1 4
2 3
3 4
Output
3
1
4
NoteIn the first example, any edge x \to y such that x > y is valid, because there already is a path 1 \to 2 \to 3.In the second example only the edge 4 \to 1 is valid. There is a path 3 \to 4 \to 1 \to 2 if this edge is added.In the third example you can add edges 2 \to 1, 3 \to 1, 4 \to 1, 4 \to 2. | 3
3 2
1 2
2 3
4 3
1 2
3 4
1 4
4 4
1 3
1 4
2 3
3 4
| 3 1 4 | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'graphs', '*3500'] |
F. Tricolor Trianglestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a simple undirected graph with n vertices and m edges. Edge i is colored in the color c_i, which is either 1, 2, or 3, or left uncolored (in this case, c_i = -1).You need to color all of the uncolored edges in such a way that for any three pairwise adjacent vertices 1 \leq a < b < c \leq n, the colors of the edges a \leftrightarrow b, b \leftrightarrow c, and a \leftrightarrow c are either pairwise different, or all equal. In case no such coloring exists, you need to determine that.InputThe first line of input contains one integer t (1 \leq t \leq 10): the number of test cases.The following lines contain the description of the test cases.In the first line you are given two integers n and m (3 \leq n \leq 64, 0 \leq m \leq \min(256, \frac{n(n-1)}{2})): the number of vertices and edges in the graph.Each of the next m lines contains three integers a_i, b_i, and c_i (1 \leq a_i, b_i \leq n, a_i \ne b_i, c_i is either -1, 1, 2, or 3), denoting an edge between a_i and b_i with color c_i. It is guaranteed that no two edges share the same endpoints.OutputFor each test case, print m integers d_1, d_2, \ldots, d_m, where d_i is the color of the i-th edge in your final coloring. If there is no valid way to finish the coloring, print -1.ExampleInput
4
3 3
1 2 1
2 3 2
3 1 -1
3 3
1 2 1
2 3 1
3 1 -1
4 4
1 2 -1
2 3 -1
3 4 -1
4 1 -1
3 3
1 2 1
2 3 1
3 1 2
Output
1 2 3
1 1 1
1 2 2 3
-1
| 4
3 3
1 2 1
2 3 2
3 1 -1
3 3
1 2 1
2 3 1
3 1 -1
4 4
1 2 -1
2 3 -1
3 4 -1
4 1 -1
3 3
1 2 1
2 3 1
3 1 2
| 1 2 3 1 1 1 1 2 2 3 -1 | 1 second | 256 megabytes | ['brute force', 'graphs', 'math', 'matrices', '*2900'] |
E. Lexicographically Small Enoughtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t of equal length n. In one move, you can swap any two adjacent characters of the string s.You need to find the minimal number of operations you need to make string s lexicographically smaller than string t.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. InputThe first line of input contains one integer q (1 \le q \le 10\,000): the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 10^5).The second line of each test case contains the string s consisting of n lowercase English letters.The third line of each test case contains the string t consisting of n lowercase English letters.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print in a separate line the minimal number of operations you need to make string s lexicographically smaller than string t, or -1, if it's impossible.ExampleInput
4
1
a
a
3
rll
rrr
3
caa
aca
5
ababa
aabba
Output
-1
0
2
2
| 4
1
a
a
3
rll
rrr
3
caa
aca
5
ababa
aabba
| -1 0 2 2 | 1 second | 256 megabytes | ['brute force', 'data structures', 'greedy', 'strings', '*2200'] |
D. Keep the Average Hightime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of integers a_1, a_2, \ldots, a_n and an integer x.You need to select the maximum number of elements in the array, such that for every subsegment a_l, a_{l + 1}, \ldots, a_r containing strictly more than one element (l < r), either: At least one element on this subsegment is not selected, or a_l + a_{l+1} + \ldots + a_r \geq x \cdot (r - l + 1). InputThe first line of input contains one integer t (1 \leq t \leq 10): the number of test cases.The descriptions of t test cases follow, three lines per test case.In the first line you are given one integer n (1 \leq n \leq 50\,000): the number of integers in the array.The second line contains n integers a_1, a_2, \ldots, a_n (-100\,000 \leq a_i \leq 100\,000).The third line contains one integer x (-100\,000 \leq x \leq 100\,000).OutputFor each test case, print one integer: the maximum number of elements that you can select.ExampleInput
4
5
1 2 3 4 5
2
10
2 4 2 4 2 4 2 4 2 4
3
3
-10 -5 -10
-8
3
9 9 -3
5
Output
4
8
2
2
NoteIn the first example, one valid way to select the elements is [\underline{1}, 2, \underline{3}, \underline{4}, \underline{5}]. All subsegments satisfy at least one of the criteria. For example, for the subsegment l = 1, r = 2 we have that the element 2 is not selected, satisfying the first criterion. For the subsegment l = 3, r = 5 we have 3 + 4 + 5 = 12 \ge 2 \cdot 3, satisfying the second criterion.We can't select all elements, because in this case for l = 1, r = 2 all elements are selected and we have a_1 + a_2 = 3 < 2 \cdot 2. Thus, the maximum number of selected elements is 4.In the second example, one valid solution is [\underline{2}, \underline{4}, 2, \underline{4}, \underline{2}, \underline{4}, 2, \underline{4}, \underline{2}, \underline{4}].In the third example, one valid solution is [\underline{-10}, -5, \underline{-10}].In the fourth example, one valid solution is [\underline{9}, \underline{9}, -3]. | 4
5
1 2 3 4 5
2
10
2 4 2 4 2 4 2 4 2 4
3
3
-10 -5 -10
-8
3
9 9 -3
5
| 4 8 2 2 | 1.5 seconds | 256 megabytes | ['dp', 'greedy', 'math', '*2000'] |
C. Representative Edgestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array a_1, a_2, \ldots, a_n is good if and only if for every subsegment 1 \leq l \leq r \leq n, the following holds: a_l + a_{l + 1} + \ldots + a_r = \frac{1}{2}(a_l + a_r) \cdot (r - l + 1). You are given an array of integers a_1, a_2, \ldots, a_n. In one operation, you can replace any one element of this array with any real number. Find the minimum number of operations you need to make this array good.InputThe first line of input contains one integer t (1 \leq t \leq 100): the number of test cases.Each of the next t lines contains the description of a test case.In the first line you are given one integer n (1 \leq n \leq 70): the number of integers in the array.The second line contains n integers a_1, a_2, \ldots, a_n (-100 \leq a_i \leq 100): the initial array.OutputFor each test case, print one integer: the minimum number of elements that you need to replace to make the given array good.ExampleInput
5
4
1 2 3 4
4
1 1 2 2
2
0 -1
6
3 -2 4 -1 -4 0
1
-100
Output
0
2
0
3
0
NoteIn the first test case, the array is good already.In the second test case, one of the possible good arrays is [1, 1, \underline{1}, \underline{1}] (replaced elements are underlined).In the third test case, the array is good already.In the fourth test case, one of the possible good arrays is [\underline{-2.5}, -2, \underline{-1.5}, -1, \underline{-0.5}, 0]. | 5
4
1 2 3 4
4
1 1 2 2
2
0 -1
6
3 -2 4 -1 -4 0
1
-100
| 0 2 0 3 0 | 1 second | 256 megabytes | ['brute force', 'geometry', 'implementation', 'math', '*1500'] |
B. Mirror in the Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a string s_1 s_2 \ldots s_n and you stand on the left of the string looking right. You want to choose an index k (1 \le k \le n) and place a mirror after the k-th letter, so that what you see is s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1. What is the lexicographically smallest string you can see?A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. InputThe first line of input contains one integer t (1 \leq t \leq 10\,000): the number of test cases.The next t lines contain the description of the test cases, two lines per a test case.In the first line you are given one integer n (1 \leq n \leq 10^5): the length of the string.The second line contains the string s consisting of n lowercase English characters.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case print the lexicographically smallest string you can see.ExampleInput
4
10
codeforces
9
cbacbacba
3
aaa
4
bbaa
Output
cc
cbaabc
aa
bb
NoteIn the first test case choose k = 1 to obtain "cc".In the second test case choose k = 3 to obtain "cbaabc".In the third test case choose k = 1 to obtain "aa".In the fourth test case choose k = 1 to obtain "bb". | 4
10
codeforces
9
cbacbacba
3
aaa
4
bbaa
| cc cbaabc aa bb | 1 second | 256 megabytes | ['greedy', 'strings', '*1100'] |
A. Integer Diversitytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers a_1, a_2, \ldots, a_n. You choose any subset of the given numbers (possibly, none or all numbers) and negate these numbers (i. e. change x \to (-x)). What is the maximum number of different values in the array you can achieve?InputThe first line of input contains one integer t (1 \leq t \leq 100): the number of test cases.The next lines contain the description of the t test cases, two lines per a test case.In the first line you are given one integer n (1 \leq n \leq 100): the number of integers in the array.The second line contains n integers a_1, a_2, \ldots, a_n (-100 \leq a_i \leq 100).OutputFor each test case, print one integer: the maximum number of different elements in the array that you can achieve negating numbers in the array.ExampleInput
3
4
1 1 2 2
3
1 2 3
2
0 0
Output
4
3
1
NoteIn the first example we can, for example, negate the first and the last numbers, achieving the array [-1, 1, 2, -2] with four different values.In the second example all three numbers are already different.In the third example negation does not change anything. | 3
4
1 1 2 2
3
1 2 3
2
0 0
| 4 3 1 | 1 second | 256 megabytes | ['implementation', '*800'] |
H. Reindeer Gamestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n reindeer at the North Pole, all battling for the highest spot on the "Top Reindeer" leaderboard on the front page of CodeNorses (a popular competitive reindeer gaming website). Interestingly, the "Top Reindeer" title is just a measure of upvotes and has nothing to do with their skill level in the reindeer games, but they still give it the utmost importance.Currently, the i-th reindeer has a score of a_i. You would like to influence the leaderboard with some operations. In an operation, you can choose a reindeer, and either increase or decrease his score by 1 unit. Negative scores are allowed.You have m requirements for the resulting scores. Each requirement is given by an ordered pair (u, v), meaning that after all operations, the score of reindeer u must be less than or equal to the score of reindeer v.Your task is to perform the minimum number of operations so that all requirements will be satisfied.InputThe first line contains two integers n and m (2\le n\le 1000; 1\le m\le 1000) — the number of reindeer and requirements, respectively.The second line contains n integers a_1,\ldots, a_n (1\le a_i\le 10^9), where a_i is the current score of reindeer i.The next m lines describe the requirements.The i-th of these lines contains two integers u_i and v_i (1\le u_i, v_i\le n; u_i\ne v_i) — the two reindeer of the i-th requirement.OutputPrint n integers b_1,\ldots, b_n (-10^{15}\le b_i\le 10^{15}), where b_i is the score of the i-th reindeer after all operations.If there are multiple solutions achieving the minimum number of operations, you may output any.We can prove that there is always an optimal solution such that |b_i|\le 10^{15} for all i.ExamplesInput
7 6
3 1 4 9 2 5 6
1 2
2 3
3 4
4 5
5 6
6 7
Output
1 1 4 4 4 5 6
Input
4 6
6 5 8 2
3 1
4 1
3 2
1 2
2 3
3 1
Output
6 6 6 2
Input
10 18
214 204 195 182 180 176 176 172 169 167
1 2
3 2
4 2
5 2
6 2
7 2
8 2
9 2
10 2
6 1
6 2
6 3
6 4
6 5
6 7
6 8
6 9
6 10
Output
204 204 195 182 180 167 176 172 169 167
| 7 6
3 1 4 9 2 5 6
1 2
2 3
3 4
4 5
5 6
6 7
| 1 1 4 4 4 5 6 | 2 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'data structures', 'divide and conquer', 'flows', 'graphs', 'shortest paths', '*3000'] |
G. Maximum Adjacent Pairstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n non-negative integers.You have to replace each 0 in a with an integer from 1 to n (different elements equal to 0 can be replaced by different integers).The value of the array you obtain is the number of integers k from 1 to n such that the following condition holds: there exist a pair of adjacent elements equal to k (i. e. there exists some i \in [1, n - 1] such that a_i = a_{i + 1} = k). If there are multiple such pairs for some integer k, this integer is counted in the value only once.Your task is to obtain the array with the maximum possible value.InputThe first line contains one integer n (2 \le n \le 3 \cdot 10^5) — the number of elements in the array.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le \min(n, 600)) — the elements of the array.OutputPrint n integers not less than 1 and not greater than n — the array with the maximum possible value you can obtain.If there are multiple answers, print any of them.ExamplesInput
4
1 1 0 2
Output
1 1 2 2
Input
5
0 0 0 0 0
Output
3 1 1 3 3
Input
5
1 2 3 4 5
Output
1 2 3 4 5
Input
6
1 0 0 0 0 1
Output
1 2 3 3 1 1
Input
3
3 0 2
Output
3 2 2
Input
5
1 0 2 0 1
Output
1 2 2 1 1
Input
7
1 0 2 3 1 0 2
Output
1 2 2 3 1 1 2
| 4
1 1 0 2
| 1 1 2 2 | 3 seconds | 512 megabytes | ['constructive algorithms', 'graph matchings', '*3300'] |
F. LEGOndary Grandmastertime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAfter getting bored by playing with crayons, you decided to switch to Legos! Today, you're working with a long strip, with height 1 and length n, some positions of which are occupied by 1 by 1 Lego pieces.In one second, you can either remove two adjacent Lego pieces from the strip (if both are present), or add two Lego pieces to adjacent positions (if both are absent). You can only add or remove Lego's at two adjacent positions at the same time, as otherwise your chubby fingers run into precision issues.You want to know exactly how much time you'll spend playing with Legos. You value efficiency, so given some starting state and some ending state, you'll always spend the least number of seconds to transform the starting state into the ending state. If it's impossible to transform the starting state into the ending state, you just skip it (so you spend 0 seconds).The issue is that, for some positions, you don't remember whether there were Legos there or not (in either the starting state, the ending state, or both). Over all pairs of (starting state, ending state) that are consistent with your memory, find the total amount of time it will take to transform the starting state to the ending state. Print this value modulo 1\,000\,000\,007 (10^9 + 7). InputThe first line contains one integer t (1 \leq t \leq 1000) — the number of test cases. Then t cases follow.The first line of each test case contains one integer n (2 \leq n \leq 2000) — the size of the Lego strip.The second line of each test case contains a string s of length n, consisting of the characters 0, 1, and ? — your memory of the starting state: 1 represents a position that definitely has a Lego piece, 0 represents a position that definitely does not have a Lego piece, and ? represents a position that you don't remember. The third line of each test case contains a string t of length n, consisting of the characters 0, 1, and ? — your memory of the ending state. It follows a similar format to the starting state.It's guaranteed that the sum of n over all test cases doesn't exceed 2000.OutputFor each test case, output a single integer — the answer to the problem modulo 1\,000\,000\,007 (10^9 + 7). ExampleInput
6
2
00
11
3
???
???
3
??1
0?0
4
??0?
??11
5
?????
0??1?
10
?01??01?1?
??100?1???
Output
1
16
1
14
101
1674
NoteFor the first test case, 00 is the only possible starting state, and 11 is the only possible ending state. It takes exactly one operation to change 00 to 11.For the second test case, some of the possible starting and ending state pairs are: (000, 011) — takes 1 operation. (001, 100) — takes 2 operations. (010, 000) — takes 0 operations, as it's impossible to achieve the ending state. | 6
2
00
11
3
???
???
3
??1
0?0
4
??0?
??11
5
?????
0??1?
10
?01??01?1?
??100?1???
| 1 16 1 14 101 1674 | 2 seconds | 512 megabytes | ['combinatorics', 'dp', 'math', '*2800'] |
E. Purple Crayontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo players, Red and Blue, are at it again, and this time they're playing with crayons! The mischievous duo is now vandalizing a rooted tree, by coloring the nodes while playing their favorite game.The game works as follows: there is a tree of size n, rooted at node 1, where each node is initially white. Red and Blue get one turn each. Red goes first. In Red's turn, he can do the following operation any number of times: Pick any subtree of the rooted tree, and color every node in the subtree red. However, to make the game fair, Red is only allowed to color k nodes of the tree. In other words, after Red's turn, at most k of the nodes can be colored red.Then, it's Blue's turn. Blue can do the following operation any number of times: Pick any subtree of the rooted tree, and color every node in the subtree blue. However, he's not allowed to choose a subtree that contains a node already colored red, as that would make the node purple and no one likes purple crayon. Note: there's no restriction on the number of nodes Blue can color, as long as he doesn't color a node that Red has already colored.After the two turns, the score of the game is determined as follows: let w be the number of white nodes, r be the number of red nodes, and b be the number of blue nodes. The score of the game is w \cdot (r - b).Red wants to maximize this score, and Blue wants to minimize it. If both players play optimally, what will the final score of the game be?InputThe first line contains two integers n and k (2 \le n \le 2 \cdot 10^5; 1 \le k \le n) — the number of vertices in the tree and the maximum number of red nodes.Next n - 1 lines contains description of edges. The i-th line contains two space separated integers u_i and v_i (1 \le u_i, v_i \le n; u_i \neq v_i) — the i-th edge of the tree.It's guaranteed that given edges form a tree.OutputPrint one integer — the resulting score if both Red and Blue play optimally.ExamplesInput
4 2
1 2
1 3
1 4
Output
1
Input
5 2
1 2
2 3
3 4
4 5
Output
6
Input
7 2
1 2
1 3
4 2
3 5
6 3
6 7
Output
4
Input
4 1
1 2
1 3
1 4
Output
-1
NoteIn the first test case, the optimal strategy is as follows: Red chooses to color the subtrees of nodes 2 and 3. Blue chooses to color the subtree of node 4. At the end of this process, nodes 2 and 3 are red, node 4 is blue, and node 1 is white. The score of the game is 1 \cdot (2 - 1) = 1.In the second test case, the optimal strategy is as follows: Red chooses to color the subtree of node 4. This colors both nodes 4 and 5. Blue does not have any options, so nothing is colored blue. At the end of this process, nodes 4 and 5 are red, and nodes 1, 2 and 3 are white. The score of the game is 3 \cdot (2 - 0) = 6.For the third test case: The score of the game is 4 \cdot (2 - 1) = 4. | 4 2
1 2
1 3
1 4
| 1 | 2 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'games', 'graphs', 'greedy', 'math', 'sortings', 'trees', '*2400'] |
D. X(or)-mas Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output'Twas the night before Christmas, and Santa's frantically setting up his new Christmas tree! There are n nodes in the tree, connected by n-1 edges. On each edge of the tree, there's a set of Christmas lights, which can be represented by an integer in binary representation. He has m elves come over and admire his tree. Each elf is assigned two nodes, a and b, and that elf looks at all lights on the simple path between the two nodes. After this, the elf's favorite number becomes the bitwise XOR of the values of the lights on the edges in that path.However, the North Pole has been recovering from a nasty bout of flu. Because of this, Santa forgot some of the configurations of lights he had put on the tree, and he has already left the North Pole! Fortunately, the elves came to the rescue, and each one told Santa what pair of nodes he was assigned (a_i, b_i), as well as the parity of the number of set bits in his favorite number. In other words, he remembers whether the number of 1's when his favorite number is written in binary is odd or even.Help Santa determine if it's possible that the memories are consistent, and if it is, remember what his tree looked like, and maybe you'll go down in history!InputThe first line contains one integer t (1 \leq t \leq 2 \cdot 10^4) — the number of test cases. Then t cases follow.The first line of each test case contains two integers, n and m (2 \leq n \leq 2 \cdot 10^5; 1 \leq m \leq 2 \cdot 10^5) — the size of tree and the number of elves respectively.The next n-1 lines of each test case each contains three integers, x, y, and v (1 \leq x, y \leq n; -1 \leq v < 2^{30}) — meaning that there's an edge between nodes x and y. If v = -1: Santa doesn't remember what the set of lights were on for this edge. v \geq 0: The set of lights on the edge is v. The next m lines of each test case each contains three integers, a, b, and p (1 \leq a, b \leq n; a \neq b; 0 \leq p \leq 1) — the nodes that the elf was assigned to, and the parity of the number of set bits in the elf's favorite number.It is guaranteed that the sum of all n and the sum of all m don't exceed 2 \cdot 10^5 each.It is guaranteed that the given edges form a tree.OutputFor each test case, first print either YES or NO (in any case), whether there's a tree consistent with Santa's memory or not. If the answer is YES, print n-1 lines each containing three integers: x, y, and v (1 \le x, y \le n; 0 \le v < 2^{30}) — the edge and the integer on that edge. The set of edges must be the same as in the input, and if the value of some edge was specified earlier, it can not change. You can print the edges in any order.If there are multiple answers, print any.ExampleInput
4
6 5
1 2 -1
1 3 1
4 2 7
6 3 0
2 5 -1
2 3 1
2 5 0
5 6 1
6 1 1
4 5 1
5 3
1 2 -1
1 3 -1
1 4 1
4 5 -1
2 4 0
3 4 1
2 3 1
3 3
1 2 -1
1 3 -1
1 2 0
1 3 1
2 3 0
2 1
1 2 1
1 2 0
Output
YES
1 2 0
1 3 1
2 4 7
3 6 0
2 5 0
YES
1 2 1
1 3 0
1 4 1
4 5 1
NO
NO
NoteThe first test case is the image in the statement.One possible answer is assigning the value of the edge (1, 2) to 5, and the value of the edge (2, 5) to 3. This is correct because: The first elf goes from node 2 to node 3. This elf's favorite number is 4, so he remembers the value 1 (as 4 has an odd number of 1 bits in its binary representation). The second elf goes from node 2 to node 5. This elf's favorite number is 3, so he remembers the value 0 (as 3 has an even number of 1 bits in its binary representation). The third elf goes from node 5 to node 6. This elf's favorite number is 7, so he remembers the value 1 (as 7 has an odd number of 1 bits in its binary representation). The fourth elf goes from node 6 to node 1. This elf's favorite number is 1, so he remembers the value 1 (as 1 has an odd number of 1 bits in its binary representation). The fifth elf goes from node 4 to node 5. This elf's favorite number is 4, so he remembers the number 1 (as 4 has an odd number of 1 bits in its binary representation). Note that there are other possible answers. | 4
6 5
1 2 -1
1 3 1
4 2 7
6 3 0
2 5 -1
2 3 1
2 5 0
5 6 1
6 1 1
4 5 1
5 3
1 2 -1
1 3 -1
1 4 1
4 5 -1
2 4 0
3 4 1
2 3 1
3 3
1 2 -1
1 3 -1
1 2 0
1 3 1
2 3 0
2 1
1 2 1
1 2 0
| YES 1 2 0 1 3 1 2 4 7 3 6 0 2 5 0 YES 1 2 1 1 3 0 1 4 1 4 5 1 NO NO | 2 seconds | 256 megabytes | ['bitmasks', 'dfs and similar', 'dsu', 'graphs', 'trees', '*2200'] |
C. Menorahtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n candles on a Hanukkah menorah, and some of its candles are initially lit. We can describe which candles are lit with a binary string s, where the i-th candle is lit if and only if s_i=1. Initially, the candle lights are described by a string a. In an operation, you select a candle that is currently lit. By doing so, the candle you selected will remain lit, and every other candle will change (if it was lit, it will become unlit and if it was unlit, it will become lit).You would like to make the candles look the same as string b. Your task is to determine if it is possible, and if it is, find the minimum number of operations required.InputThe first line contains an integer t (1\le t\le 10^4) — the number of test cases. Then t cases follow.The first line of each test case contains a single integer n (1\le n\le 10^5) — the number of candles.The second line contains a string a of length n consisting of symbols 0 and 1 — the initial pattern of lights.The third line contains a string b of length n consisting of symbols 0 and 1 — the desired pattern of lights.It is guaranteed that the sum of n does not exceed 10^5.OutputFor each test case, output the minimum number of operations required to transform a to b, or -1 if it's impossible.ExampleInput
5
5
11010
11010
2
01
11
3
000
101
9
100010111
101101100
9
001011011
011010101
Output
0
1
-1
3
4
NoteIn the first test case, the two strings are already equal, so we don't have to perform any operations.In the second test case, we can perform a single operation selecting the second candle to transform 01 into 11.In the third test case, it's impossible to perform any operations because there are no lit candles to select.In the fourth test case, we can perform the following operations to transform a into b: Select the 7-th candle: 100010{\color{red}1}11\to 011101{\color{red} 1}00. Select the 2-nd candle: 0{\color{red} 1}1101100\to 1{\color{red} 1}0010011. Select the 1-st candle: {\color{red}1}10010011\to {\color{red}1}01101100. In the fifth test case, we can perform the following operations to transform a into b: Select the 6-th candle: 00101{\color{red}1}011\to 11010{\color{red}1}100 Select the 2-nd candle: 1{\color{red}1}0101100\to 0{\color{red}1}1010011 Select the 8-th candle: 0110100{\color{red}1}1\to 1001011{\color{red}1}0 Select the 7-th candle: 100101{\color{red}1}10\to 011010{\color{red}1}01 | 5
5
11010
11010
2
01
11
3
000
101
9
100010111
101101100
9
001011011
011010101
| 0 1 -1 3 4 | 2 seconds | 256 megabytes | ['brute force', 'graphs', 'greedy', 'math', '*1600'] |
B. And It's Non-Zerotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array consisting of all integers from [l, r] inclusive. For example, if l = 2 and r = 5, the array would be [2, 3, 4, 5]. What's the minimum number of elements you can delete to make the bitwise AND of the array non-zero?A bitwise AND is a binary operation that takes two equal-length binary representations and performs the AND operation on each pair of the corresponding bits.InputThe first line contains one integer t (1 \leq t \leq 10^4) — the number of test cases. Then t cases follow.The first line of each test case contains two integers l and r (1 \leq l \leq r \leq 2 \cdot 10^5) — the description of the array.OutputFor each test case, output a single integer — the answer to the problem.ExampleInput
5
1 2
2 8
4 5
1 5
100000 200000
Output
1
3
0
2
31072
NoteIn the first test case, the array is [1, 2]. Currently, the bitwise AND is 0, as 1\ \& \ 2 = 0. However, after deleting 1 (or 2), the array becomes [2] (or [1]), and the bitwise AND becomes 2 (or 1). This can be proven to be the optimal, so the answer is 1.In the second test case, the array is [2, 3, 4, 5, 6, 7, 8]. Currently, the bitwise AND is 0. However, after deleting 4, 5, and 8, the array becomes [2, 3, 6, 7], and the bitwise AND becomes 2. This can be proven to be the optimal, so the answer is 3. Note that there may be other ways to delete 3 elements. | 5
1 2
2 8
4 5
1 5
100000 200000
| 1 3 0 2 31072 | 2 seconds | 256 megabytes | ['bitmasks', 'greedy', 'math', '*1300'] |
A. Closing The Gaptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n block towers in a row, where tower i has a height of a_i. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation: Choose two indices i and j (1 \leq i, j \leq n; i \neq j), and move a block from tower i to tower j. This essentially decreases a_i by 1 and increases a_j by 1. You think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as \max(a)-\min(a). What's the minimum possible ugliness you can achieve, after any number of days?InputThe first line contains one integer t (1 \leq t \leq 1000) — the number of test cases. Then t cases follow.The first line of each test case contains one integer n (2 \leq n \leq 100) — the number of buildings.The second line of each test case contains n space separated integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^7) — the heights of the buildings.OutputFor each test case, output a single integer — the minimum possible ugliness of the buildings.ExampleInput
3
3
10 10 10
4
3 2 1 2
5
1 2 3 1 5
Output
0
0
1
NoteIn the first test case, the ugliness is already 0.In the second test case, you should do one operation, with i = 1 and j = 3. The new heights will now be [2, 2, 2, 2], with an ugliness of 0.In the third test case, you may do three operations: with i = 3 and j = 1. The new array will now be [2, 2, 2, 1, 5], with i = 5 and j = 4. The new array will now be [2, 2, 2, 2, 4], with i = 5 and j = 3. The new array will now be [2, 2, 3, 2, 3]. The resulting ugliness is 1. It can be proven that this is the minimum possible ugliness for this test. | 3
3
10 10 10
4
3 2 1 2
5
1 2 3 1 5
| 0 0 1 | 2 seconds | 256 megabytes | ['greedy', 'math', '*800'] |
E. Divan and a Cottagetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDivan's new cottage is finally complete! However, after a thorough inspection, it turned out that the workers had installed the insulation incorrectly, and now the temperature in the house directly depends on the temperature outside. More precisely, if the temperature in the house is P in the morning, and the street temperature is T, then by the next morning the temperature in the house changes according to the following rule: P_{new} = P + 1, if P < T, P_{new} = P - 1, if P > T, P_{new} = P, if P = T. Here P_{new} is the temperature in the house next morning.Divan is a very busy businessman, so sometimes he is not at home for long periods and does not know what the temperature is there now, so he hired you to find it. You will work for n days. In the beginning of the i-th day, the temperature outside T_i is first given to you. After that, on the i-th day, you will receive k_i queries. Each query asks the following: "if the temperature in the house was x_i at the morning of the first day, what would be the temperature in the house next morning (after day i)?"Please answer all the businessman's queries.InputThe first line of the input contains the number n (1 \leq n \leq 2 \cdot 10^5) — the number of days.The following is a description of n days in the following format.The first line of the description contains an integer T_i (0 \leq T_i \leq 10^9) — the temperature on that day.The second line contains a non-negative integer k_i (0 \le k_i \le 2 \cdot 10^5) — the number of queries that day.The third line contains k integers x'_i (0 \leq x'_{i} \leq 10^9) — the encrypted version of Divan's queries.Let lastans = 0 initially. Divan's actual queries are given by x_i = (x'_i + lastans) \bmod (10^9 + 1), where a \bmod b is the reminder when a is divided by b. After answering the query, set lastans to the answer.It is guaranteed that the total number of queries (the sum of all k_i) does not exceed 2 \cdot 10^5.OutputFor each query, output a single integer — the temperature in the house after day i.ExamplesInput
3
50
3
1 2 3
50
3
4 5 6
0
3
7 8 9
Output
2
5
9
15
22
30
38
47
53
Input
4
728
3
859 1045 182
104
1
689
346
6
634 356 912 214 1 1
755
3
241 765 473
Output
858
1902
2083
2770
3401
3754
4663
4874
4872
4870
5107
5868
6337
Input
2
500000000
3
1000000000 999999999 888888888
250000000
5
777777777 666666666 555555555 444444444 333333333
Output
999999999
999999996
888888882
666666656
333333321
888888874
333333317
666666648
NoteLet's look at the first four queries from the example input.The temperature is 50 on the first day, 50 on the second day, and 0 on the third day.Note that lastans = 0 initially. The initial temperature of the first query of the first day is (1 \, + \, lastans) \bmod (10^9 + 1) = 1. After the first day, the temperature rises by 1, because 1 < 50. So the answer to the query is 2. Then, we set lastans = 2. The initial temperature of the second query of the first day is (2 \, + \, lastans) \bmod (10^9 + 1) = 4. After the first day, the temperature rises by 1, because 4 < 50. So the answer to the query is 5. Then, we set lastans = 5. The initial temperature of the third query of the first day is (3 \, + \, lastans) \bmod (10^9 + 1) = 8. After the first day, the temperature rises by 1. So the answer to the query is 9. Then, we set lastans = 9. The initial temperature of the first query of the second day is (4 \, + \, lastans) \bmod (10^9 + 1) = 13. After the first day, the temperature rises by 1. After the second day, the temperature rises by 1. So the answer to the query is 15. Then, we set lastans = 15. | 3
50
3
1 2 3
50
3
4 5 6
0
3
7 8 9
| 2 5 9 15 22 30 38 47 53 | 2 seconds | 1024 megabytes | ['binary search', 'data structures', '*2600'] |
D2. Divan and Kostomuksha (hard version)time limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference is maximum value of a_i.Once in Kostomuksha Divan found an array a consisting of positive integers. Now he wants to reorder the elements of a to maximize the value of the following function: \sum_{i=1}^n \operatorname{gcd}(a_1, \, a_2, \, \dots, \, a_i), where \operatorname{gcd}(x_1, x_2, \ldots, x_k) denotes the greatest common divisor of integers x_1, x_2, \ldots, x_k, and \operatorname{gcd}(x) = x for any integer x.Reordering elements of an array means changing the order of elements in the array arbitrary, or leaving the initial order.Of course, Divan can solve this problem. However, he found it interesting, so he decided to share it with you.InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the size of the array a.The second line contains n integers a_{1}, \, a_{2}, \, \dots, \, a_{n} (1 \le a_{i} \le 2 \cdot 10^7) — the array a.OutputOutput the maximum value of the function that you can get by reordering elements of the array a.ExamplesInput
6
2 3 1 2 6 2
Output
14Input
10
5 7 10 3 1 10 100 3 42 54
Output
131NoteIn the first example, it's optimal to rearrange the elements of the given array in the following order: [6, \, 2, \, 2, \, 2, \, 3, \, 1]:\operatorname{gcd}(a_1) + \operatorname{gcd}(a_1, \, a_2) + \operatorname{gcd}(a_1, \, a_2, \, a_3) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4, \, a_5) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4, \, a_5, \, a_6) = 6 + 2 + 2 + 2 + 1 + 1 = 14. It can be shown that it is impossible to get a better answer.In the second example, it's optimal to rearrange the elements of a given array in the following order: [100, \, 10, \, 10, \, 5, \, 1, \, 3, \, 3, \, 7, \, 42, \, 54]. | 6
2 3 1 2 6 2
| 14 | 4 seconds | 1024 megabytes | ['dp', 'number theory', '*2300'] |
D1. Divan and Kostomuksha (easy version)time limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference is maximum value of a_i.Once in Kostomuksha Divan found an array a consisting of positive integers. Now he wants to reorder the elements of a to maximize the value of the following function: \sum_{i=1}^n \operatorname{gcd}(a_1, \, a_2, \, \dots, \, a_i), where \operatorname{gcd}(x_1, x_2, \ldots, x_k) denotes the greatest common divisor of integers x_1, x_2, \ldots, x_k, and \operatorname{gcd}(x) = x for any integer x.Reordering elements of an array means changing the order of elements in the array arbitrary, or leaving the initial order.Of course, Divan can solve this problem. However, he found it interesting, so he decided to share it with you.InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the size of the array a.The second line contains n integers a_{1}, \, a_{2}, \, \dots, \, a_{n} (1 \le a_{i} \le 5 \cdot 10^6) — the array a.OutputOutput the maximum value of the function that you can get by reordering elements of the array a.ExamplesInput
6
2 3 1 2 6 2
Output
14Input
10
5 7 10 3 1 10 100 3 42 54
Output
131NoteIn the first example, it's optimal to rearrange the elements of the given array in the following order: [6, \, 2, \, 2, \, 2, \, 3, \, 1]:\operatorname{gcd}(a_1) + \operatorname{gcd}(a_1, \, a_2) + \operatorname{gcd}(a_1, \, a_2, \, a_3) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4, \, a_5) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4, \, a_5, \, a_6) = 6 + 2 + 2 + 2 + 1 + 1 = 14. It can be shown that it is impossible to get a better answer.In the second example, it's optimal to rearrange the elements of a given array in the following order: [100, \, 10, \, 10, \, 5, \, 1, \, 3, \, 3, \, 7, \, 42, \, 54]. | 6
2 3 1 2 6 2
| 14 | 4 seconds | 1024 megabytes | ['dp', 'number theory', '*2100'] |
C. Divan and bitwise operationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Divan analyzed a sequence a_1, a_2, \ldots, a_n consisting of n non-negative integers as follows. He considered each non-empty subsequence of the sequence a, computed the bitwise XOR of its elements and added up all the XORs, obtaining the coziness of the sequence a.A sequence c is a subsequence of a sequence d if c can be obtained from d by deletion of several (possibly, zero or all) elements. For example, [1, \, 2, \, 3, \, 4], [2, \, 4], and [2] are subsequences of [1, \, 2, \, 3, \, 4], but [4, \, 3] and [0] are not.Divan was very proud of his analysis, but now he lost the sequence a, and also the coziness value! However, Divan remembers the value of bitwise OR on m contiguous subsegments of the sequence a. It turns out that each element of the original sequence is contained in at least one of these m segments.Divan asks you to help find the coziness of the sequence a using the information he remembers. If several coziness values are possible, print any.As the result can be very large, print the value modulo 10^9 + 7.InputThe first line contains one integer number t (1 \le t \le 10^3) — the number of test cases.The first line of each test case contains two integer numbers n and m (1 \le n, m \le 2 \cdot 10^5) — the length of the sequence and the number of contiguous segments whose bitwise OR values Divan remembers, respectively.The following m lines describe the segments, one per line.Each segment is described with three integers l, r, and x (1 \le l \le r \le n, 0 \le x \le 2^{30} - 1) — the first and last elements of the segment and the bitwise OR of a_l, a_{l + 1}, \ldots, a_r, respectively.It is guaranteed that each element of the sequence is contained in at least one of the segments. It is guaranteed that there exists a sequence that satisfies all constraints.It is guaranteed that the sum of n and the sum of m over all test cases do not exceed 2 \cdot 10^5. OutputFor each test case print the coziness any suitable sequence a modulo 10^9 + 7.ExampleInput
3
2 1
1 2 2
3 2
1 3 5
2 3 5
5 4
1 2 7
3 3 7
4 4 0
4 5 2
Output
4
20
112
NoteIn first example, one of the sequences that fits the constraints is [0, 2]. Consider all its non-empty subsequences: [0]: the bitwise XOR of this subsequence is 0; [2]: the bitwise XOR of this subsequence is 2; [0, 2]: the bitwise XOR of this subsequence is 2. The sum of all results is 4, so it is the answer.In second example, one of the sequences that fits the constraints is [0, \, 5, \, 5].In third example, one of the sequences that fits the constraints is [5, \, 6, \, 7, \, 0, \, 2]. | 3
2 1
1 2 2
3 2
1 3 5
2 3 5
5 4
1 2 7
3 3 7
4 4 0
4 5 2
| 4 20 112 | 1 second | 256 megabytes | ['bitmasks', 'combinatorics', 'constructive algorithms', 'dp', 'math', '*1500'] |
B. Divan and a New Project time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe company "Divan's Sofas" is planning to build n + 1 different buildings on a coordinate line so that: the coordinate of each building is an integer number; no two buildings stand at the same point. Let x_i be the coordinate of the i-th building. To get from the building i to the building j, Divan spends |x_i - x_j| minutes, where |y| is the absolute value of y.All buildings that Divan is going to build can be numbered from 0 to n. The businessman will live in the building 0, the new headquarters of "Divan's Sofas". In the first ten years after construction Divan will visit the i-th building a_i times, each time spending 2 \cdot |x_0-x_i| minutes for walking.Divan asks you to choose the coordinates for all n + 1 buildings so that over the next ten years the businessman will spend as little time for walking as possible.InputEach test contains several test cases. The first line contains one integer number t (1 \le t \le 10^3) — the number of test cases.The first line of each case contains an integer n (1 \le n \le 2 \cdot 10^5) — the number of buildings that "Divan's Sofas" is going to build, apart from the headquarters.The second line contains the sequence a_1, a_2, \ldots, a_n (0 \le a_i \le 10^6), where a_i is the number of visits to the i-th building.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, on the first line print the number T — the minimum time Divan will spend walking. On the second line print the sequence x_0, x_1, \ldots, x_n of n + 1 integers, where x_i (-10^6 \le x_i \le 10^6) is the selected coordinate of the i-th building. It can be shown that an optimal answer exists with coordinates not exceeding 10^6.If there are multiple answers, print any of them.ExampleInput
4
3
1 2 3
5
3 8 10 6 1
5
1 1 1 1 1
1
0
Output
14
2 4 1 3
78
1 -1 0 2 3 4
18
3 6 1 5 2 4
0
1 2NoteLet's look at the first example.Divan will visit the first building a_1 = 1 times, the second a_2 = 2 times and the third a_3 = 3 times. Then one of the optimal solution will be as follows: the headquarters is located in x_0 = 2; x_1 = 4: Divan will spend 2 \cdot |x_0-x_1| \cdot a_1 = 2 \cdot |2-4| \cdot 1 = 4 minutes walking to the first building; x_2 = 1: Divan will spend 2 \cdot |x_0-x_2| \cdot a_2 = 2 \cdot |2-1| \cdot 2 = 4 minutes walking to the second building; x_3 = 3: Divan will spend 2 \cdot |x_0-x_3| \cdot a_3 = 2 \cdot |2-3| \cdot 3 = 6 minutes walking to the third building. In total, Divan will spend 4 + 4 + 6 = 14 minutes. It can be shown that it is impossible to arrange buildings so that the businessman spends less time.Among others, x = [1, 3, 2, 0], x = [-5, -3, -6, -4] are also correct answers for the first example. | 4
3
1 2 3
5
3 8 10 6 1
5
1 1 1 1 1
1
0
| 14 2 4 1 3 78 1 -1 0 2 3 4 18 3 6 1 5 2 4 0 1 2 | 1 second | 256 megabytes | ['constructive algorithms', 'sortings', '*1000'] |
A. Divan and a Storetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBusinessman Divan loves chocolate! Today he came to a store to buy some chocolate. Like all businessmen, Divan knows the value of money, so he will not buy too expensive chocolate. At the same time, too cheap chocolate tastes bad, so he will not buy it as well.The store he came to has n different chocolate bars, and the price of the i-th chocolate bar is a_i dollars. Divan considers a chocolate bar too expensive if it costs strictly more than r dollars. Similarly, he considers a bar of chocolate to be too cheap if it costs strictly less than l dollars. Divan will not buy too cheap or too expensive bars.Divan is not going to spend all his money on chocolate bars, so he will spend at most k dollars on chocolates.Please determine the maximum number of chocolate bars Divan can buy.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The description of each test case consists of two lines. The first line contains integers n, l, r, k (1 \le n \le 100, 1 \le l \le r \le 10^9, 1 \le k \le 10^9) — the lowest acceptable price of a chocolate, the highest acceptable price of a chocolate and Divan's total budget, respectively.The second line contains a sequence a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) integers — the prices of chocolate bars in the store.OutputFor each test case print a single integer — the maximum number of chocolate bars Divan can buy.ExampleInput
8
3 1 100 100
50 100 50
6 3 5 10
1 2 3 4 5 6
6 3 5 21
1 2 3 4 5 6
10 50 69 100
20 30 40 77 1 1 12 4 70 10000
3 50 80 30
20 60 70
10 2 7 100
2 2 2 2 2 7 7 7 7 7
4 1000000000 1000000000 1000000000
1000000000 1000000000 1000000000 1000000000
1 1 1 1
1
Output
2
2
3
0
0
10
1
1
NoteIn the first example Divan can buy chocolate bars 1 and 3 and spend 100 dollars on them.In the second example Divan can buy chocolate bars 3 and 4 and spend 7 dollars on them.In the third example Divan can buy chocolate bars 3, 4, and 5 for 12 dollars.In the fourth example Divan cannot buy any chocolate bar because each of them is either too cheap or too expensive.In the fifth example Divan cannot buy any chocolate bar because he considers the first bar too cheap, and has no budget for the second or third.In the sixth example Divan can buy all the chocolate bars in the shop. | 8
3 1 100 100
50 100 50
6 3 5 10
1 2 3 4 5 6
6 3 5 21
1 2 3 4 5 6
10 50 69 100
20 30 40 77 1 1 12 4 70 10000
3 50 80 30
20 60 70
10 2 7 100
2 2 2 2 2 7 7 7 7 7
4 1000000000 1000000000 1000000000
1000000000 1000000000 1000000000 1000000000
1 1 1 1
1
| 2 2 3 0 0 10 1 1 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', '*800'] |
F. Tree Coloringtime limit per test4.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is the vertex 1.You have to color all vertices of the tree into n colors (also numbered from 1 to n) so that there is exactly one vertex for each color. Let c_i be the color of vertex i, and p_i be the parent of vertex i in the rooted tree. The coloring is considered beautiful if there is no vertex k (k > 1) such that c_k = c_{p_k} - 1, i. e. no vertex such that its color is less than the color of its parent by exactly 1.Calculate the number of beautiful colorings, and print it modulo 998244353.InputThe first line contains one integer n (2 \le n \le 250000) — the number of vertices in the tree.Then n-1 lines follow, the i-th line contains two integers x_i and y_i (1 \le x_i, y_i \le n; x_i \ne y_i) denoting an edge between the vertex x_i and the vertex y_i. These edges form a tree.OutputPrint one integer — the number of beautiful colorings, taken modulo 998244353.ExamplesInput
5
1 2
3 2
4 2
2 5
Output
42
Input
5
1 2
2 3
3 4
4 5
Output
53
Input
20
20 19
20 4
12 4
5 8
1 2
20 7
3 10
7 18
11 8
9 10
17 10
1 15
11 16
14 11
18 10
10 1
14 2
13 17
20 6
Output
955085064
| 5
1 2
3 2
4 2
2 5
| 42 | 4.5 seconds | 512 megabytes | ['combinatorics', 'divide and conquer', 'fft', '*2600'] |
E. Crazy Robottime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is a grid, consisting of n rows and m columns. Each cell of the grid is either free or blocked. One of the free cells contains a lab. All the cells beyond the borders of the grid are also blocked.A crazy robot has escaped from this lab. It is currently in some free cell of the grid. You can send one of the following commands to the robot: "move right", "move down", "move left" or "move up". Each command means moving to a neighbouring cell in the corresponding direction.However, as the robot is crazy, it will do anything except following the command. Upon receiving a command, it will choose a direction such that it differs from the one in command and the cell in that direction is not blocked. If there is such a direction, then it will move to a neighbouring cell in that direction. Otherwise, it will do nothing.We want to get the robot to the lab to get it fixed. For each free cell, determine if the robot can be forced to reach the lab starting in this cell. That is, after each step of the robot a command can be sent to a robot such that no matter what different directions the robot chooses, it will end up in a lab.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.The first line of each testcase contains two integers n and m (1 \le n, m \le 10^6; n \cdot m \le 10^6) — the number of rows and the number of columns in the grid.The i-th of the next n lines provides a description of the i-th row of the grid. It consists of m elements of one of three types: '.' — the cell is free; '#' — the cell is blocked; 'L' — the cell contains a lab. The grid contains exactly one lab. The sum of n \cdot m over all testcases doesn't exceed 10^6.OutputFor each testcase find the free cells that the robot can be forced to reach the lab from. Given the grid, replace the free cells (marked with a dot) with a plus sign ('+') for the cells that the robot can be forced to reach the lab from. Print the resulting grid.ExampleInput
4
3 3
...
.L.
...
4 5
#....
..##L
...#.
.....
1 1
L
1 9
....L..#.
Output
...
.L.
...
#++++
..##L
...#+
...++
L
++++L++#.
NoteIn the first testcase there is no free cell that the robot can be forced to reach the lab from. Consider a corner cell. Given any direction, it will move to a neighbouring border grid that's not a corner. Now consider a non-corner free cell. No matter what direction you send to the robot, it can choose a different direction such that it ends up in a corner.In the last testcase, you can keep sending the command that is opposite to the direction to the lab and the robot will have no choice other than move towards the lab. | 4
3 3
...
.L.
...
4 5
#....
..##L
...#.
.....
1 1
L
1 9
....L..#.
| ... .L. ... #++++ ..##L ...#+ ...++ L ++++L++#. | 2 seconds | 512 megabytes | ['dfs and similar', 'graphs', '*2000'] |
D. MEX Sequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a sequence of integers x_1, x_2, \dots, x_k MEX-correct if for all i (1 \le i \le k) |x_i - \operatorname{MEX}(x_1, x_2, \dots, x_i)| \le 1 holds. Where \operatorname{MEX}(x_1, \dots, x_k) is the minimum non-negative integer that doesn't belong to the set x_1, \dots, x_k. For example, \operatorname{MEX}(1, 0, 1, 3) = 2 and \operatorname{MEX}(2, 1, 5) = 0.You are given an array a consisting of n non-negative integers. Calculate the number of non-empty MEX-correct subsequences of a given array. The number of subsequences can be very large, so print it modulo 998244353. Note: a subsequence of an array a is a sequence [a_{i_1}, a_{i_2}, \dots, a_{i_m}] meeting the constraints 1 \le i_1 < i_2 < \dots < i_m \le n. If two different ways to choose the sequence of indices [i_1, i_2, \dots, i_m] yield the same subsequence, the resulting subsequence should be counted twice (i. e. two subsequences are different if their sequences of indices [i_1, i_2, \dots, i_m] are not the same).InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 5 \cdot 10^5).The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le n).The sum of n over all test cases doesn't exceed 5 \cdot 10^5.OutputFor each test case, print a single integer — the number of non-empty MEX-correct subsequences of a given array, taken modulo 998244353.ExampleInput
4
3
0 2 1
2
1 0
5
0 0 0 0 0
4
0 1 2 3
Output
4
2
31
7
NoteIn the first example, the valid subsequences are [0], [1], [0,1] and [0,2].In the second example, the valid subsequences are [0] and [1].In the third example, any non-empty subsequence is valid. | 4
3
0 2 1
2
1 0
5
0 0 0 0 0
4
0 1 2 3
| 4 2 31 7 | 2 seconds | 256 megabytes | ['dp', 'math', '*1900'] |
C. Poisoned Daggertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts 100^{500} seconds, during which Monocarp attacks the dragon with a poisoned dagger. The i-th attack is performed at the beginning of the a_i-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals 1 damage during each of the next k seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one).For example, suppose k = 4, and Monocarp stabs the dragon during the seconds 2, 4 and 10. Then the poison effect is applied at the start of the 2-nd second and deals 1 damage during the 2-nd and 3-rd seconds; then, at the beginning of the 4-th second, the poison effect is reapplied, so it deals exactly 1 damage during the seconds 4, 5, 6 and 7; then, during the 10-th second, the poison effect is applied again, and it deals 1 damage during the seconds 10, 11, 12 and 13. In total, the dragon receives 10 damage.Monocarp knows that the dragon has h hit points, and if he deals at least h damage to the dragon during the battle — he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of k (the number of seconds the poison effect lasts) that is enough to deal at least h damage to the dragon.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of the test case contains two integers n and h (1 \le n \le 100; 1 \le h \le 10^{18}) — the number of Monocarp's attacks and the amount of damage that needs to be dealt.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^9; a_i < a_{i + 1}), where a_i is the second when the i-th attack is performed.OutputFor each test case, print a single integer — the minimum value of the parameter k, such that Monocarp will cause at least h damage to the dragon.ExampleInput
4
2 5
1 5
3 10
2 4 10
5 3
1 2 4 5 7
4 1000
3 25 64 1337
Output
3
4
1
470
NoteIn the first example, for k=3, damage is dealt in seconds [1, 2, 3, 5, 6, 7].In the second example, for k=4, damage is dealt in seconds [2, 3, 4, 5, 6, 7, 10, 11, 12, 13].In the third example, for k=1, damage is dealt in seconds [1, 2, 4, 5, 7]. | 4
2 5
1 5
3 10
2 4 10
5 3
1 2 4 5 7
4 1000
3 25 64 1337
| 3 4 1 470 | 2 seconds | 256 megabytes | ['binary search', '*1200'] |
B. Absent Remaindertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a_1, a_2, \dots, a_n consisting of n pairwise distinct positive integers.Find \left\lfloor \frac n 2 \right\rfloor different pairs of integers x and y such that: x \neq y; x and y appear in a; x~mod~y doesn't appear in a. Note that some x or y can belong to multiple pairs.\lfloor x \rfloor denotes the floor function — the largest integer less than or equal to x. x~mod~y denotes the remainder from dividing x by y.If there are multiple solutions, print any of them. It can be shown that at least one solution always exists.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains a single integer n (2 \le n \le 2 \cdot 10^5) — the length of the sequence.The second line of each testcase contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6).All numbers in the sequence are pairwise distinct. The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputThe answer for each testcase should contain \left\lfloor \frac n 2 \right\rfloor different pairs of integers x and y such that x \neq y, x and y appear in a and x~mod~y doesn't appear in a. Print the pairs one after another.You can print the pairs in any order. However, the order of numbers in the pair should be exactly such that the first number is x and the second number is y. All pairs should be pairwise distinct.If there are multiple solutions, print any of them.ExampleInput
4
2
1 4
4
2 8 3 4
5
3 8 5 9 7
6
2 7 5 3 4 8
Output
4 1
8 2
8 4
9 5
7 5
8 7
4 3
5 2NoteIn the first testcase there are only two pairs: (1, 4) and (4, 1). \left\lfloor \frac 2 2 \right\rfloor=1, so we have to find one pair. 1~mod~4=1, and 1 appears in a, so that pair is invalid. Thus, the only possible answer is a pair (4, 1).In the second testcase, we chose pairs 8~mod~2=0 and 8~mod~4=0. 0 doesn't appear in a, so that answer is valid. There are multiple possible answers for that testcase.In the third testcase, the chosen pairs are 9~mod~5=4 and 7~mod~5=2. Neither 4, nor 2, appears in a, so that answer is valid. | 4
2
1 4
4
2 8 3 4
5
3 8 5 9 7
6
2 7 5 3 4 8
| 4 1 8 2 8 4 9 5 7 5 8 7 4 3 5 2 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'sortings', '*1000'] |
A. Long Comparisontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp wrote down two numbers on a whiteboard. Both numbers follow a specific format: a positive integer x with p zeros appended to its end.Now Monocarp asks you to compare these two numbers. Can you help him?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains two integers x_1 and p_1 (1 \le x_1 \le 10^6; 0 \le p_1 \le 10^6) — the description of the first number.The second line of each testcase contains two integers x_2 and p_2 (1 \le x_2 \le 10^6; 0 \le p_2 \le 10^6) — the description of the second number.OutputFor each testcase print the result of the comparison of the given two numbers. If the first number is smaller than the second one, print '<'. If the first number is greater than the second one, print '>'. If they are equal, print '='.ExampleInput
5
2 1
19 0
10 2
100 1
1999 0
2 3
1 0
1 0
99 0
1 2
Output
>
=
<
=
<
NoteThe comparisons in the example are: 20 > 19, 1000 = 1000, 1999 < 2000, 1 = 1, 99 < 100. | 5
2 1
19 0
10 2
100 1
1999 0
2 3
1 0
1 0
99 0
1 2
| > = < = < | 2 seconds | 256 megabytes | ['implementation', 'math', '*900'] |
G. Max Sum Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array c = [c_1, c_2, \dots, c_m]. An array a = [a_1, a_2, \dots, a_n] is constructed in such a way that it consists of integers 1, 2, \dots, m, and for each i \in [1,m], there are exactly c_i occurrences of integer i in a. So, the number of elements in a is exactly \sum\limits_{i=1}^{m} c_i.Let's define for such array a the value f(a) as f(a) = \sum_{\substack{1 \le i < j \le n\\ a_i = a_j}}{j - i}.In other words, f(a) is the total sum of distances between all pairs of equal elements.Your task is to calculate the maximum possible value of f(a) and the number of arrays yielding the maximum possible value of f(a). Two arrays are considered different, if elements at some position differ.InputThe first line contains a single integer m (1 \le m \le 5 \cdot 10^5) — the size of the array c.The second line contains m integers c_1, c_2, \dots, c_m (1 \le c_i \le 10^6) — the array c.OutputPrint two integers — the maximum possible value of f(a) and the number of arrays a with such value. Since both answers may be too large, print them modulo 10^9 + 7.ExamplesInput
6
1 1 1 1 1 1
Output
0 720
Input
1
1000000
Output
499833345 1
Input
7
123 451 234 512 345 123 451
Output
339854850 882811119
NoteIn the first example, all possible arrays a are permutations of [1, 2, 3, 4, 5, 6]. Since each array a will have f(a) = 0, so maximum value is f(a) = 0 and there are 6! = 720 such arrays.In the second example, the only possible array consists of 10^6 ones and its f(a) = \sum\limits_{1 \le i < j \le 10^6}{j - i} = 166\,666\,666\,666\,500\,000 and 166\,666\,666\,666\,500\,000 \bmod{10^9 + 7} = 499\,833\,345. | 6
1 1 1 1 1 1
| 0 720 | 2 seconds | 256 megabytes | ['combinatorics', 'constructive algorithms', 'greedy', 'sortings', '*2500'] |
F. Armor and Weaponstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp plays a computer game. There are n different sets of armor and m different weapons in this game. If a character equips the i-th set of armor and wields the j-th weapon, their power is usually equal to i + j; but some combinations of armor and weapons synergize well. Formally, there is a list of q ordered pairs, and if the pair (i, j) belongs to this list, the power of the character equipped with the i-th set of armor and wielding the j-th weapon is not i + j, but i + j + 1.Initially, Monocarp's character has got only the 1-st armor set and the 1-st weapon. Monocarp can obtain a new weapon or a new set of armor in one hour. If he wants to obtain the k-th armor set or the k-th weapon, he must possess a combination of an armor set and a weapon that gets his power to k or greater. Of course, after Monocarp obtains a weapon or an armor set, he can use it to obtain new armor sets or weapons, but he can go with any of the older armor sets and/or weapons as well.Monocarp wants to obtain the n-th armor set and the m-th weapon. What is the minimum number of hours he has to spend on it? InputThe first line contains two integers n and m (2 \le n, m \le 2 \cdot 10^5) — the number of armor sets and the number of weapons, respectively.The second line contains one integer q (0 \le q \le \min(2 \cdot 10^5, nm)) — the number of combinations that synergize well.Then q lines follow, the i-th line contains two integers a_i and b_i (1 \le a_i \le n; 1 \le b_i \le m) meaning that the a_i-th armor set synergizes well with the b_i-th weapon. All pairs (a_i, b_i) are distinct.OutputPrint one integer — the minimum number of hours Monocarp has to spend to obtain both the n-th armor set and the m-th weapon.ExamplesInput
3 4
0
Output
3
Input
3 4
2
1 1
1 3
Output
2
NoteIn the first example, Monocarp can obtain the strongest armor set and the strongest weapon as follows: Obtain the 2-nd weapon using the 1-st armor set and the 1-st weapon; Obtain the 3-rd armor set using the 1-st armor set and the 2-nd weapon; Obtain the 4-th weapon using the 3-rd armor set and the 2-nd weapon. In the second example, Monocarp can obtain the strongest armor set and the strongest weapon as follows: Obtain the 3-rd armor set using the 1-st armor set and the 1-st weapon (they synergize well, so Monocarp's power is not 2 but 3); Obtain the 4-th weapon using the 3-rd armor set and the 1-st weapon. | 3 4
0
| 3 | 2 seconds | 512 megabytes | ['brute force', 'dp', 'greedy', 'shortest paths', '*2800'] |
E. Messagestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp is a tutor of a group of n students. He communicates with them using a conference in a popular messenger.Today was a busy day for Monocarp — he was asked to forward a lot of posts and announcements to his group, that's why he had to write a very large number of messages in the conference. Monocarp knows the students in the group he is tutoring quite well, so he understands which message should each student read: Monocarp wants the student i to read the message m_i.Of course, no one's going to read all the messages in the conference. That's why Monocarp decided to pin some of them. Monocarp can pin any number of messages, and if he wants anyone to read some message, he should pin it — otherwise it will definitely be skipped by everyone.Unfortunately, even if a message is pinned, some students may skip it anyway. For each student i, Monocarp knows that they will read at most k_i messages. Suppose Monocarp pins t messages; if t \le k_i, then the i-th student will read all the pinned messages; but if t > k_i, the i-th student will choose exactly k_i random pinned messages (all possible subsets of pinned messages of size k_i are equiprobable) and read only the chosen messages.Monocarp wants to maximize the expected number of students that read their respective messages (i.e. the number of such indices i that student i reads the message m_i). Help him to choose how many (and which) messages should he pin!InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of students in the conference.Then n lines follow. The i-th line contains two integers m_i and k_i (1 \le m_i \le 2 \cdot 10^5; 1 \le k_i \le 20) — the index of the message which Monocarp wants the i-th student to read and the maximum number of messages the i-th student will read, respectively.OutputIn the first line, print one integer t (1 \le t \le 2 \cdot 10^5) — the number of messages Monocarp should pin. In the second line, print t distinct integers c_1, c_2, ..., c_t (1 \le c_i \le 2 \cdot 10^5) — the indices of the messages Monocarp should pin. The messages can be listed in any order.If there are multiple answers, print any of them.ExamplesInput
3
10 1
10 2
5 2
Output
2
5 10
Input
3
10 1
5 2
10 1
Output
1
10
Input
4
1 1
2 2
3 3
4 4
Output
3
2 3 4
Input
3
13 2
42 2
37 2
Output
3
42 13 37
NoteLet's consider the examples from the statement. In the first example, Monocarp pins the messages 5 and 10. if the first student reads the message 5, the second student reads the messages 5 and 10, and the third student reads the messages 5 and 10, the number of students which have read their respective messages will be 2; if the first student reads the message 10, the second student reads the messages 5 and 10, and the third student reads the messages 5 and 10, the number of students which have read their respective messages will be 3. So, the expected number of students which will read their respective messages is \frac{5}{2}. In the second example, Monocarp pins the message 10. if the first student reads the message 10, the second student reads the message 10, and the third student reads the message 10, the number of students which have read their respective messages will be 2. So, the expected number of students which will read their respective messages is 2. If Monocarp had pinned both messages 5 and 10, the expected number of students which read their respective messages would have been 2 as well. In the third example, the expected number of students which will read their respective messages is \frac{8}{3}. In the fourth example, the expected number of students which will read their respective messages is 2. | 3
10 1
10 2
5 2
| 2 5 10 | 3 seconds | 512 megabytes | ['brute force', 'dp', 'greedy', 'probabilities', 'sortings', '*2000'] |
D. X-Magic Pairtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a pair of integers (a, b) and an integer x.You can change the pair in two different ways: set (assign) a := |a - b|; set (assign) b := |a - b|, where |a - b| is the absolute difference between a and b.The pair (a, b) is called x-magic if x is obtainable either as a or as b using only the given operations (i.e. the pair (a, b) is x-magic if a = x or b = x after some number of operations applied). You can apply the operations any number of times (even zero).Your task is to find out if the pair (a, b) is x-magic or not.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. The next t lines describe test cases.The only line of the test case contains three integers a, b and x (1 \le a, b, x \le 10^{18}).OutputFor the i-th test case, print YES if the corresponding pair (a, b) is x-magic and NO otherwise.ExampleInput
8
6 9 3
15 38 7
18 8 8
30 30 30
40 50 90
24 28 20
365 216 52
537037812705867558 338887693834423551 3199921013340
Output
YES
YES
YES
YES
NO
YES
YES
YES
| 8
6 9 3
15 38 7
18 8 8
30 30 30
40 50 90
24 28 20
365 216 52
537037812705867558 338887693834423551 3199921013340
| YES YES YES YES NO YES YES YES | 2 seconds | 512 megabytes | ['math', 'number theory', '*1600'] |
C. Chat Bantime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are a usual chat user on the most famous streaming platform. Of course, there are some moments when you just want to chill and spam something.More precisely, you want to spam the emote triangle of size k. It consists of 2k-1 messages. The first message consists of one emote, the second one — of two emotes, ..., the k-th one — of k emotes, the k+1-th one — of k-1 emotes, ..., and the last one — of one emote.For example, the emote triangle for k=3 consists of 5 messages: Of course, most of the channels have auto moderation. Auto moderator of the current chat will ban you right after you spam at least x emotes in succession (you can assume you are the only user in the chat). Now you are interested — how many messages will you write before getting banned? Or maybe you will not get banned at all (i.e. will write all 2k-1 messages and complete your emote triangle successfully)? Note that if you get banned as a result of writing a message, this message is also counted.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. The next t lines describe test cases.The only line of the test case contains integers k and x (1 \le k \le 10^9; 1 \le x \le 10^{18}).OutputFor each test case, print the number of messages you will write before getting banned for the corresponding values k and x.ExampleInput
7
4 6
4 7
1 2
3 7
2 5
100 1
1000000000 923456789987654321
Output
3
4
1
4
3
1
1608737403
NoteLet's analyze the test cases of the example. In the first test case, you write three messages containing 1, 2 and 3 emotes respectively, and since 1 + 2 + 3 \ge 6, you get banned after that. In the second test case, you write four messages containing 1, 2, 3 and 4 emotes respectively, and since 1 + 2 + 3 + 4 \ge 7, you get banned after that. In the third test case, you write one message containing exactly 1 emote. It doesn't get you banned, since 1 < 2, but you have already finished posting your emote triangle. So you wrote one message successfully. In the fourth test case, you write four messages containing 1, 2, 3 and 2 emotes respectively, and since 1 + 2 + 3 + 2 \ge 7, you get banned after that. In the fifth test case, you write three messages containing 1, 2 and 1 emote respectively. It doesn't get you banned, since 1 + 2 + 1 < 5, but you have already finished posting your emote triangle. So you wrote three messages successfully. In the sixth test case, since x = 1, you get banned as soon as you send your first message. The seventh test case is too large to analyze, so we'll skip it. | 7
4 6
4 7
1 2
3 7
2 5
100 1
1000000000 923456789987654321
| 3 4 1 4 3 1 1608737403 | 2 seconds | 512 megabytes | ['binary search', 'math', '*1300'] |
B. Special Permutationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA permutation of length n is an array p=[p_1,p_2,\dots, p_n] which contains every integer from 1 to n (inclusive) exactly once. For example, p=[4, 2, 6, 5, 3, 1] is a permutation of length 6.You are given three integers n, a and b, where n is an even number. Print any permutation of length n that the minimum among all its elements of the left half equals a and the maximum among all its elements of the right half equals b. Print -1 if no such permutation exists.InputThe first line of the input contains one integer t (1 \le t \le 1000), the number of test cases in the test. The following t lines contain test case descriptions.Each test case description contains three integers n, a, b (2 \le n \le 100; 1 \le a,b \le n; a \ne b), where n is an even number (i.e. n \bmod 2 = 0).OutputFor each test case, print a single line containing any suitable permutation. Print -1 no such permutation exists. If there are multiple answers, print any of them.ExampleInput
7
6 2 5
6 1 3
6 4 3
4 2 4
10 5 3
2 1 2
2 2 1
Output
4 2 6 5 3 1
-1
6 4 5 1 3 2
3 2 4 1
-1
1 2
2 1
| 7
6 2 5
6 1 3
6 4 3
4 2 4
10 5 3
2 1 2
2 2 1
| 4 2 6 5 3 1 -1 6 4 5 1 3 2 3 2 4 1 -1 1 2 2 1 | 2 seconds | 512 megabytes | ['constructive algorithms', 'greedy', '*900'] |
A. Distancetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's denote the Manhattan distance between two points p_1 (with coordinates (x_1, y_1)) and p_2 (with coordinates (x_2, y_2)) as d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|. For example, the distance between two points with coordinates (1, 3) and (4, 2) is |1 - 4| + |3 - 2| = 4.You are given two points, A and B. The point A has coordinates (0, 0), the point B has coordinates (x, y).Your goal is to find a point C such that: both coordinates of C are non-negative integers; d(A, C) = \dfrac{d(A, B)}{2} (without any rounding); d(B, C) = \dfrac{d(A, B)}{2} (without any rounding). Find any point C that meets these constraints, or report that no such point exists.InputThe first line contains one integer t (1 \le t \le 3000) — the number of test cases.Each test case consists of one line containing two integers x and y (0 \le x, y \le 50) — the coordinates of the point B.OutputFor each test case, print the answer on a separate line as follows: if it is impossible to find a point C meeting the constraints, print "-1 -1" (without quotes); otherwise, print two non-negative integers not exceeding 10^6 — the coordinates of point C meeting the constraints. If there are multiple answers, print any of them. It can be shown that if any such point exists, it's possible to find a point with coordinates not exceeding 10^6 that meets the constraints. ExampleInput
10
49 3
2 50
13 0
0 41
42 0
0 36
13 37
42 16
42 13
0 0
Output
23 3
1 25
-1 -1
-1 -1
21 0
0 18
13 12
25 4
-1 -1
0 0
NoteExplanations for some of the test cases from the example: In the first test case, the point B has coordinates (49, 3). If the point C has coordinates (23, 3), then the distance from A to B is |49 - 0| + |3 - 0| = 52, the distance from A to C is |23 - 0| + |3 - 0| = 26, and the distance from B to C is |23 - 49| + |3 - 3| = 26. In the second test case, the point B has coordinates (2, 50). If the point C has coordinates (1, 25), then the distance from A to B is |2 - 0| + |50 - 0| = 52, the distance from A to C is |1 - 0| + |25 - 0| = 26, and the distance from B to C is |1 - 2| + |25 - 50| = 26. In the third and the fourth test cases, it can be shown that no point with integer coordinates meets the constraints. In the fifth test case, the point B has coordinates (42, 0). If the point C has coordinates (21, 0), then the distance from A to B is |42 - 0| + |0 - 0| = 42, the distance from A to C is |21 - 0| + |0 - 0| = 21, and the distance from B to C is |21 - 42| + |0 - 0| = 21. | 10
49 3
2 50
13 0
0 41
42 0
0 36
13 37
42 16
42 13
0 0
| 23 3 1 25 -1 -1 -1 -1 21 0 0 18 13 12 25 4 -1 -1 0 0 | 3 seconds | 512 megabytes | ['brute force', 'constructive algorithms', '*800'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.