contest_id
int32 1
2.13k
| index
stringclasses 62
values | problem_id
stringlengths 2
6
| title
stringlengths 0
67
| rating
int32 0
3.5k
| tags
stringlengths 0
139
| statement
stringlengths 0
6.96k
| input_spec
stringlengths 0
2.32k
| output_spec
stringlengths 0
1.52k
| note
stringlengths 0
5.06k
| sample_tests
stringlengths 0
1.02k
| difficulty_category
stringclasses 6
values | tag_count
int8 0
11
| statement_length
int32 0
6.96k
| input_spec_length
int16 0
2.32k
| output_spec_length
int16 0
1.52k
| contest_year
int16 0
21
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
490 |
C
|
490C
|
C. Hacking Cypher
| 1,700 |
brute force; math; number theory; strings
|
Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which may consist of even a million digits!Polycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible by a as a separate number, and the second (right) part is divisible by b as a separate number. Both parts should be positive integers that have no leading zeros. Polycarpus knows values a and b.Help Polycarpus and find any suitable method to cut the public key.
|
The first line of the input contains the public key of the messenger — an integer without leading zeroes, its length is in range from 1 to 106 digits. The second line contains a pair of space-separated positive integers a, b (1 ≤ a, b ≤ 108).
|
In the first line print ""YES"" (without the quotes), if the method satisfying conditions above exists. In this case, next print two lines — the left and right parts after the cut. These two parts, being concatenated, must be exactly identical to the public key. The left part must be divisible by a, and the right part must be divisible by b. The two parts must be positive integers having no leading zeros. If there are several answers, print any of them.If there is no answer, print in a single line ""NO"" (without the quotes).
|
Input: 11640102497 1024 | Output: YES116401024
|
Medium
| 4 | 749 | 242 | 531 | 4 |
|
865 |
G
|
865G
|
G. Flowers and Chocolate
| 3,300 |
combinatorics; math; matrices
|
It's Piegirl's birthday soon, and Pieguy has decided to buy her a bouquet of flowers and a basket of chocolates.The flower shop has F different types of flowers available. The i-th type of flower always has exactly pi petals. Pieguy has decided to buy a bouquet consisting of exactly N flowers. He may buy the same type of flower multiple times. The N flowers are then arranged into a bouquet. The position of the flowers within a bouquet matters. You can think of a bouquet as an ordered list of flower types.The chocolate shop sells chocolates in boxes. There are B different types of boxes available. The i-th type of box contains ci pieces of chocolate. Pieguy can buy any number of boxes, and can buy the same type of box multiple times. He will then place these boxes into a basket. The position of the boxes within the basket matters. You can think of the basket as an ordered list of box types.Pieguy knows that Piegirl likes to pluck a petal from a flower before eating each piece of chocolate. He would like to ensure that she eats the last piece of chocolate from the last box just after plucking the last petal from the last flower. That is, the total number of petals on all the flowers in the bouquet should equal the total number of pieces of chocolate in all the boxes in the basket.How many different bouquet+basket combinations can Pieguy buy? The answer may be very large, so compute it modulo 1000000007 = 109 + 7.
|
The first line of input will contain integers F, B, and N (1 ≤ F ≤ 10, 1 ≤ B ≤ 100, 1 ≤ N ≤ 1018), the number of types of flowers, the number of types of boxes, and the number of flowers that must go into the bouquet, respectively.The second line of input will contain F integers p1, p2, ..., pF (1 ≤ pi ≤ 109), the numbers of petals on each of the flower types.The third line of input will contain B integers c1, c2, ..., cB (1 ≤ ci ≤ 250), the number of pieces of chocolate in each of the box types.
|
Print the number of bouquet+basket combinations Pieguy can buy, modulo 1000000007 = 109 + 7.
|
In the first example, there is 1 way to make a bouquet with 9 petals (3 + 3 + 3), and 1 way to make a basket with 9 pieces of chocolate (3 + 3 + 3), for 1 possible combination. There are 3 ways to make a bouquet with 13 petals (3 + 5 + 5, 5 + 3 + 5, 5 + 5 + 3), and 5 ways to make a basket with 13 pieces of chocolate (3 + 10, 10 + 3, 3 + 3 + 7, 3 + 7 + 3, 7 + 3 + 3), for 15 more combinations. Finally there is 1 way to make a bouquet with 15 petals (5 + 5 + 5) and 1 way to make a basket with 15 pieces of chocolate (3 + 3 + 3 + 3 + 3), for 1 more combination.Note that it is possible for multiple types of flowers to have the same number of petals. Such types are still considered different. Similarly different types of boxes may contain the same number of pieces of chocolate, but are still considered different.
|
Input: 2 3 33 510 3 7 | Output: 17
|
Master
| 3 | 1,434 | 501 | 92 | 8 |
1,626 |
B
|
1626B
|
B. Minor Reduction
| 1,100 |
greedy; strings
|
You 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?
|
The 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\).
|
For 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.
|
The 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.
|
Input: 21005790 | Output: 10012 9
|
Easy
| 2 | 850 | 319 | 173 | 16 |
997 |
A
|
997A
|
A. Convert to Ones
| 1,500 |
brute force; greedy; implementation; math
|
You've got a string \(a_1, a_2, \dots, a_n\), consisting of zeros and ones.Let's call a sequence of consecutive elements \(a_i, a_{i + 1}, \ldots, a_j\) (\(1\leq i\leq j\leq n\)) a substring of string \(a\). You can apply the following operations any number of times: Choose some substring of string \(a\) (for example, you can choose entire string) and reverse it, paying \(x\) coins for it (for example, «0101101» \(\to\) «0111001»); Choose some substring of string \(a\) (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying \(y\) coins for it (for example, «0101101» \(\to\) «0110001»). You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.What is the minimum number of coins you need to spend to get a string consisting only of ones?
|
The first line of input contains integers \(n\), \(x\) and \(y\) (\(1 \leq n \leq 300\,000, 0 \leq x, y \leq 10^9\)) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).The second line contains the string \(a\) of length \(n\), consisting of zeros and ones.
|
Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print \(0\), if you do not need to perform any operations.
|
In the first sample, at first you need to reverse substring \([1 \dots 2]\), and then you need to invert substring \([2 \dots 5]\). Then the string was changed as follows:«01000» \(\to\) «10000» \(\to\) «11111».The total cost of operations is \(1 + 10 = 11\).In the second sample, at first you need to invert substring \([1 \dots 1]\), and then you need to invert substring \([3 \dots 5]\). Then the string was changed as follows:«01000» \(\to\) «11000» \(\to\) «11111».The overall cost is \(1 + 1 = 2\).In the third example, string already consists only of ones, so the answer is \(0\).
|
Input: 5 1 1001000 | Output: 11
|
Medium
| 4 | 916 | 348 | 179 | 9 |
1,781 |
C
|
1781C
|
C. Equal Frequencies
| 1,600 |
brute force; constructive algorithms; greedy; implementation; sortings; strings
|
Let's call a string balanced if all characters that are present in it appear the same number of times. For example, ""coder"", ""appall"", and ""ttttttt"" are balanced, while ""wowwow"" and ""codeforces"" are not.You are given a string \(s\) of length \(n\) consisting of lowercase English letters. Find a balanced string \(t\) of the same length \(n\) consisting of lowercase English letters that is different from the string \(s\) in as few positions as possible. In other words, the number of indices \(i\) such that \(s_i \ne t_i\) should be as small as possible.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows.Each test case consists of two lines. The first line contains a single integer \(n\) (\(1 \le n \le 10^5\)) — the length of the string \(s\).The second line contains the string \(s\) of length \(n\) consisting of lowercase English letters.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
|
For each test case, print the smallest number of positions where string \(s\) and a balanced string \(t\) can differ, followed by such a string \(t\).If there are multiple solutions, print any. It can be shown that at least one balanced string always exists.
|
In the first test case, the given string ""hello"" is not balanced: letters 'h', 'e', and 'o' appear in it once, while letter 'l' appears twice. On the other hand, string ""helno"" is balanced: five distinct letters are present in it, and each of them appears exactly once. Strings ""hello"" and ""helno"" differ in just one position: the fourth character. Other solutions are possible too.In the second test case, string ""codefofced"" is balanced since only letters 'c', 'o', 'd', 'e', and 'f' are present in it, and each of them appears exactly twice.In the third test case, string ""eeeee"" is balanced since only letter 'e' is present in it.In the fourth test case, the given string ""appall"" is already balanced.
|
Input: 45hello10codeforces5eevee6appall | Output: 1 helno 2 codefofced 1 eeeee 0 appall
|
Medium
| 6 | 567 | 484 | 258 | 17 |
1,605 |
C
|
1605C
|
C. Dominant Character
| 1,400 |
brute force; greedy; implementation; strings
|
Ashish has a string \(s\) of length \(n\) containing only characters 'a', 'b' and 'c'.He wants to find the length of the smallest substring, which satisfies the following conditions: Length of the substring is at least \(2\) 'a' occurs strictly more times in this substring than 'b' 'a' occurs strictly more times in this substring than 'c' Ashish is busy planning his next Codeforces round. Help him solve the problem.A string \(a\) is a substring of a string \(b\) if \(a\) can be obtained from \(b\) by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
|
The first line contains a single integer \(t\) \((1 \le t \le 10^{5})\) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer \(n\) \((2 \le n \le 10^{6})\) — the length of the string \(s\).The second line of each test case contains a string \(s\) consisting only of characters 'a', 'b' and 'c'.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^{6}\).
|
For each test case, output the length of the smallest substring which satisfies the given conditions or print \(-1\) if there is no such substring.
|
Consider the first test case. In the substring ""aa"", 'a' occurs twice, while 'b' and 'c' occur zero times. Since 'a' occurs strictly more times than 'b' and 'c', the substring ""aa"" satisfies the condition and the answer is \(2\). The substring ""a"" also satisfies this condition, however its length is not at least \(2\).In the second test case, it can be shown that in none of the substrings of ""cbabb"" does 'a' occur strictly more times than 'b' and 'c' each.In the third test case, ""cacabccc"", the length of the smallest substring that satisfies the conditions is \(3\).
|
Input: 3 2 aa 5 cbabb 8 cacabccc | Output: 2 -1 3
|
Easy
| 4 | 640 | 452 | 147 | 16 |
463 |
E
|
463E
|
E. Caisa and Tree
| 2,100 |
brute force; dfs and similar; math; number theory; trees
|
Caisa is now at home and his son has a simple task for him.Given a rooted tree with n vertices, numbered from 1 to n (vertex 1 is the root). Each vertex of the tree has a value. You should answer q queries. Each query is one of the following: Format of the query is ""1 v"". Let's write out the sequence of vertices along the path from the root to vertex v: u1, u2, ..., uk (u1 = 1; uk = v). You need to output such a vertex ui that gcd(value of ui, value of v) > 1 and i < k. If there are several possible vertices ui pick the one with maximum value of i. If there is no such vertex output -1. Format of the query is ""2 v w"". You must change the value of vertex v to w. You are given all the queries, help Caisa to solve the problem.
|
The first line contains two space-separated integers n, q (1 ≤ n, q ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2·106), where ai represent the value of node i.Each of the next n - 1 lines contains two integers xi and yi (1 ≤ xi, yi ≤ n; xi ≠ yi), denoting the edge of the tree between vertices xi and yi.Each of the next q lines contains a query in the format that is given above. For each query the following inequalities hold: 1 ≤ v ≤ n and 1 ≤ w ≤ 2·106. Note that: there are no more than 50 queries that changes the value of a vertex.
|
For each query of the first type output the result of the query.
|
gcd(x, y) is greatest common divisor of two integers x and y.
|
Input: 4 610 8 4 31 22 33 41 11 21 31 42 1 91 4 | Output: -112-11
|
Hard
| 5 | 736 | 564 | 64 | 4 |
107 |
C
|
107C
|
C. Arrangement
| 2,400 |
bitmasks; dp
|
In the year 2500 the annual graduation ceremony in the German University in Cairo (GUC) has run smoothly for almost 500 years so far.The most important part of the ceremony is related to the arrangement of the professors in the ceremonial hall.Traditionally GUC has n professors. Each professor has his seniority level. All seniorities are different. Let's enumerate the professors from 1 to n, with 1 being the most senior professor and n being the most junior professor.The ceremonial hall has n seats, one seat for each professor. Some places in this hall are meant for more senior professors than the others. More specifically, m pairs of seats are in ""senior-junior"" relation, and the tradition requires that for all m pairs of seats (ai, bi) the professor seated in ""senior"" position ai should be more senior than the professor seated in ""junior"" position bi.GUC is very strict about its traditions, which have been carefully observed starting from year 2001. The tradition requires that: The seating of the professors changes every year. Year 2001 ceremony was using lexicographically first arrangement of professors in the ceremonial hall. Each consecutive year lexicographically next arrangement of the professors is used. The arrangement of the professors is the list of n integers, where the first integer is the seniority of the professor seated in position number one, the second integer is the seniority of the professor seated in position number two, etc.Given n, the number of professors, y, the current year and m pairs of restrictions, output the arrangement of the professors for this year.
|
The first line contains three integers n, y and m (1 ≤ n ≤ 16, 2001 ≤ y ≤ 1018, 0 ≤ m ≤ 100) — the number of professors, the year for which the arrangement should be computed, and the number of pairs of seats for which the seniority relation should be kept, respectively.The next m lines contain one pair of integers each, ""ai bi"", indicating that professor on the ai-th seat is more senior than professor on the bi-th seat (1 ≤ ai, bi ≤ n, ai ≠ bi). Some pair may be listed more than once.Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin stream (you may also use the %I64d specificator).
|
Print the order in which the professors should be seated in the requested year.If by this year the GUC would have ran out of arrangements, or the given ""senior-junior"" relation are contradictory, print ""The times have changed"" (without quotes).
|
In the first example the lexicographically first order of seating is 1 2 3.In the third example the GUC will run out of arrangements after the year 3630800.In the fourth example there are no valid arrangements for the seating.The lexicographical comparison of arrangements is performed by the < operator in modern programming languages. The arrangement a is lexicographically less that the arrangement b, if there exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.
|
Input: 3 2001 21 22 3 | Output: 1 2 3
|
Expert
| 2 | 1,615 | 654 | 248 | 1 |
1,842 |
A
|
1842A
|
A. Tenzing and Tsondu
| 800 |
games; math
|
Tsondu always runs first! ! !Tsondu and Tenzing are playing a card game. Tsondu has \(n\) monsters with ability values \(a_1, a_2, \ldots, a_n\) while Tenzing has \(m\) monsters with ability values \(b_1, b_2, \ldots, b_m\).Tsondu and Tenzing take turns making moves, with Tsondu going first. In each move, the current player chooses two monsters: one on their side and one on the other side. Then, these monsters will fight each other. Suppose the ability values for the chosen monsters are \(x\) and \(y\) respectively, then the ability values of the monsters will become \(x-y\) and \(y-x\) respectively. If the ability value of any monster is smaller than or equal to \(0\), the monster dies.The game ends when at least one player has no monsters left alive. The winner is the player with at least one monster left alive. If both players have no monsters left alive, the game ends in a draw.Find the result of the game when both players play optimally.
|
Each test contains multiple test cases. The first line of input contains a single integer \(t\) (\(1 \le t \le 2 \cdot 10^3\)) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers \(n\) and \(m\) (\(1 \leq n,m \leq 50\)) — the number of monsters Tsondu and Tenzing have respectively.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 ability values of Tsondu's monsters. The third line of each test case contains \(m\) integers \(b_1,b_2,\ldots,b_m\) \((1 \leq b_i \leq 10^9\)) — the ability values of Tenzing's monsters.
|
For each test case, output ""Tsondu"" if Tsondu wins, ""Tenzing"" if Tenzing wins, and ""Draw"" if the game ends in a draw. (Output without quotes.)Note that the output is case-sensitive. For example, if the answer is ""Tsondu"", the outputs ""tsondu"", ""TSONDU"", and ""tSonDu"" will all be recognized as incorrect outputs.
|
Consider the first test case. It can be shown that Tsondu has a winning strategy. The following is a possible way that Tsondu can win (note that the players may not be playing optimally in this example): In the first move, Tsondu chooses a monster with ability value \(9\) on his side to fight against a monster with ability value \(1\) on Tenzing's side, the ability value of both monsters become \(8\) and \(-8\) respectively. The monster with ability value \(-8\) on Tenzing's side dies. In the second move, Tenzing chooses a monster with ability value \(2\) on his side to fight against a monster with ability value \(8\) on Tsondu's side, the ability value of both monsters become \(-6\) and \(6\) respectively. The monster with ability value \(-6\) on Tenzing's side dies. In the third move, Tsondu chooses a monster with ability value \(6\) on his side to fight against a monster with ability value \(3\) onTenzing's side, the ability value of both monsters become \(3\) and \(-3\) respectively. The monster with ability value \(-3\) on Tenzing's side dies. Now, Tenzing has no monsters left alive. Since Tsondu still has monsters left alive, Tsondu wins.
|
Input: 61 391 2 32 31 21 1 13 21 2 31 13 31 1 12 2 210 101 2 3 3 2 2 1 1 2 23 3 3 3 2 1 1 1 1 110 101 2 3 4 5 6 7 8 9 106 7 8 9 10 11 1 1 1 1 | Output: Tsondu Draw Tsondu Tenzing Draw Draw
|
Beginner
| 2 | 956 | 652 | 325 | 18 |
1,453 |
F
|
1453F
|
F. Even Harder
| 2,700 |
dp
|
Gildong is now developing a puzzle game. The puzzle consists of \(n\) platforms numbered from \(1\) to \(n\). The player plays the game as a character that can stand on each platform and the goal of the game is to move the character from the \(1\)-st platform to the \(n\)-th platform.The \(i\)-th platform is labeled with an integer \(a_i\) (\(0 \le a_i \le n-i\)). When the character is standing on the \(i\)-th platform, the player can move the character to any of the \(j\)-th platforms where \(i+1 \le j \le i+a_i\). If the character is on the \(i\)-th platform where \(a_i=0\) and \(i \ne n\), the player loses the game.Since Gildong thinks the current game is not hard enough, he wants to make it even harder. He wants to change some (possibly zero) labels to \(0\) so that there remains exactly one way to win. He wants to modify the game as little as possible, so he's asking you to find the minimum number of platforms that should have their labels changed. Two ways are different if and only if there exists a platform the character gets to in one way but not in the other way.
|
Each test contains one or more test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 500\)).Each test case contains two lines. The first line of each test case consists of an integer \(n\) (\(2 \le n \le 3000\)) — the number of platforms of the game.The second line of each test case contains \(n\) integers. The \(i\)-th integer is \(a_i\) (\(0 \le a_i \le n-i\)) — the integer of the \(i\)-th platform.It is guaranteed that: For each test case, there is at least one way to win initially. The sum of \(n\) in all test cases doesn't exceed \(3000\).
|
For each test case, print one integer — the minimum number of different labels that should be changed to \(0\) so that there remains exactly one way to win.
|
In the first case, the player can only move to the next platform until they get to the \(4\)-th platform. Since there is already only one way to win, the answer is zero.In the second case, Gildong can change \(a_2\), \(a_3\), and \(a_4\) to \(0\) so that the game becomes \(4\) \(0\) \(0\) \(0\) \(0\). Now the only way the player can win is to move directly from the \(1\)-st platform to the \(5\)-th platform.In the third case, Gildong can change \(a_2\) and \(a_8\) to \(0\), then the only way to win is to move in the following way: \(1\) – \(3\) – \(7\) – \(9\).
|
Input: 3 4 1 1 1 0 5 4 3 2 1 0 9 4 1 4 2 1 0 2 1 0 | Output: 0 3 2
|
Master
| 1 | 1,088 | 578 | 156 | 14 |
1,416 |
B
|
1416B
|
B. Make Them Equal
| 2,000 |
constructive algorithms; greedy; math
|
You are given an array \(a\) consisting of \(n\) positive integers, numbered from \(1\) to \(n\). You can perform the following operation no more than \(3n\) times: choose three integers \(i\), \(j\) and \(x\) (\(1 \le i, j \le n\); \(0 \le x \le 10^9\)); assign \(a_i := a_i - x \cdot i\), \(a_j := a_j + x \cdot i\). After each operation, all elements of the array should be non-negative.Can you find a sequence of no more than \(3n\) operations after which all elements of the array are equal?
|
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. Then \(t\) test cases follow.The first line of each test case contains one integer \(n\) (\(1 \le n \le 10^4\)) — the number of elements in the array. The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^5\)) — the elements of the array.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^4\).
|
For each test case print the answer to it as follows: if there is no suitable sequence of operations, print \(-1\); otherwise, print one integer \(k\) (\(0 \le k \le 3n\)) — the number of operations in the sequence. Then print \(k\) lines, the \(m\)-th of which should contain three integers \(i\), \(j\) and \(x\) (\(1 \le i, j \le n\); \(0 \le x \le 10^9\)) for the \(m\)-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize \(k\).
|
Input: 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 | Output: 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1
|
Hard
| 3 | 496 | 446 | 506 | 14 |
|
260 |
C
|
260C
|
C. Balls and Boxes
| 1,700 |
constructive algorithms; greedy; implementation
|
Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right.Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers i + 1, i + 2, i + 3 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If i = n, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on. For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if i = 3, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4, 1, 2, 3, 4. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one.At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x — the number of the box, where he put the last of the taken out balls.He asks you to help to find the initial arrangement of the balls in the boxes.
|
The first line of the input contains two integers n and x (2 ≤ n ≤ 105, 1 ≤ x ≤ n), that represent the number of the boxes and the index of the box that got the last ball from Vasya, correspondingly. The second line contains n space-separated integers a1, a2, ..., an, where integer ai (0 ≤ ai ≤ 109, ax ≠ 0) represents the number of balls in the box with index i after Vasya completes all the actions. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
Print n integers, where the i-th one represents the number of balls in the box number i before Vasya starts acting. Separate the numbers in the output by spaces. If there are multiple correct solutions, you are allowed to print any of them.
|
Input: 4 44 3 1 6 | Output: 3 2 5 4
|
Medium
| 3 | 1,575 | 550 | 240 | 2 |
|
1,211 |
A
|
1211A
|
A. Three Problems
| 1,000 |
*special; implementation
|
Polycarp is choosing three problems for creating a programming test. Totally he has \(n\) problems in his list. The complexity of the \(i\)-th problem equals \(r_i\). All problems are numerated from \(1\) to \(n\).Help Polycarp to choose such three problems \(a\), \(b\) and \(c\), so that the complexity of the first problem strictly less than the complexity of second problem and the complexity of the second problem is strictly less than the complexity of the third problem. So, for chosen problems \(a\), \(b\) and \(c\) it should be true that \(r_a < r_b < r_c\).If Polycarp can choose three problems in different ways, you can print any of them.
|
The first line of the input contains one integer \(n\) (\(3 \le n \le 3000\)) — the number of problems in Polycarp's list.The second line of the input contains \(n\) integers \(r_1, r_2, \dots, r_n\) (\(1 \le r_i \le 10^9\)), where \(r_i\) is the complexity of the \(i\)-th problem.
|
If Polycarp has no ways to choose three problems, you should print three numbers -1. Ih there is a way to choose them, you should print three different integers \(a, b, c\) (\(1 \le a, b, c \le n\)), where \(a\) is the number of the first chosen problem, \(b\) is the number of the second chosen problem and \(c\) is the number of the third chosen problem.
|
Input: 6 3 1 4 1 5 9 | Output: 4 1 3
|
Beginner
| 2 | 651 | 282 | 356 | 12 |
|
925 |
C
|
925C
|
C. Big Secret
| 2,200 |
constructive algorithms; math
|
Vitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer 54 42, but an increasing integer sequence \(a_1, \ldots, a_n\). In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence \(b_1, \ldots, b_n\) using the following rules: \(b_1 = a_1\); \(b_i = a_i \oplus a_{i - 1}\) for all \(i\) from 2 to \(n\), where \(x \oplus y\) is the bitwise XOR of \(x\) and \(y\). It is easy to see that the original sequence can be obtained using the rule \(a_i = b_1 \oplus \ldots \oplus b_i\).However, some time later Vitya discovered that the integers \(b_i\) in the cypher got shuffled, and it can happen that when decrypted using the rule mentioned above, it can produce a sequence that is not increasing. In order to save his reputation in the scientific community, Vasya decided to find some permutation of integers \(b_i\) so that the sequence \(a_i = b_1 \oplus \ldots \oplus b_i\) is strictly increasing. Help him find such a permutation or determine that it is impossible.
|
The first line contains a single integer \(n\) (\(1 \leq n \leq 10^5\)).The second line contains \(n\) integers \(b_1, \ldots, b_n\) (\(1 \leq b_i < 2^{60}\)).
|
If there are no valid permutations, print a single line containing ""No"".Otherwise in the first line print the word ""Yes"", and in the second line print integers \(b'_1, \ldots, b'_n\) — a valid permutation of integers \(b_i\). The unordered multisets \(\{b_1, \ldots, b_n\}\) and \(\{b'_1, \ldots, b'_n\}\) should be equal, i. e. for each integer \(x\) the number of occurrences of \(x\) in the first multiset should be equal to the number of occurrences of \(x\) in the second multiset. Apart from this, the sequence \(a_i = b'_1 \oplus \ldots \oplus b'_i\) should be strictly increasing.If there are multiple answers, print any of them.
|
In the first example no permutation is valid.In the second example the given answer lead to the sequence \(a_1 = 4\), \(a_2 = 8\), \(a_3 = 15\), \(a_4 = 16\), \(a_5 = 23\), \(a_6 = 42\).
|
Input: 31 2 3 | Output: No
|
Hard
| 2 | 1,077 | 159 | 641 | 9 |
797 |
B
|
797B
|
B. Odd sum
| 1,400 |
dp; greedy; implementation
|
You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You should write a program which finds sum of the best subsequence.
|
The first line contains integer number n (1 ≤ n ≤ 105).The second line contains n integer numbers a1, a2, ..., an ( - 104 ≤ ai ≤ 104). The sequence contains at least one subsequence with odd sum.
|
Print sum of resulting subseqeuence.
|
In the first example sum of the second and the fourth elements is 3.
|
Input: 4-2 2 -3 1 | Output: 3
|
Easy
| 3 | 454 | 195 | 36 | 7 |
1,610 |
B
|
1610B
|
B. Kalindrome Array
| 1,100 |
greedy; two pointers
|
An array \([b_1, b_2, \ldots, b_m]\) is a palindrome, if \(b_i = b_{m+1-i}\) for each \(i\) from \(1\) to \(m\). Empty array is also a palindrome.An array is called kalindrome, if the following condition holds: It's possible to select some integer \(x\) and delete some of the elements of the array equal to \(x\), so that the remaining array (after gluing together the remaining parts) is a palindrome. Note that you don't have to delete all elements equal to \(x\), and you don't have to delete at least one element equal to \(x\).For example : \([1, 2, 1]\) is kalindrome because you can simply not delete a single element. \([3, 1, 2, 3, 1]\) is kalindrome because you can choose \(x = 3\) and delete both elements equal to \(3\), obtaining array \([1, 2, 1]\), which is a palindrome. \([1, 2, 3]\) is not kalindrome. You are given an array \([a_1, a_2, \ldots, a_n]\). Determine if \(a\) is kalindrome or not.
|
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) — the length of the array.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le n\)) — elements of the array.It's guaranteed that the sum of \(n\) over all test cases won't exceed \(2 \cdot 10^5\).
|
For each test case, print YES if \(a\) is kalindrome and NO otherwise. You can print each letter in any case.
|
In the first test case, array \([1]\) is already a palindrome, so it's a kalindrome as well.In the second test case, we can choose \(x = 2\), delete the second element, and obtain array \([1]\), which is a palindrome.In the third test case, it's impossible to obtain a palindrome.In the fourth test case, you can choose \(x = 4\) and delete the fifth element, obtaining \([1, 4, 4, 1]\). You also can choose \(x = 1\), delete the first and the fourth elements, and obtain \([4, 4, 4]\).
|
Input: 4 1 1 2 1 2 3 1 2 3 5 1 4 4 1 4 | Output: YES YES NO YES
|
Easy
| 2 | 914 | 480 | 109 | 16 |
833 |
E
|
833E
|
E. Caramel Clouds
| 3,400 |
data structures; dp; sortings
|
It is well-known that the best decoration for a flower bed in Sweetland are vanilla muffins. Seedlings of this plant need sun to grow up. Slastyona has m seedlings, and the j-th seedling needs at least kj minutes of sunlight to grow up.Most of the time it's sunny in Sweetland, but sometimes some caramel clouds come, the i-th of which will appear at time moment (minute) li and disappear at time moment ri. Of course, the clouds make shadows, and the seedlings can't grow when there is at least one cloud veiling the sun.Slastyona wants to grow up her muffins as fast as possible. She has exactly C candies, which is the main currency in Sweetland. One can dispel any cloud by paying ci candies. However, in order to comply with Sweetland's Department of Meteorology regulations, one can't dispel more than two clouds.Slastyona hasn't decided yet which of the m seedlings will be planted at the princess' garden, so she needs your help. For each seedling determine the earliest moment it can grow up if Slastyona won't break the law and won't spend more candies than she has. Note that each of the seedlings is considered independently.The seedlings start to grow at time moment 0.
|
The first line contains two integers n and C (0 ≤ n ≤ 3·105, 0 ≤ C ≤ 109) – the number of caramel clouds and the number of candies Slastyona has.The next n lines contain three integers each: li, ri, ci (0 ≤ li < ri ≤ 109, 0 ≤ ci ≤ 109), describing one caramel cloud.The next line contains single integer m (1 ≤ m ≤ 3·105) – the number of seedlings. Each of the seedlings is described with one integer kj (1 ≤ kj ≤ 109) – the required number of sunny minutes.
|
For each seedling print one integer – the minimum minute Slastyona can grow it up.
|
Consider the first example. For each k it is optimal to dispel clouds 1 and 3. Then the remaining cloud will give shadow on time segment [1..6]. So, intervals [0..1] and [6..inf) are sunny. In the second example for k = 1 it is not necessary to dispel anything, and for k = 5 the best strategy is to dispel clouds 2 and 3. This adds an additional sunny segment [4..8], which together with [0..1] allows to grow up the muffin at the eight minute. If the third example the two seedlings are completely different. For the first one it is necessary to dispel cloud 1 and obtain a sunny segment [0..10]. However, the same strategy gives answer 180 for the second seedling. Instead, we can dispel cloud 2, to make segments [0..3] and [7..inf) sunny, and this allows up to shorten the time to 104.
|
Input: 3 51 7 11 6 21 7 13725 | Output: 12710
|
Master
| 3 | 1,182 | 458 | 82 | 8 |
1,430 |
E
|
1430E
|
E. String Reversal
| 1,900 |
data structures; greedy; strings
|
You are given a string \(s\). You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string ""abddea"", you should get the string ""aeddba"". To accomplish your goal, you can swap the neighboring elements of the string. Your task is to calculate the minimum number of swaps you have to perform to reverse the given string.
|
The first line contains one integer \(n\) (\(2 \le n \le 200\,000\)) — the length of \(s\).The second line contains \(s\) — a string consisting of \(n\) lowercase Latin letters.
|
Print one integer — the minimum number of swaps of neighboring elements you have to perform to reverse the string.
|
In the first example, you have to swap the third and the fourth elements, so the string becomes ""aazaa"". Then you have to swap the second and the third elements, so the string becomes ""azaaa"". So, it is possible to reverse the string in two swaps.Since the string in the second example is a palindrome, you don't have to do anything to reverse it.
|
Input: 5 aaaza | Output: 2
|
Hard
| 3 | 522 | 177 | 114 | 14 |
1,101 |
B
|
1101B
|
B. Accordion
| 1,300 |
greedy; implementation
|
An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code \(091\)), a colon (ASCII code \(058\)), some (possibly zero) vertical line characters (ASCII code \(124\)), another colon, and a closing bracket (ASCII code \(093\)). The length of the accordion is the number of characters in it.For example, [::], [:||:] and [:|||:] are accordions having length \(4\), \(6\) and \(7\). (:|:), {:||:}, [:], ]:||:[ are not accordions. You are given a string \(s\). You want to transform it into an accordion by removing some (possibly zero) characters from it. Note that you may not insert new characters or reorder existing ones. Is it possible to obtain an accordion by removing characters from \(s\), and if so, what is the maximum possible length of the result?
|
The only line contains one string \(s\) (\(1 \le |s| \le 500000\)). It consists of lowercase Latin letters and characters [, ], : and |.
|
If it is not possible to obtain an accordion by removing some characters from \(s\), print \(-1\). Otherwise print maximum possible length of the resulting accordion.
|
Input: |[a:b:|] | Output: 4
|
Easy
| 2 | 900 | 136 | 166 | 11 |
|
24 |
A
|
24A
|
A. Ring road
| 1,400 |
graphs
|
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
|
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
|
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
|
Input: 31 3 11 2 13 2 1 | Output: 1
|
Easy
| 1 | 811 | 303 | 158 | 0 |
|
48 |
H
|
48H
|
H. Black and White
| 2,800 |
constructive algorithms
|
According to the legends the king of Berland Berl I was noted for his love of beauty and order. One day he ordered to tile the palace hall's floor where balls and receptions used to take place with black and white tiles according to a regular geometrical pattern invented by him. However, as is after the case, due to low financing there were only a black and b white tiles delivered to the palace. The other c tiles were black and white (see the picture). The initial plan failed! Having learned of that, the king gave a new command: tile the floor with the available tiles so that no black side of a tile touched a white one. The tiles are squares of one size 1 × 1, every black and white tile can be rotated in one of the four ways. The court programmer was given the task to work out the plan of tiling and he coped with the task and didn't suffer the consequences of disobedience. And can you cope with it?
|
The first line contains given integers n and m (1 ≤ n, m ≤ 100) which represent the sizes of the rectangle that needs to be tiled. The next line contains non-negative numbers a, b and c, a + b + c = nm, c ≥ m.
|
Print 2n lines containing 2m characters each — the tiling scheme. Every tile is represented by a square 2 × 2 in the following manner (the order corresponds to the order of the picture above): If multiple solutions exist, output any.
|
Input: 2 20 0 4 | Output: \../#\/#\##/.\/.
|
Master
| 1 | 911 | 209 | 233 | 0 |
|
391 |
C3
|
391C3
|
C3. The Tournament
| 0 |
This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points.Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined, there were n contestants in the tournament, numbered from 1 to n. Each of them had already obtained some amount of tournament points, namely the i-th fighter had pi points.Manao is going to engage in a single fight against each contestant. Each of Manao's fights ends in either a win or a loss. A win grants Manao one point, and a loss grants Manao's opponent one point. For each i, Manao estimated the amount of effort ei he needs to invest to win against the i-th contestant. Losing a fight costs no effort.After Manao finishes all of his fights, the ranklist will be determined, with 1 being the best rank and n + 1 being the worst. The contestants will be ranked in descending order of their tournament points. The contestants with the same number of points as Manao will be ranked better than him if they won the match against him and worse otherwise. The exact mechanism of breaking ties for other fighters is not relevant here.Manao's objective is to have rank k or better. Determine the minimum total amount of effort he needs to invest in order to fulfill this goal, if it is possible.
|
The first line contains a pair of integers n and k (1 ≤ k ≤ n + 1). The i-th of the following n lines contains two integers separated by a single space — pi and ei (0 ≤ pi, ei ≤ 200000).The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem C1 (4 points), the constraint 1 ≤ n ≤ 15 will hold. In subproblem C2 (4 points), the constraint 1 ≤ n ≤ 100 will hold. In subproblem C3 (8 points), the constraint 1 ≤ n ≤ 200000 will hold.
|
Print a single number in a single line — the minimum amount of effort Manao needs to use to rank in the top k. If no amount of effort can earn Manao such a rank, output number -1.
|
Consider the first test case. At the time when Manao joins the tournament, there are three fighters. The first of them has 1 tournament point and the victory against him requires 1 unit of effort. The second contestant also has 1 tournament point, but Manao needs 4 units of effort to defeat him. The third contestant has 2 points and victory against him costs Manao 2 units of effort. Manao's goal is top be in top 2. The optimal decision is to win against fighters 1 and 3, after which Manao, fighter 2, and fighter 3 will all have 2 points. Manao will rank better than fighter 3 and worse than fighter 2, thus finishing in second place.Consider the second test case. Even if Manao wins against both opponents, he will still rank third.
|
Input: 3 21 11 42 2 | Output: 3
|
Beginner
| 0 | 1,413 | 602 | 179 | 3 |
|
1,903 |
B
|
1903B
|
B. StORage room
| 1,200 |
bitmasks; brute force; constructive algorithms; greedy
|
In Cyprus, the weather is pretty hot. Thus, Theofanis saw this as an opportunity to create an ice cream company. He keeps the ice cream safe from other ice cream producers by locking it inside big storage rooms. However, he forgot the password. Luckily, the lock has a special feature for forgetful people! It gives you a table \(M\) with \(n\) rows and \(n\) columns of non-negative integers, and to open the lock, you need to find an array \(a\) of \(n\) elements such that: \(0 \le a_i < 2^{30}\), and \(M_{i,j} = a_i | a_j\) for all \(i \neq j\), where \(|\) denotes the bitwise OR operation. The lock has a bug, and sometimes it gives tables without any solutions. In that case, the ice cream will remain frozen for the rest of eternity.Can you find an array to open the lock?
|
The first line contains a single integer \(t\) (\(1 \le t \le 10^{3}\)) — the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^{3}\)) — the size of the hidden array.The next \(n\) lines describe the rows of \(M\), line \(i\) contains the table values \(M_{i,1}, M_{i,2}, \ldots, M_{i,n}\) (\(0 \le M_{i,j} < 2^{30}\)).It is guaranteed that \(M_{i,i} = 0\) and \(M_{i,j} = M_{j,i}\) for all \(1 \le i,j \le n\).It is also guaranteed that the sum of \(n\) over all test cases does not exceed \(10^{3}\).
|
For each test case, if there is a solution print YES and an array that satisfies the property, otherwise print NO.If there are multiple solutions, print any of them.You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
|
Input: 41040 3 3 53 0 3 73 3 0 75 7 7 050 7 7 5 57 0 3 2 67 3 0 3 75 2 3 0 45 6 7 4 030 0 10 0 01 0 0 | Output: YES 7 YES 1 3 2 5 YES 5 2 3 0 4 NO
|
Easy
| 4 | 781 | 556 | 326 | 19 |
|
804 |
A
|
804A
|
A. Find Amir
| 1,000 |
constructive algorithms; greedy; math
|
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
|
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of schools.
|
Print single integer: the minimum cost of tickets needed to visit all schools.
|
In the first example we can buy a ticket between the schools that costs .
|
Input: 2 | Output: 0
|
Beginner
| 3 | 479 | 81 | 78 | 8 |
137 |
D
|
137D
|
D. Palindromes
| 1,900 |
dp; strings
|
Friday is Polycarpus' favourite day of the week. Not because it is followed by the weekend, but because the lessons on Friday are 2 IT lessons, 2 math lessons and 2 literature lessons. Of course, Polycarpus has prepared to all of them, unlike his buddy Innocentius. Innocentius spent all evening playing his favourite game Fur2 and didn't have enough time to do the literature task. As Innocentius didn't want to get an F, he decided to do the task and read the book called ""Storm and Calm"" during the IT and Math lessons (he never used to have problems with these subjects). When the IT teacher Mr. Watkins saw this, he decided to give Innocentius another task so that the boy concentrated more on the lesson and less — on the staff that has nothing to do with IT. Mr. Watkins said that a palindrome is a string that can be read the same way in either direction, from the left to the right and from the right to the left. A concatenation of strings a, b is a string ab that results from consecutive adding of string b to string a. Of course, Innocentius knew it all but the task was much harder than he could have imagined. Mr. Watkins asked change in the ""Storm and Calm"" the minimum number of characters so that the text of the book would also be a concatenation of no more than k palindromes. Innocentius can't complete the task and therefore asks you to help him.
|
The first input line contains a non-empty string s which is the text of ""Storm and Calm"" (without spaces). The length of the string s does not exceed 500 characters. String s consists of uppercase and lowercase Latin letters. The second line contains a single number k (1 ≤ k ≤ |s|, where |s| represents the length of the string s).
|
Print on the first line the minimum number of changes that Innocentius will have to make. Print on the second line the string consisting of no more than k palindromes. Each palindrome should be non-empty and consist of uppercase and lowercase Latin letters. Use the character ""+"" (ASCII-code 43) to separate consecutive palindromes. If there exist several solutions, print any of them.The letters' case does matter, that is an uppercase letter is not considered equivalent to the corresponding lowercase letter.
|
Input: abacaba1 | Output: 0abacaba
|
Hard
| 2 | 1,372 | 334 | 513 | 1 |
|
1,956 |
C
|
1956C
|
C. Nene's Magical Matrix
| 1,600 |
constructive algorithms; greedy; math
|
The magical girl Nene has an \(n\times n\) matrix \(a\) filled with zeroes. The \(j\)-th element of the \(i\)-th row of matrix \(a\) is denoted as \(a_{i, j}\).She can perform operations of the following two types with this matrix: Type \(1\) operation: choose an integer \(i\) between \(1\) and \(n\) and a permutation \(p_1, p_2, \ldots, p_n\) of integers from \(1\) to \(n\). Assign \(a_{i, j}:=p_j\) for all \(1 \le j \le n\) simultaneously. Type \(2\) operation: choose an integer \(i\) between \(1\) and \(n\) and a permutation \(p_1, p_2, \ldots, p_n\) of integers from \(1\) to \(n\). Assign \(a_{j, i}:=p_j\) for all \(1 \le j \le n\) simultaneously. Nene wants to maximize the sum of all the numbers in the matrix \(\sum\limits_{i=1}^{n}\sum\limits_{j=1}^{n}a_{i,j}\). She asks you to find the way to perform the operations so that this sum is maximized. As she doesn't want to make too many operations, you should provide a solution with no more than \(2n\) operations.A permutation of length \(n\) is an array consisting of \(n\) distinct integers from \(1\) to \(n\) in arbitrary order. For example, \([2,3,1,5,4]\) is a permutation, but \([1,2,2]\) is not a permutation (\(2\) appears twice in the array), and \([1,3,4]\) is also not a permutation (\(n=3\) but there is \(4\) in the array).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 500\)). The description of test cases follows.The only line of each test case contains a single integer \(n\) (\(1 \le n \le 500\)) — the size of the matrix \(a\).It is guaranteed that the sum of \(n^2\) over all test cases does not exceed \(5 \cdot 10^5\).
|
For each test case, in the first line output two integers \(s\) and \(m\) (\(0\leq m\leq 2n\)) — the maximum sum of the numbers in the matrix and the number of operations in your solution.In the \(k\)-th of the next \(m\) lines output the description of the \(k\)-th operation: an integer \(c\) (\(c \in \{1, 2\}\)) — the type of the \(k\)-th operation; an integer \(i\) (\(1 \le i \le n\)) — the row or the column the \(k\)-th operation is applied to; a permutation \(p_1, p_2, \ldots, p_n\) of integers from \(1\) to \(n\) — the permutation used in the \(k\)-th operation. Note that you don't need to minimize the number of operations used, you only should use no more than \(2n\) operations. It can be shown that the maximum possible sum can always be obtained in no more than \(2n\) operations.
|
In the first test case, the maximum sum \(s=1\) can be obtained in \(1\) operation by setting \(a_{1, 1}:=1\).In the second test case, the maximum sum \(s=7\) can be obtained in \(3\) operations as follows: It can be shown that it is impossible to make the sum of the numbers in the matrix larger than \(7\).
|
Input: 212 | Output: 1 1 1 1 1 7 3 1 1 1 2 1 2 1 2 2 1 1 2
|
Medium
| 3 | 1,304 | 367 | 798 | 19 |
2,121 |
G
|
2121G
|
G. Gangsta
| 1,900 |
data structures; divide and conquer; math; sortings
|
You are given a binary string \(s_1s_2 \ldots s_n\) of length \(n\). A string \(s\) is called binary if it consists only of zeros and ones.For a string \(p\), we define the function \(f(p)\) as the maximum number of occurrences of any character in the string \(p\). For example, \(f(00110) = 3\), \(f(01) = 1\).You need to find the sum \(f(s_ls_{l+1} \ldots s_r)\) for all pairs \(1 \leq l \leq r \leq n\).
|
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. Then follows their descriptions.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) — the length of the binary string.The second line of each test case contains a string of length \(n\), consisting of \(0\)s and \(1\)s — the binary string \(s\).It is guaranteed that the sum of \(n\) across all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, output the sum \(f(s_ls_{l+1} \ldots s_r)\) for all pairs \(1 \leq l \leq r \leq n\).
|
In the first test case, the string \(s\) has one substring, and the value \(f(0) = 1\).In the second test case, all substrings of the string \(s\) are \(0\), \(01\), \(1\). And the answer is \(1 + 1 + 1 = 3\), respectively.In the third test case, all substrings of the string \(s\) are \(0\), \(01\), \(011\), \(0110\), \(1\), \(11\), \(110\), \(1\), \(10\), \(0\). And the answer is \(1 + 1 + 2 + 2 + 1 + 2 + 2 + 1 + 1 + 1 = 14\), respectively.
|
Input: 6102014011061100018100111001101011011100 | Output: 1 3 14 40 78 190
|
Hard
| 4 | 406 | 524 | 105 | 21 |
1,342 |
F
|
1342F
|
F. Make It Ascending
| 3,000 |
bitmasks; brute force; dp
|
You are given an array \(a\) consisting of \(n\) elements. You may apply several operations (possibly zero) to it.During each operation, you choose two indices \(i\) and \(j\) (\(1 \le i, j \le n\); \(i \ne j\)), increase \(a_j\) by \(a_i\), and remove the \(i\)-th element from the array (so the indices of all elements to the right to it decrease by \(1\), and \(n\) also decreases by \(1\)).Your goal is to make the array \(a\) strictly ascending. That is, the condition \(a_1 < a_2 < \dots < a_n\) should hold (where \(n\) is the resulting size of the array).Calculate the minimum number of actions required to make the array strictly ascending.
|
The first line contains one integer \(T\) (\(1 \le T \le 10000\)) — the number of test cases.Each test case consists of two lines. The first line contains one integer \(n\) (\(1 \le n \le 15\)) — the number of elements in the initial array \(a\).The second line contains \(n\) integers \(a_1\), \(a_2\), ..., \(a_n\) (\(1 \le a_i \le 10^6\)).It is guaranteed that: the number of test cases having \(n \ge 5\) is not greater than \(5000\); the number of test cases having \(n \ge 8\) is not greater than \(500\); the number of test cases having \(n \ge 10\) is not greater than \(100\); the number of test cases having \(n \ge 11\) is not greater than \(50\); the number of test cases having \(n \ge 12\) is not greater than \(25\); the number of test cases having \(n \ge 13\) is not greater than \(10\); the number of test cases having \(n \ge 14\) is not greater than \(3\); the number of test cases having \(n \ge 15\) is not greater than \(1\).
|
For each test case, print the answer as follows:In the first line, print \(k\) — the minimum number of operations you have to perform. Then print \(k\) lines, each containing two indices \(i\) and \(j\) for the corresponding operation. Note that the numeration of elements in the array changes after removing elements from it. If there are multiple optimal sequences of operations, print any one of them.
|
In the first test case, the sequence of operations changes \(a\) as follows:\([2, 1, 3, 5, 1, 2, 4, 5] \rightarrow [2, 1, 3, 5, 1, 4, 7] \rightarrow [1, 3, 5, 1, 6, 7] \rightarrow [2, 3, 5, 6, 7]\).
|
Input: 4 8 2 1 3 5 1 2 4 5 15 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 2 3 3 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Output: 3 6 8 1 6 4 1 7 1 15 1 13 1 11 1 9 1 7 1 5 1 3 1 2 1 0
|
Master
| 3 | 649 | 948 | 404 | 13 |
1,195 |
B
|
1195B
|
B. Sport Mafia
| 1,000 |
binary search; brute force; math
|
Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia. For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs \(n\) actions. The first action performed is to put a single candy into the box. For each of the remaining moves she can choose from two options: the first option, in case the box contains at least one candy, is to take exactly one candy out and eat it. This way the number of candies in the box decreased by \(1\); the second option is to put candies in the box. In this case, Alya will put \(1\) more candy, than she put in the previous time. Thus, if the box is empty, then it can only use the second option.For example, one possible sequence of Alya's actions look as follows: put one candy into the box; put two candies into the box; eat one candy from the box; eat one candy from the box; put three candies into the box; eat one candy from the box; put four candies into the box; eat one candy from the box; put five candies into the box; This way she will perform \(9\) actions, the number of candies at the end will be \(11\), while Alya will eat \(4\) candies in total.You know the total number of actions \(n\) and the number of candies at the end \(k\). You need to find the total number of sweets Alya ate. That is the number of moves of the first option. It's guaranteed, that for the given \(n\) and \(k\) the answer always exists.Please note, that during an action of the first option, Alya takes out and eats exactly one candy.
|
The first line contains two integers \(n\) and \(k\) (\(1 \le n \le 10^9\); \(0 \le k \le 10^9\)) — the total number of moves and the number of candies in the box at the end. It's guaranteed, that for the given \(n\) and \(k\) the answer exists.
|
Print a single integer — the number of candies, which Alya ate. Please note, that in this problem there aren't multiple possible answers — the answer is unique for any input data.
|
In the first example, Alya has made one move only. According to the statement, the first move is always putting one candy in the box. Hence Alya ate \(0\) candies.In the second example the possible sequence of Alya's actions looks as follows: put \(1\) candy, put \(2\) candies, eat a candy, eat a candy, put \(3\) candies, eat a candy, put \(4\) candies, eat a candy, put \(5\) candies. This way, she will make exactly \(n=9\) actions and in the end the box will contain \(1+2-1-1+3-1+4-1+5=11\) candies. The answer is \(4\), since she ate \(4\) candies in total.
|
Input: 1 1 | Output: 0
|
Beginner
| 3 | 1,560 | 245 | 179 | 11 |
1,917 |
D
|
1917D
|
D. Yet Another Inversions Problem
| 2,300 |
combinatorics; data structures; dp; implementation; math; number theory
|
You are given a permutation \(p_0, p_1, \ldots, p_{n-1}\) of odd integers from \(1\) to \(2n-1\) and a permutation \(q_0, q_1, \ldots, q_{k-1}\) of integers from \(0\) to \(k-1\).An array \(a_0, a_1, \ldots, a_{nk-1}\) of length \(nk\) is defined as follows: \(a_{i \cdot k+j}=p_i \cdot 2^{q_j}\) for all \(0 \le i < n\) and all \(0 \le j < k\) For example, if \(p = [3, 5, 1]\) and \(q = [0, 1]\), then \(a = [3, 6, 5, 10, 1, 2]\).Note that all arrays in the statement are zero-indexed. Note that each element of the array \(a\) is uniquely determined.Find the number of inversions in the array \(a\). Since this number can be very large, you should find only its remainder modulo \(998\,244\,353\).An inversion in array \(a\) is a pair \((i, j)\) (\(0 \le i < j < nk\)) such that \(a_i > a_j\).
|
The 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, k \le 2 \cdot 10^5\)) — the lengths of arrays \(p\) and \(q\).The second line of each test case contains \(n\) distinct integers \(p_0, p_1, \ldots, p_{n-1}\) (\(1 \le p_i \le 2n-1\), \(p_i\) is odd) — the array \(p\).The third line of each test case contains \(k\) distinct integers \(q_0, q_1, \ldots, q_{k-1}\) (\(0 \le q_i < k\)) — the array \(q\).It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(2 \cdot 10^5\) and the sum of \(k\) over all test cases doesn't exceed \(2 \cdot 10^5\).
|
For each test case, output one integer: the number of inversions in array \(a\) modulo \(998\,244\,353\).
|
In the first test case, array \(a\) is equal to \([3, 6, 5, 10, 1, 2]\). There are \(9\) inversions in it: \((0, 4)\), \((0, 5)\), \((1, 2)\), \((1, 4)\), \((1, 5)\), \((2, 4)\), \((2, 5)\), \((3, 4)\), \((3, 5)\). Note that these are pairs \((i, j)\) such that \(i < j\) and \(a_i > a_j\).In the second test case, array \(a\) is equal to \([8, 4, 1, 2, 24, 12, 3, 6, 40, 20, 5, 10]\). There are \(25\) inversions in it.In the third test case, array \(a\) is equal to \([1, 2, 4, 8, 16]\). There are no inversions in it.
|
Input: 43 23 5 10 13 41 3 53 2 0 11 510 1 2 3 48 35 1 7 11 15 3 9 132 0 1 | Output: 9 25 0 104
|
Expert
| 6 | 796 | 696 | 105 | 19 |
1,624 |
A
|
1624A
|
A. Plus One on the Subset
| 800 |
math
|
Polycarp 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\))?
|
The 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\).
|
For each test case, print one integer — the minimum number of operations to make all elements of the array \(a\) equal.
|
First 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]\).
|
Input: 363 4 2 4 1 231000 1002 998212 11 | Output: 3 4 1
|
Beginner
| 1 | 755 | 452 | 119 | 16 |
1,879 |
A
|
1879A
|
A. Rigged!
| 800 |
greedy
|
Monocarp organizes a weightlifting competition. There are \(n\) athletes participating in the competition, the \(i\)-th athlete has strength \(s_i\) and endurance \(e_i\). The \(1\)-st athlete is Monocarp's friend Polycarp, and Monocarp really wants Polycarp to win.The competition will be conducted as follows. The jury will choose a positive (greater than zero) integer \(w\), which denotes the weight of the barbell that will be used in the competition. The goal for each athlete is to lift the barbell as many times as possible. The athlete who lifts the barbell the most amount of times will be declared the winner (if there are multiple such athletes — there's no winner).If the barbell's weight \(w\) is strictly greater than the strength of the \(i\)-th athlete \(s_i\), then the \(i\)-th athlete will be unable to lift the barbell even one single time. Otherwise, the \(i\)-th athlete will be able to lift the barbell, and the number of times he does it will be equal to his endurance \(e_i\).For example, suppose there are \(4\) athletes with parameters \(s_1 = 7, e_1 = 4\); \(s_2 = 9, e_2 = 3\); \(s_3 = 4, e_3 = 6\); \(s_4 = 2, e_4 = 2\). If the weight of the barbell is \(5\), then: the first athlete will be able to lift the barbell \(4\) times; the second athlete will be able to lift the barbell \(3\) times; the third athlete will be unable to lift the barbell; the fourth athlete will be unable to lift the barbell. Monocarp wants to choose \(w\) in such a way that Polycarp (the \(1\)-st athlete) wins the competition. Help him to choose the value of \(w\), or report that it is impossible.
|
The first line contains one integer \(t\) (\(1 \le t \le 100\)) — the number of test cases.The first line of each test case contains one integer \(n\) (\(2 \le n \le 100\)) — the number of athletes. Then \(n\) lines follow, the \(i\)-th of them contains two integers \(s_i\) and \(e_i\) (\(1 \le s_i \le 10^9\); \(1 \le e_i \le 100\)) — the strength and the endurance of the \(i\)-th athlete.
|
For each test case, print the answer as follows: if the answer exists, print one integer — the value of \(w\) meeting the constraints. The integer you print should satisfy \(1 \le w \le 10^9\). It can be shown that if the answer exists, at least one such value of \(w\) exists as well. If there are multiple answers, you can print any of them; otherwise, print one integer \(-1\).
|
The first test case of the example is described in the statement.
|
Input: 347 49 34 62 224 6100 10021337 31337 3 | Output: 5 -1 -1
|
Beginner
| 1 | 1,610 | 392 | 380 | 18 |
1,536 |
E
|
1536E
|
E. Omkar and Forest
| 2,300 |
combinatorics; graphs; math; shortest paths
|
Omkar's most recent follower, Ajit, has entered the Holy Forest. Ajit realizes that Omkar's forest is an \(n\) by \(m\) grid (\(1 \leq n, m \leq 2000\)) of some non-negative integers. Since the forest is blessed by Omkar, it satisfies some special conditions: For any two adjacent (sharing a side) cells, the absolute value of the difference of numbers in them is at most \(1\). If the number in some cell is strictly larger than \(0\), it should be strictly greater than the number in at least one of the cells adjacent to it. Unfortunately, Ajit is not fully worthy of Omkar's powers yet. He sees each cell as a ""0"" or a ""#"". If a cell is labeled as ""0"", then the number in it must equal \(0\). Otherwise, the number in it can be any nonnegative integer.Determine how many different assignments of elements exist such that these special conditions are satisfied. Two assignments are considered different if there exists at least one cell such that the numbers written in it in these assignments are different. Since the answer may be enormous, find the answer modulo \(10^9+7\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \leq t \leq 100\)). Description of the test cases follows.The first line of each test case contains two integers \(n\) and \(m\) (\(1 \leq n, m \leq 2000, nm \geq 2\)) – the dimensions of the forest.\(n\) lines follow, each consisting of one string of \(m\) characters. Each of these characters is either a ""0"" or a ""#"".It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2000\) and the sum of \(m\) over all test cases does not exceed \(2000\).
|
For each test case, print one integer: the number of valid configurations modulo \(10^9+7\).
|
For the first test case, the two valid assignments are\(0000\\ 0000\\ 0000\)and\(0000\\ 0010\\ 0000\)
|
Input: 4 3 4 0000 00#0 0000 2 1 # # 1 2 ## 6 29 ############################# #000##0###0##0#0####0####000# #0#0##00#00##00####0#0###0#0# #0#0##0#0#0##00###00000##00## #000##0###0##0#0##0###0##0#0# ############################# | Output: 2 3 3 319908071
|
Expert
| 4 | 1,086 | 574 | 92 | 15 |
2,002 |
D1
|
2002D1
|
D1. DFS Checker (Easy Version)
| 1,900 |
brute force; data structures; dfs and similar; graphs; hashing; trees
|
This is the easy version of the problem. In this version, the given tree is a perfect binary tree and the constraints on \(n\) and \(q\) are lower. You can make hacks only if both versions of the problem are solved.You are given a perfect binary tree\(^\dagger\) consisting of \(n\) vertices. The vertices are numbered from \(1\) to \(n\), and the root is the vertex \(1\). You are also given a permutation \(p_1, p_2, \ldots, p_n\) of \([1,2,\ldots,n]\).You need to answer \(q\) queries. For each query, you are given two integers \(x\), \(y\); you need to swap \(p_x\) and \(p_y\) and determine if \(p_1, p_2, \ldots, p_n\) is a valid DFS order\(^\ddagger\) of the given tree.Please note that the swaps are persistent through queries.\(^\dagger\) A perfect binary tree is a tree with vertex \(1\) as its root, with size \(n=2^k-1\) for a positive integer \(k\), and where the parent of each vertex \(i\) (\(1<i\le n\)) is \(\left\lfloor\frac{i}{2}\right\rfloor\). Thus, all leaves of this tree are at a distance \(k - 1\) from the root.\(^\ddagger\) A DFS order is found by calling the following \(\texttt{dfs}\) function on the given tree.dfs_order = []function dfs(v): append v to the back of dfs_order pick an arbitrary permutation s of children of v for child in s: dfs(child)dfs(1)Note that the DFS order is not unique.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1\le t\le10^4\)). The description of the test cases follows. The first line of each test case contains two integers \(n\), \(q\) (\(3\le n\le 65\,535\), \(2\le q\le 5 \cdot 10^4\)) — the number of vertices in the tree and the number of queries. It is guaranteed that \(n=2^k-1\) for a positive integer \(k\).The next line contains \(n-1\) integers \(a_2,a_3,\ldots,a_n\) (\(1\le a_i<i\)) — the parent of each vertex in the given tree. It is guaranteed that \(a_i=\left\lfloor\frac{i}{2}\right\rfloor\).The next line contains \(n\) integers \(p_1,p_2,\ldots,p_n\) (\(1\le p_i\le n\), all \(p_i\) are distinct) — the initial permutation \(p\).The next \(q\) lines each contain two integers \(x\), \(y\) (\(1\le x,y\le n,x\neq y\)) — the positions of the elements to swap in the permutation.It is guaranteed that the sum of all \(n\) does not exceed \(65\,535\), and the sum of all \(q\) does not exceed \(5 \cdot 10^4\).
|
For each test case, print \(q\) lines corresponding to the \(q\) queries. For each query, output \(\texttt{YES}\) if there is a DFS order that exactly equals the current permutation, and output \(\texttt{NO}\) otherwise.You can output \(\texttt{Yes}\) and \(\texttt{No}\) in any case (for example, strings \(\texttt{yEs}\), \(\texttt{yes}\), \(\texttt{Yes}\) and \(\texttt{YES}\) will be recognized as a positive response).
|
In the first test case, the permutation \(p_1, p_2, \ldots, p_n\) after each modification is \([1,3,2],[1,2,3],[3,2,1]\), respectively. The first two permutations are valid DFS orders; the third is not a DFS order.In the second test case, the permutation \(p_1, p_2, \ldots, p_n\) after each modification is \([1,2,5,4,3,6,7],[1,3,5,4,2,6,7],[1,3,7,4,2,6,5],[1,3,7,6,2,4,5]\), respectively.
|
Input: 23 31 11 2 32 33 21 37 41 1 2 2 3 31 2 3 4 5 6 73 52 53 74 6 | Output: YES YES NO YES NO NO YES
|
Hard
| 6 | 1,326 | 1,016 | 423 | 20 |
1,386 |
B
|
1386B
|
B. Mixture
| 2,900 |
*special; data structures; geometry; math; sortings
|
Serge, the chef of the famous restaurant ""Salt, Pepper & Garlic"" is trying to obtain his first Michelin star. He has been informed that a secret expert plans to visit his restaurant this evening.Even though the expert's name hasn't been disclosed, Serge is certain he knows which dish from the menu will be ordered as well as what the taste preferences of the expert are. Namely, the expert requires an extremely precise proportion of salt, pepper and garlic powder in his dish.Serge keeps a set of bottles with mixtures of salt, pepper and garlic powder on a special shelf in the kitchen. For each bottle, he knows the exact amount of each of the ingredients in kilograms. Serge can combine any number of bottled mixtures (or just use one of them directly) to get a mixture of particular proportions needed for a certain dish.Luckily, the absolute amount of a mixture that needs to be added to a dish is so small that you can assume that the amounts in the bottles will always be sufficient. However, the numeric values describing the proportions may be quite large.Serge would like to know whether it is possible to obtain the expert's favourite mixture from the available bottles, and if so—what is the smallest possible number of bottles needed to achieve that.Furthermore, the set of bottles on the shelf may change over time as Serge receives new ones or lends his to other chefs. So he would like to answer this question after each such change.For example, assume that expert's favorite mixture is \(1:1:1\) and there are three bottles of mixtures on the shelf: $$$\( \begin{array}{cccc} \hline \text{Mixture} & \text{Salt} & \text{Pepper} & \text{Garlic powder} \\ \hline 1 & 10 & 20 & 30 \\ 2 & 300 & 200 & 100 \\ 3 & 12 & 15 & 27 \\ \hline \end{array} \)$$$ Amount of ingredient in the bottle, kg To obtain the desired mixture it is enough to use an equivalent amount of mixtures from bottles 1 and 2. If bottle 2 is removed, then it is no longer possible to obtain it.Write a program that helps Serge to solve this task!
|
The first row contains three non-negative integers \(S_f\), \(P_f\) and \(G_f\) (\(0 \leq S_f, P_f, G_f\); \(0 < S_f+P_f+G_f \leq 10^6\)) describing the amount of salt, pepper and garlic powder in the expert's favourite mixture. For any real \(\alpha>0\), \((\alpha{S_f}, \alpha{P_f}, \alpha{G_f})\) also is an expert's favourite mixture.In the second row, there is a positive integer \(N\) (number of changes on the shelf, \(N \leq 100\,000\)). You should assume that initially the shelf is empty.Each of the next \(N\) rows describes a single change on the shelf: If a new bottle is added, the row contains capital letter \(A\) followed by three non-negative integers \(S_i\), \(P_i\) and \(G_i\) (\(0 \leq S_i, P_i, G_i\); \(0 < S_i+P_i+G_i \leq 10^6\)) describing the amount of salt, pepper and garlic powder in the added bottle. Added bottles are numbered consecutively by unique integers starting from \(1\), that is, the \(i\)-th bottle corresponds to the \(i\)-th added bottle in the input data. If a particular bottle is removed from the shelf, the row contains capital letter \(R\) followed by the integer—the bottle number \(r_i\). All values \(r_i\) in the removals are unique, \(r_i\) never exceeds total number of bottles added thus far.
|
Output \(N\) rows. The \(j\)-th row (\(1 \leq j \leq N\)) should contain the number \(x_j\), the smallest number of bottles needed to prepare a mixture with the expert's favourite proportions of salt, pepper and garlic powder using the bottles available after the first \(j\) changes on the shelf, or \(0\) if it is not possible.
|
Pay attention that in the example, bottles \(1\) and \(3\) contain the same proportions of salt, pepper and garlic powder.
|
Input: 1 2 3 6 A 5 6 7 A 3 10 17 R 1 A 15 18 21 A 5 10 15 R 3 | Output: 0 2 0 2 1 1
|
Master
| 5 | 2,033 | 1,251 | 329 | 13 |
413 |
E
|
413E
|
E. Maze 2D
| 2,200 |
data structures; divide and conquer
|
The last product of the R2 company in the 2D games' field is a new revolutionary algorithm of searching for the shortest path in a 2 × n maze.Imagine a maze that looks like a 2 × n rectangle, divided into unit squares. Each unit square is either an empty cell or an obstacle. In one unit of time, a person can move from an empty cell of the maze to any side-adjacent empty cell. The shortest path problem is formulated as follows. Given two free maze cells, you need to determine the minimum time required to go from one cell to the other.Unfortunately, the developed algorithm works well for only one request for finding the shortest path, in practice such requests occur quite often. You, as the chief R2 programmer, are commissioned to optimize the algorithm to find the shortest path. Write a program that will effectively respond to multiple requests to find the shortest path in a 2 × n maze.
|
The first line contains two integers, n and m (1 ≤ n ≤ 2·105; 1 ≤ m ≤ 2·105) — the width of the maze and the number of queries, correspondingly. Next two lines contain the maze. Each line contains n characters, each character equals either '.' (empty cell), or 'X' (obstacle).Each of the next m lines contains two integers vi and ui (1 ≤ vi, ui ≤ 2n) — the description of the i-th request. Numbers vi, ui mean that you need to print the value of the shortest path from the cell of the maze number vi to the cell number ui. We assume that the cells of the first line of the maze are numbered from 1 to n, from left to right, and the cells of the second line are numbered from n + 1 to 2n from left to right. It is guaranteed that both given cells are empty.
|
Print m lines. In the i-th line print the answer to the i-th request — either the size of the shortest path or -1, if we can't reach the second cell from the first one.
|
Input: 4 7.X.....X5 11 37 71 46 14 75 7 | Output: 1405222
|
Hard
| 2 | 898 | 756 | 168 | 4 |
|
1,354 |
E
|
1354E
|
E. Graph Coloring
| 2,100 |
dfs and similar; dp; graphs
|
You are given an undirected graph without self-loops or multiple edges which consists of \(n\) vertices and \(m\) edges. Also you are given three integers \(n_1\), \(n_2\) and \(n_3\).Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to \(n_1\); The total number of vertices with label 2 should be equal to \(n_2\); The total number of vertices with label 3 should be equal to \(n_3\); \(|col_u - col_v| = 1\) for each edge \((u, v)\), where \(col_x\) is the label of vertex \(x\). If there are multiple valid labelings, print any of them.
|
The first line contains two integers \(n\) and \(m\) (\(1 \le n \le 5000\); \(0 \le m \le 10^5\)) — the number of vertices and edges in the graph.The second line contains three integers \(n_1\), \(n_2\) and \(n_3\) (\(0 \le n_1, n_2, n_3 \le n\)) — the number of labels 1, 2 and 3, respectively. It's guaranteed that \(n_1 + n_2 + n_3 = n\).Next \(m\) lines contan description of edges: the \(i\)-th line contains two integers \(u_i\), \(v_i\) (\(1 \le u_i, v_i \le n\); \(u_i \neq v_i\)) — the vertices the \(i\)-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
|
If valid labeling exists then print ""YES"" (without quotes) in the first line. In the second line print string of length \(n\) consisting of 1, 2 and 3. The \(i\)-th letter should be equal to the label of the \(i\)-th vertex.If there is no valid labeling, print ""NO"" (without quotes).
|
Input: 6 3 2 2 2 3 1 5 4 2 5 | Output: YES 112323
|
Hard
| 3 | 691 | 608 | 287 | 13 |
|
816 |
B
|
816B
|
B. Karen and Coffee
| 1,400 |
binary search; data structures; implementation
|
To stay woke and attentive during classes, Karen needs some coffee! Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed ""The Art of the Covfefe"".She knows n coffee recipes. The i-th recipe suggests that coffee should be brewed between li and ri degrees, inclusive, to achieve the optimal taste.Karen thinks that a temperature is admissible if at least k recipes recommend it.Karen has a rather fickle mind, and so she asks q questions. In each question, given that she only wants to prepare coffee with a temperature between a and b, inclusive, can you tell her how many admissible integer temperatures fall within the range?
|
The first line of input contains three integers, n, k (1 ≤ k ≤ n ≤ 200000), and q (1 ≤ q ≤ 200000), the number of recipes, the minimum number of recipes a certain temperature must be recommended by to be admissible, and the number of questions Karen has, respectively.The next n lines describe the recipes. Specifically, the i-th line among these contains two integers li and ri (1 ≤ li ≤ ri ≤ 200000), describing that the i-th recipe suggests that the coffee be brewed between li and ri degrees, inclusive.The next q lines describe the questions. Each of these lines contains a and b, (1 ≤ a ≤ b ≤ 200000), describing that she wants to know the number of admissible integer temperatures between a and b degrees, inclusive.
|
For each question, output a single integer on a line by itself, the number of admissible integer temperatures between a and b degrees, inclusive.
|
In the first test case, Karen knows 3 recipes. The first one recommends brewing the coffee between 91 and 94 degrees, inclusive. The second one recommends brewing the coffee between 92 and 97 degrees, inclusive. The third one recommends brewing the coffee between 97 and 99 degrees, inclusive. A temperature is admissible if at least 2 recipes recommend it.She asks 4 questions.In her first question, she wants to know the number of admissible integer temperatures between 92 and 94 degrees, inclusive. There are 3: 92, 93 and 94 degrees are all admissible.In her second question, she wants to know the number of admissible integer temperatures between 93 and 97 degrees, inclusive. There are 3: 93, 94 and 97 degrees are all admissible.In her third question, she wants to know the number of admissible integer temperatures between 95 and 96 degrees, inclusive. There are none.In her final question, she wants to know the number of admissible integer temperatures between 90 and 100 degrees, inclusive. There are 4: 92, 93, 94 and 97 degrees are all admissible.In the second test case, Karen knows 2 recipes. The first one, ""wikiHow to make Cold Brew Coffee"", recommends brewing the coffee at exactly 1 degree. The second one, ""What good is coffee that isn't brewed at at least 36.3306 times the temperature of the surface of the sun?"", recommends brewing the coffee at exactly 200000 degrees. A temperature is admissible if at least 1 recipe recommends it.In her first and only question, she wants to know the number of admissible integer temperatures that are actually reasonable. There are none.
|
Input: 3 2 491 9492 9797 9992 9493 9795 9690 100 | Output: 3304
|
Easy
| 3 | 778 | 723 | 145 | 8 |
592 |
A
|
592A
|
A. PawnChess
| 1,200 |
implementation
|
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed. Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
|
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'. It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
|
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
|
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
|
Input: .................B....B.....W.............W..................... | Output: A
|
Easy
| 1 | 1,874 | 327 | 177 | 5 |
274 |
B
|
274B
|
B. Zero Tree
| 1,800 |
dfs and similar; dp; greedy; trees
|
A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.
|
The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109).
|
Print the minimum number of operations needed to solve the task.Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
Input: 31 21 31 -1 1 | Output: 3
|
Medium
| 4 | 886 | 346 | 213 | 2 |
|
1,207 |
A
|
1207A
|
A. There Are Two Types Of Burgers
| 800 |
brute force; greedy; implementation; math
|
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have \(b\) buns, \(p\) beef patties and \(f\) chicken cutlets in your restaurant. You can sell one hamburger for \(h\) dollars and one chicken burger for \(c\) dollars. Calculate the maximum profit you can achieve.You have to answer \(t\) independent queries.
|
The first line contains one integer \(t\) (\(1 \le t \le 100\)) – the number of queries.The first line of each query contains three integers \(b\), \(p\) and \(f\) (\(1 \le b, ~p, ~f \le 100\)) — the number of buns, beef patties and chicken cutlets in your restaurant.The second line of each query contains two integers \(h\) and \(c\) (\(1 \le h, ~c \le 100\)) — the hamburger and chicken burger prices in your restaurant.
|
For each query print one integer — the maximum profit you can achieve.
|
In first query you have to sell two hamburgers and three chicken burgers. Your income is \(2 \cdot 5 + 3 \cdot 10 = 40\).In second query you have to ell one hamburgers and two chicken burgers. Your income is \(1 \cdot 10 + 2 \cdot 12 = 34\).In third query you can not create any type of burgers because because you have only one bun. So your income is zero.
|
Input: 3 15 2 3 5 10 7 5 2 10 12 1 100 100 100 100 | Output: 40 34 0
|
Beginner
| 4 | 476 | 423 | 70 | 12 |
1,031 |
C
|
1031C
|
C. Cram Time
| 1,600 |
greedy
|
In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.Lesha knows that today he can study for at most \(a\) hours, and he will have \(b\) hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number \(k\) in \(k\) hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day.Thus, the student has to fully read several lecture notes today, spending at most \(a\) hours in total, and fully read several lecture notes tomorrow, spending at most \(b\) hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which — in the second?
|
The only line of input contains two integers \(a\) and \(b\) (\(0 \leq a, b \leq 10^{9}\)) — the number of hours Lesha has today and the number of hours Lesha has tomorrow.
|
In the first line print a single integer \(n\) (\(0 \leq n \leq a\)) — the number of lecture notes Lesha has to read in the first day. In the second line print \(n\) distinct integers \(p_1, p_2, \ldots, p_n\) (\(1 \leq p_i \leq a\)), the sum of all \(p_i\) should not exceed \(a\).In the third line print a single integer \(m\) (\(0 \leq m \leq b\)) — the number of lecture notes Lesha has to read in the second day. In the fourth line print \(m\) distinct integers \(q_1, q_2, \ldots, q_m\) (\(1 \leq q_i \leq b\)), the sum of all \(q_i\) should not exceed \(b\).All integers \(p_i\) and \(q_i\) should be distinct. The sum \(n + m\) should be largest possible.
|
In the first example Lesha can read the third note in \(3\) hours in the first day, and the first and the second notes in one and two hours correspondingly in the second day, spending \(3\) hours as well. Note that Lesha can make it the other way round, reading the first and the second notes in the first day and the third note in the second day.In the second example Lesha should read the third and the sixth notes in the first day, spending \(9\) hours in total. In the second day Lesha should read the first, second fourth and fifth notes, spending \(12\) hours in total.
|
Input: 3 3 | Output: 13 22 1
|
Medium
| 1 | 1,264 | 172 | 663 | 10 |
680 |
A
|
680A
|
A. Bear and Five Cards
| 800 |
constructive algorithms; implementation
|
A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer.Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards.He is allowed to at most once discard two or three cards with the same number. Of course, he won't discard cards if it's impossible to choose two or three cards with the same number.Given five numbers written on cards, cay you find the minimum sum of numbers on remaining cards?
|
The only line of the input contains five integers t1, t2, t3, t4 and t5 (1 ≤ ti ≤ 100) — numbers written on cards.
|
Print the minimum possible sum of numbers written on remaining cards.
|
In the first sample, Limak has cards with numbers 7, 3, 7, 3 and 20. Limak can do one of the following. Do nothing and the sum would be 7 + 3 + 7 + 3 + 20 = 40. Remove two cards with a number 7. The remaining sum would be 3 + 3 + 20 = 26. Remove two cards with a number 3. The remaining sum would be 7 + 7 + 20 = 34. You are asked to minimize the sum so the answer is 26.In the second sample, it's impossible to find two or three cards with the same number. Hence, Limak does nothing and the sum is 7 + 9 + 1 + 3 + 8 = 28.In the third sample, all cards have the same number. It's optimal to discard any three cards. The sum of two remaining numbers is 10 + 10 = 20.
|
Input: 7 3 7 3 20 | Output: 26
|
Beginner
| 2 | 535 | 114 | 69 | 6 |
1,761 |
F1
|
1761F1
|
F1. Anti-median (Easy Version)
| 3,100 |
dp; math
|
This is the easy version of the problem. The only difference between the two versions is the constraint on \(n\). You can make hacks only if all versions of the problem are solved.Let's call an array \(a\) of odd length \(2m+1\) (with \(m \ge 1\)) bad, if element \(a_{m+1}\) is equal to the median of this array. In other words, the array is bad if, after sorting it, the element at \(m+1\)-st position remains the same.Let's call a permutation \(p\) of integers from \(1\) to \(n\) anti-median, if every its subarray of odd length \(\ge 3\) is not bad.You are already given values of some elements of the permutation. Find the number of ways to set unknown values to obtain an anti-median permutation. As this number can be very large, find it modulo \(10^9+7\).
|
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer \(n\) \((2 \le n \le 1000)\) — the length of the permutation.The second line of each test case contains \(n\) integers \(p_1, p_2, \ldots, p_n\) (\(1 \le p_i \le n\), or \(p_i = -1\)) — the elements of the permutation. If \(p_i \neq -1\), it's given, else it's unknown. It's guaranteed that if for some \(i \neq j\) holds \(p_i \neq -1, p_j \neq -1\), then \(p_i \neq p_j\).It is guaranteed that the sum of \(n^2\) over all test cases does not exceed \(10^6\).
|
For each test case, output a single integer — the number of ways to set unknown values to obtain an anti-median permutation, modulo \(10^9+7\).
|
In the first test case, both \([1, 2]\) and \([2, 1]\) are anti-median.In the second test case, permutations \([1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2]\) are anti-median. The remaining two permutations, \([1, 2, 3]\), \([3, 2, 1]\), are bad arrays on their own, as their median, \(2\), is in their middle.In the third test case, \([1, 2, 3, 4]\) isn't anti-median, as it contains bad subarray \([1, 2, 3]\).In the fourth test case, the only anti-median array you can get is \([5, 6, 3, 4, 1, 2]\).
|
Input: 52-1 -13-1 -1 -141 2 3 46-1 -1 3 4 -1 -18-1 -1 -1 -1 -1 -1 -1 -1 | Output: 2 4 0 1 316
|
Master
| 2 | 764 | 655 | 143 | 17 |
298 |
A
|
298A
|
A. Snow Footprints
| 1,300 |
greedy; implementation
|
There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints.
|
The first line of the input contains integer n (3 ≤ n ≤ 1000).The second line contains the description of the road — the string that consists of n characters. Each character will be either ""."" (a block without footprint), or ""L"" (a block with a left footprint), ""R"" (a block with a right footprint).It's guaranteed that the given string contains at least one character not equal to ""."". Also, the first and the last character will always be ""."". It's guaranteed that a solution exists.
|
Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them.
|
The first test sample is the one in the picture.
|
Input: 9..RRLL... | Output: 3 4
|
Easy
| 2 | 773 | 495 | 126 | 2 |
938 |
D
|
938D
|
D. Buy a Ticket
| 2,000 |
data structures; graphs; shortest paths
|
Musicians of a popular band ""Flayer"" have announced that they are going to ""make their exit"" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by ""Flayer"", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
|
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105).Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input.The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
|
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
|
Input: 4 21 2 42 3 76 20 1 25 | Output: 6 14 1 25
|
Hard
| 3 | 1,139 | 461 | 221 | 9 |
|
1,012 |
C
|
1012C
|
C. Hills
| 1,900 |
dp
|
Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5, 4, 6, 2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up.
|
The first line of input contains the only integer n (1 ≤ n ≤ 5000)—the number of the hills in the sequence.Second line contains n integers ai (1 ≤ ai ≤ 100 000)—the heights of the hills in the sequence.
|
Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses.
|
In the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1, 0, 1, 1, 1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1, 0, 1, 0, 1, and hills 1, 3, 5 become suitable for construction.
|
Input: 51 1 1 1 1 | Output: 1 2 2
|
Hard
| 1 | 1,207 | 202 | 179 | 10 |
464 |
B
|
464B
|
B. Restore Cube
| 2,000 |
brute force; geometry
|
Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers — coordinates of cube's vertex (a single line contains coordinates of a single vertex, each vertex is written exactly once), put the paper on the table and left. While Peter was away, his little brother Nick decided to play with the numbers on the paper. In one operation Nick could swap some numbers inside a single line (Nick didn't swap numbers from distinct lines). Nick could have performed any number of such operations.When Peter returned and found out about Nick's mischief, he started recollecting the original coordinates. Help Peter restore the original position of the points or else state that this is impossible and the numbers were initially recorded incorrectly.
|
Each of the eight lines contains three space-separated integers — the numbers written on the piece of paper after Nick's mischief. All numbers do not exceed 106 in their absolute value.
|
If there is a way to restore the cube, then print in the first line ""YES"". In each of the next eight lines print three integers — the restored coordinates of the points. The numbers in the i-th output line must be a permutation of the numbers in i-th input line. The numbers should represent the vertices of a cube with non-zero length of a side. If there are multiple possible ways, print any of them.If there is no valid way, print ""NO"" (without the quotes) in the first line. Do not print anything else.
|
Input: 0 0 00 0 10 0 10 0 10 1 10 1 10 1 11 1 1 | Output: YES0 0 00 0 10 1 01 0 00 1 11 0 11 1 01 1 1
|
Hard
| 2 | 995 | 185 | 510 | 4 |
|
1,952 |
F
|
1952F
|
F. Grid
| 0 |
*special; brute force
|
The input contains \(21\) lines, each containing \(21\) characters \(\texttt{0}\) or \(\texttt{1}\).
|
Input: 111111101011101111111100000100011001000001101110101101001011101101110101100101011101101110101001001011101100000100111101000001111111101010101111111000000000001100000000111100101111110011101000111010101100110101111101101101001000011001001000001000011000111101110000111001011000000001001001111100111111100001101010000100000100010010100111101110100110110011100101110101100000100010101110101010110000100100000101000011001001111111101011111111100 | Output: 12
|
Beginner
| 2 | 0 | 100 | 0 | 19 |
|||
996 |
A
|
996A
|
A. Hit the Lottery
| 800 |
dp; greedy
|
Allen has a LOT of money. He has \(n\) dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are \(1\), \(5\), \(10\), \(20\), \(100\). What is the minimum number of bills Allen could receive after withdrawing his entire balance?
|
The first and only line of input contains a single integer \(n\) (\(1 \le n \le 10^9\)).
|
Output the minimum number of bills that Allen could receive.
|
In the first sample case, Allen can withdraw this with a \(100\) dollar bill, a \(20\) dollar bill, and a \(5\) dollar bill. There is no way for Allen to receive \(125\) dollars in one or two bills.In the second sample case, Allen can withdraw two \(20\) dollar bills and three \(1\) dollar bills.In the third sample case, Allen can withdraw \(100000000\) (ten million!) \(100\) dollar bills.
|
Input: 125 | Output: 3
|
Beginner
| 2 | 326 | 88 | 60 | 9 |
810 |
B
|
810B
|
B. Summer sell-off
| 1,300 |
greedy; sortings
|
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.Shop, where Noora is working, has a plan on the following n days. For each day sales manager knows exactly, that in i-th day ki products will be put up for sale and exactly li clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any f days from n next for sell-outs. On each of f chosen days the number of products were put up for sale would be doubled. Thus, if on i-th day shop planned to put up for sale ki products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·ki products. Consequently, there is an opportunity to sell two times more products on days of sell-out.Noora's task is to choose f days to maximize total number of sold products. She asks you to help her with such a difficult problem.
|
The first line contains two integers n and f (1 ≤ n ≤ 105, 0 ≤ f ≤ n) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out.Each line of the following n subsequent lines contains two integers ki, li (0 ≤ ki, li ≤ 109) denoting the number of products on the shelves of the shop on the i-th day and the number of clients that will come to the shop on i-th day.
|
Print a single integer denoting the maximal number of products that shop can sell.
|
In the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2, 6, 2, 2] respectively. So on the first day shop will sell 1 product, on the second — 5, on the third — 2, on the fourth — 2. In total 1 + 5 + 2 + 2 = 10 product units.In the second example it is possible to sell 5 products, if you choose third day for sell-out.
|
Input: 4 22 13 52 31 5 | Output: 10
|
Easy
| 2 | 1,437 | 408 | 82 | 8 |
1,975 |
D
|
1975D
|
D. Paint the Tree
| 1,700 |
brute force; dfs and similar; dp; greedy; shortest paths; trees
|
378QAQ has a tree with \(n\) vertices. Initially, all vertices are white. There are two chess pieces called \(P_A\) and \(P_B\) on the tree. \(P_A\) and \(P_B\) are initially located on vertices \(a\) and \(b\) respectively. In one step, 378QAQ will do the following in order: Move \(P_A\) to a neighboring vertex. If the target vertex is white, this vertex will be painted red. Move \(P_B\) to a neighboring vertex. If the target vertex is colored in red, this vertex will be painted blue. Initially, the vertex \(a\) is painted red. If \(a=b\), the vertex \(a\) is painted blue instead. Note that both the chess pieces must be moved in each step. Two pieces can be on the same vertex at any given time.378QAQ wants to know the minimum number of steps to paint all vertices blue.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1\leq t\leq 10^4\)). The description of the test cases follows.The first line of each test case contains one integer \(n\) (\(1\leq n\leq 2\cdot 10^5\)).The second line of each test case contains two integers \(a\) and \(b\) (\(1\leq a,b\leq n\)).Then \(n - 1\) lines follow, each line contains two integers \(x_i\) and \(y_i\) (\(1 \le x_i,y_i \le n\)), indicating an edge between vertices \(x_i\) and \(y_i\). It is guaranteed that these edges form a tree.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot 10^5\).
|
For each test case, output the minimum number of steps to paint all vertices blue.
|
In the first test case, 378QAQ can paint all vertices blue in the following order: Initially, \(P_A\) is located on the vertex \(1\), and \(P_B\) is located on the vertex \(2\). The vertex \(1\) is painted red and the vertex \(2\) is white. 378QAQ moves \(P_A\) to the vertex \(2\) and paints it red. Then 378QAQ moves \(P_B\) to the vertex \(1\) and paints it blue. 378QAQ moves \(P_A\) to the vertex \(1\). Then 378QAQ moves \(P_B\) to the vertex \(2\) and paints it blue.
|
Input: 321 21 251 21 21 31 41 585 47 11 51 88 37 28 63 4 | Output: 2 8 13
|
Medium
| 6 | 780 | 647 | 82 | 19 |
1,146 |
H
|
1146H
|
H. Satanic Panic
| 2,900 |
dp; geometry
|
You are given a set of \(n\) points in a 2D plane. No three points are collinear.A pentagram is a set of \(5\) points \(A,B,C,D,E\) that can be arranged as follows. Note the length of the line segments don't matter, only that those particular intersections exist.Count the number of ways to choose \(5\) points from the given set that form a pentagram.
|
The first line contains an integer \(n\) (\(5 \leq n \leq 300\)) — the number of points.Each of the next \(n\) lines contains two integers \(x_i, y_i\) (\(-10^6 \leq x_i,y_i \leq 10^6\)) — the coordinates of the \(i\)-th point. It is guaranteed that no three points are collinear.
|
Print a single integer, the number of sets of \(5\) points that form a pentagram.
|
A picture of the first sample: A picture of the second sample: A picture of the third sample:
|
Input: 5 0 0 0 2 2 0 2 2 1 3 | Output: 1
|
Master
| 2 | 352 | 280 | 81 | 11 |
817 |
F
|
817F
|
F. MEX Queries
| 2,300 |
binary search; data structures; trees
|
You are given a set of integer numbers, initially it is empty. You should perform n queries.There are three different types of queries: 1 l r — Add all missing numbers from the interval [l, r] 2 l r — Remove all present numbers from the interval [l, r] 3 l r — Invert the interval [l, r] — add all missing and remove all present numbers from the interval [l, r] After each query you should output MEX of the set — the smallest positive (MEX ≥ 1) integer number which is not presented in the set.
|
The first line contains one integer number n (1 ≤ n ≤ 105).Next n lines contain three integer numbers t, l, r (1 ≤ t ≤ 3, 1 ≤ l ≤ r ≤ 1018) — type of the query, left and right bounds.
|
Print MEX of the set after each query.
|
Here are contents of the set after each query in the first example: {3, 4} — the interval [3, 4] is added {1, 2, 5, 6} — numbers {3, 4} from the interval [1, 6] got deleted and all the others are added {5, 6} — numbers {1, 2} got deleted
|
Input: 31 3 43 1 62 1 3 | Output: 131
|
Expert
| 3 | 495 | 183 | 38 | 8 |
1,394 |
E
|
1394E
|
E. Boboniu and Banknote Collection
| 3,500 |
strings
|
No matter what trouble you're in, don't be afraid, but face it with a smile.I've made another billion dollars! — BoboniuBoboniu has issued his currencies, named Bobo Yuan. Bobo Yuan (BBY) is a series of currencies. Boboniu gives each of them a positive integer identifier, such as BBY-1, BBY-2, etc.Boboniu has a BBY collection. His collection looks like a sequence. For example: We can use sequence \(a=[1,2,3,3,2,1,4,4,1]\) of length \(n=9\) to denote it.Now Boboniu wants to fold his collection. You can imagine that Boboniu stick his collection to a long piece of paper and fold it between currencies: Boboniu will only fold the same identifier of currencies together. In other words, if \(a_i\) is folded over \(a_j\) (\(1\le i,j\le n\)), then \(a_i=a_j\) must hold. Boboniu doesn't care if you follow this rule in the process of folding. But once it is finished, the rule should be obeyed.A formal definition of fold is described in notes.According to the picture above, you can fold \(a\) two times. In fact, you can fold \(a=[1,2,3,3,2,1,4,4,1]\) at most two times. So the maximum number of folds of it is \(2\).As an international fan of Boboniu, you're asked to calculate the maximum number of folds. You're given a sequence \(a\) of length \(n\), for each \(i\) (\(1\le i\le n\)), you need to calculate the maximum number of folds of \([a_1,a_2,\ldots,a_i]\).
|
The first line contains an integer \(n\) (\(1\le n\le 10^5\)).The second line contains \(n\) integers \(a_1,a_2,\ldots,a_n\) (\(1\le a_i\le n\)).
|
Print \(n\) integers. The \(i\)-th of them should be equal to the maximum number of folds of \([a_1,a_2,\ldots,a_i]\).
|
Formally, for a sequence \(a\) of length \(n\), let's define the folding sequence as a sequence \(b\) of length \(n\) such that: \(b_i\) (\(1\le i\le n\)) is either \(1\) or \(-1\). Let \(p(i)=[b_i=1]+\sum_{j=1}^{i-1}b_j\). For all \(1\le i<j\le n\), if \(p(i)=p(j)\), then \(a_i\) should be equal to \(a_j\). (\([A]\) is the value of boolean expression \(A\). i. e. \([A]=1\) if \(A\) is true, else \([A]=0\)).Now we define the number of folds of \(b\) as \(f(b)=\sum_{i=1}^{n-1}[b_i\ne b_{i+1}]\).The maximum number of folds of \(a\) is \(F(a)=\max\{ f(b)\mid b \text{ is a folding sequence of }a \}\).
|
Input: 9 1 2 3 3 2 1 4 4 1 | Output: 0 0 0 1 1 1 1 2 2
|
Master
| 1 | 1,370 | 145 | 118 | 13 |
714 |
B
|
714B
|
B. Filya and Homework
| 1,200 |
implementation; sortings
|
Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help.Filya is given an array of non-negative integers a1, a2, ..., an. First, he pick an integer x and then he adds x to some elements of the array (no more than once), subtract x from some other elements (also, no more than once) and do no change other elements. He wants all elements of the array to be equal.Now he wonders if it's possible to pick such integer x and change some elements of the array using this x in order to make all elements equal.
|
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the number of integers in the Filya's array. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — elements of the array.
|
If it's impossible to make all elements of the array equal using the process given in the problem statement, then print ""NO"" (without quotes) in the only line of the output. Otherwise print ""YES"" (without quotes).
|
In the first sample Filya should select x = 1, then add it to the first and the last elements of the array and subtract from the second and the third elements.
|
Input: 51 3 3 2 1 | Output: YES
|
Easy
| 2 | 591 | 206 | 217 | 7 |
1,109 |
D
|
1109D
|
D. Sasha and Interesting Fact from Graph Theory
| 2,400 |
brute force; combinatorics; dp; math; trees
|
Once, during a lesson, Sasha got bored and decided to talk with his friends. Suddenly, he saw Kefa. Since we can talk endlessly about Kefa, we won't even start doing that. The conversation turned to graphs. Kefa promised Sasha to tell him about one interesting fact from graph theory if Sasha helps Kefa to count the number of beautiful trees. In this task, a tree is a weighted connected graph, consisting of \(n\) vertices and \(n-1\) edges, and weights of edges are integers from \(1\) to \(m\). Kefa determines the beauty of a tree as follows: he finds in the tree his two favorite vertices — vertices with numbers \(a\) and \(b\), and counts the distance between them. The distance between two vertices \(x\) and \(y\) is the sum of weights of edges on the simple path from \(x\) to \(y\). If the distance between two vertices \(a\) and \(b\) is equal to \(m\), then the tree is beautiful.Sasha likes graph theory, and even more, Sasha likes interesting facts, that's why he agreed to help Kefa. Luckily, Sasha is familiar with you the best programmer in Byteland. Help Sasha to count the number of beautiful trees for Kefa. Two trees are considered to be distinct if there is an edge that occurs in one of them and doesn't occur in the other one. Edge's weight matters.Kefa warned Sasha, that there can be too many beautiful trees, so it will be enough to count the number modulo \(10^9 + 7\).
|
The first line contains four integers \(n\), \(m\), \(a\), \(b\) (\(2 \le n \le 10^6\), \(1 \le m \le 10^6\), \(1 \le a, b \le n\), \(a \neq b\)) — the number of vertices in the tree, the maximum weight of an edge and two Kefa's favorite vertices.
|
Print one integer — the number of beautiful trees modulo \(10^9+7\).
|
There are \(5\) beautiful trees in the first example:In the second example the following trees are beautiful:
|
Input: 3 2 1 3 | Output: 5
|
Expert
| 5 | 1,399 | 247 | 68 | 11 |
105 |
D
|
105D
|
D. Entertaining Geodetics
| 2,700 |
brute force; dsu; implementation
|
The maps in the game are divided into square cells called Geo Panels. Some of these panels are painted. We shall assume that the Geo Panels without color are painted the transparent color. Besides, the map has so-called Geo Symbols. They look like pyramids of different colors (including Geo Symbols of the transparent color). Each Geo Symbol is located on one Geo Panel, and each Geo Panel may contain no more than one Geo Symbol. Geo Symbols can be eliminated. To understand better what happens when a Geo Symbol is eliminated, let us introduce some queue to which we will put the recently eliminated Geo Symbols. Let's put at the head of the queue a Geo Symbol that was eliminated just now. Next, we will repeat the following operation: Extract the Geo Symbol from the queue. Look at the color of the panel containing the given Geo Symbol. If it differs from transparent and differs from the color of the Geo Symbol, then all Geo Panels of this color are repainted in the color of the given Geo Symbol (transparent Geo Symbols repaint the Geo Panels transparent). Repainting is executed in an infinite spiral strictly in the following order starting from the panel, which contained the Geo Symbol: In other words, we select all the panels that need to be repainted and find their numbers in the infinite spiral whose center is placed in the position of the given Geo Symbol. After that, we repaint them in the order of the number's increasing. If a panel contains another Geo Symbol and this panel is being repainted, then the Geo Symbol is removed from the field and placed at the tail of the queue. After repainting the Geo Symbol is completely eliminated and the next Geo Symbol is taken from the head of the queue (if there is any) and the process repeats. The process ends if the queue is empty. See the sample analysis for better understanding. You know the colors of all the Geo Panels and the location of all the Geo Symbols. Determine the number of repaintings, which will occur if you destroy one of the Geo Symbols.
|
The first line contains two integers n and m (1 ≤ n, m ≤ 300) — the height and the width of the map (in cells).Then follow n line; each of them contains m numbers — the Geo Panels' colors.Then follow n more lines; each of them contains m numbers — the Geo Symbols' description. -1 means that the given position contains no Geo Symbol. Otherwise, the number represents the color of the Geo Symbol in the given position.All colors are integers from 0 to 109. 0 represents the transparent color.The last line contains two integers x and y (1 ≤ x ≤ n, 1 ≤ y ≤ m) — the row and the column where the Geo Symbol is placed that needs to be eliminated. The rows are numbered from top to bottom, the columns are numbered from left to right. Coordinates are 1-based. It is guaranteed that the position with coordinates (x, y) contains a Geo Symbol.
|
Print the single number — the total number of repaintings after the Geo Symbol is eliminated. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cout stream (you may also use the %I64d specificator).
|
All actions of the sample you can see on the following picture: If your browser does not support APNG and you see just static image, you can see GIF version of this image by the following link:http://assets.codeforces.com/images/geo_slow.gif
|
Input: 5 59 0 1 1 00 0 3 2 01 1 1 3 01 1 1 3 00 1 2 0 3-1 1 -1 3 -1-1 -1 -1 0 -1-1 -1 -1 -1 -1-1 2 3 -1 -1-1 -1 -1 -1 24 2 | Output: 35
|
Master
| 3 | 2,029 | 837 | 257 | 1 |
178 |
A3
|
178A3
|
A3. Educational Game
| 1,100 |
greedy
|
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequence) equal to zero for some fixed k (k < n), and this should be done in the smallest possible number of moves.One move is choosing an integer i (1 ≤ i ≤ n) such that ai > 0 and an integer t (t ≥ 0) such that i + 2t ≤ n. After the values of i and t have been selected, the value of ai is decreased by 1, and the value of ai + 2t is increased by 1. For example, let n = 4 and a = (1, 0, 1, 2), then it is possible to make move i = 3, t = 0 and get a = (1, 0, 0, 3) or to make move i = 1, t = 1 and get a = (0, 0, 2, 2) (the only possible other move is i = 1, t = 0).You are given n and the initial sequence ai. The task is to calculate the minimum number of moves needed to make the first k elements of the original sequence equal to zero for each possible k (1 ≤ k < n).
|
The first input line contains a single integer n. The second line contains n integers ai (0 ≤ ai ≤ 104), separated by single spaces.The input limitations for getting 20 points are: 1 ≤ n ≤ 300 The input limitations for getting 50 points are: 1 ≤ n ≤ 2000 The input limitations for getting 100 points are: 1 ≤ n ≤ 105
|
Print exactly n - 1 lines: the k-th output line must contain the minimum number of moves needed to make the first k elements of the original sequence ai equal to zero.Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams, or the %I64d specifier.
|
Input: 41 0 1 2 | Output: 113
|
Easy
| 1 | 1,085 | 316 | 314 | 1 |
|
2,027 |
E1
|
2027E1
|
E1. Bit Game (Easy Version)
| 2,800 |
bitmasks; brute force; games; math
|
This is the easy version of this problem. The only difference is that you need to output the winner of the game in this version, and the number of stones in each pile are fixed. You must solve both versions to be able to hack.Alice and Bob are playing a familiar game where they take turns removing stones from \(n\) piles. Initially, there are \(x_i\) stones in the \(i\)-th pile, and it has an associated value \(a_i\). A player can take \(d\) stones away from the \(i\)-th pile if and only if both of the following conditions are met: \(1 \le d \le a_i\), and \(x \, \& \, d = d\), where \(x\) is the current number of stones in the \(i\)-th pile and \(\&\) denotes the bitwise AND operation. The player who cannot make a move loses, and Alice goes first.You're given the \(a_i\) and \(x_i\) values for each pile, please determine who will win the game if both players play optimally.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 1000\)). The description of the test cases follows.The first line of each test case contains \(n\) (\(1 \le n \le 10^4\)) — the number of piles.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i < 2^{30}\)).The third line of each test case contains \(n\) integers \(x_1, x_2, \ldots, x_n\) (\(1 \le x_i < 2^{30}\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^4\).
|
Print a single line with the winner's name. If Alice wins, print ""Alice"", otherwise print ""Bob"" (without quotes).
|
In the first test case, neither player can take any stones from the first pile since there is no value of \(d\) satisfying the conditions. For the second pile, to begin with, Alice can remove between \(1\) and \(6\) stones. No matter which move Alice performs, Bob can remove the rest of the stones on his turn. After Bob's move, there are no more moves that Alice can perform, so Bob wins.In the second test case, here is one example of how the game might go. Alice moves first, and she decides to remove from the first pile. She cannot take \(17\) stones, because \(17 > 10\), which fails the first condition. She cannot take \(10\) stones, because \(25 \, \& \, 10 = 8\) which fails the second condition. One option is to take \(9\) stones; now the pile has \(16\) stones left. On Bob's turn he decides to take stones from the second pile; the only option here is to take all \(4\). Now, no more stones can be taken from either of the first two piles, so Alice must take some stones from the last pile. She decides to take \(12\) stones, and Bob then follows by taking the last \(2\) stones on that pile. Since Alice now has no legal moves left, Bob wins. It can be shown that no matter which strategy Alice follows, Bob will always be able to win if he plays optimally.
|
Input: 721 610 7310 8 1525 4 1448 32 65 647 45 126 94320 40 123 55 1512345 9876 86419 8641 16789 54321 7532 97532 1220 6444 61357 109 5569 90 85 | Output: Bob Bob Bob Bob Bob Alice Alice
|
Master
| 4 | 887 | 555 | 117 | 20 |
1,421 |
E
|
1421E
|
E. Swedish Heroes
| 2,700 |
brute force; dp; implementation
|
While playing yet another strategy game, Mans has recruited \(n\) Swedish heroes, whose powers which can be represented as an array \(a\).Unfortunately, not all of those mighty heroes were created as capable as he wanted, so that he decided to do something about it. In order to accomplish his goal, he can pick two consecutive heroes, with powers \(a_i\) and \(a_{i+1}\), remove them and insert a hero with power \(-(a_i+a_{i+1})\) back in the same position. For example if the array contains the elements \([5, 6, 7, 8]\), he can pick \(6\) and \(7\) and get \([5, -(6+7), 8] = [5, -13, 8]\).After he will perform this operation \(n-1\) times, Mans will end up having only one hero. He wants his power to be as big as possible. What's the largest possible power he can achieve?
|
The first line contains a single integer \(n\) (\(1 \le n \le 200000\)).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(-10^9 \le a_i \le 10^9\)) — powers of the heroes.
|
Print the largest possible power he can achieve after \(n-1\) operations.
|
Suitable list of operations for the first sample:\([5, 6, 7, 8] \rightarrow [-11, 7, 8] \rightarrow [-11, -15] \rightarrow [26]\)
|
Input: 4 5 6 7 8 | Output: 26
|
Master
| 3 | 779 | 190 | 73 | 14 |
1,003 |
A
|
1003A
|
A. Polycarp's Pockets
| 800 |
implementation
|
Polycarp has \(n\) coins, the value of the \(i\)-th coin is \(a_i\). Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.For example, if Polycarp has got six coins represented as an array \(a = [1, 2, 4, 3, 3, 2]\), he can distribute the coins into two pockets as follows: \([1, 2, 3], [2, 3, 4]\).Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that.
|
The first line of the input contains one integer \(n\) (\(1 \le n \le 100\)) — the number of coins.The second line of the input contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 100\)) — values of coins.
|
Print only one integer — the minimum number of pockets Polycarp needs to distribute all the coins so no two coins with the same value are put into the same pocket.
|
Input: 61 2 4 3 3 2 | Output: 2
|
Beginner
| 1 | 483 | 219 | 163 | 10 |
|
926 |
G
|
926G
|
G. Large Bouquets
| 1,500 |
A flower shop has got n bouquets, and the i-th bouquet consists of ai flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets. Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet.Determine the maximum possible number of large bouquets Vasya can make.
|
The first line contains a single positive integer n (1 ≤ n ≤ 105) — the number of initial bouquets.The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the number of flowers in each of the initial bouquets.
|
Print the maximum number of large bouquets Vasya can make.
|
In the first example Vasya can make 2 large bouquets. For example, the first bouquet can contain the first and the fifth initial bouquets (the total number of flowers is then equal to 9), and the second bouquet can consist of the second and the third initial bouquets (the total number of flowers is then equal to 7). The fourth initial bouquet is unused in this scheme. In the second example it is not possible to form a single bouquet with odd number of flowers.In the third example Vasya can make one large bouquet. For example, he can make it using all three initial bouquets. The size of the large bouquet is then equal to 11 + 4 + 10 = 25.
|
Input: 52 3 4 2 7 | Output: 2
|
Medium
| 0 | 587 | 234 | 58 | 9 |
|
471 |
B
|
471B
|
B. MUH and Important Things
| 1,300 |
implementation; sortings
|
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
|
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
|
In the first line print ""YES"" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line ""NO"" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.If there are multiple possible answers, you can print any of them.
|
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks.
|
Input: 41 3 3 1 | Output: YES1 4 2 3 4 1 2 3 4 1 3 2
|
Easy
| 2 | 945 | 247 | 504 | 4 |
1,297 |
G
|
1297G
|
G. M-numbers
| 0 |
*special; dp; math
|
For a given positive integer \(m\), a positive number is called a \(m\)-number if the product of its digits is \(m\). For example, the beginning of a series of \(24\)-numbers are as follows: \(38\), \(46\), \(64\), \(83\), \(138\), \(146\), \(164\), \(183\), \(226\) ...You are given a positive integer \(m\) and \(k\). Print \(k\)-th among \(m\)-numbers if all \(m\)-numbers are sorted in ascending order.
|
A single line of input contains two integers \(m\) and \(k\) (\(2 \le m \le 10^9\), \(1 \le k \le 10^9\)).
|
Print the desired number — \(k\)-th among all \(m\)-numbers if \(m\)-numbers are sorted in ascending order. If the answer does not exist, print -1.
|
Input: 24 9 | Output: 226
|
Beginner
| 3 | 406 | 106 | 147 | 12 |
|
1,081 |
B
|
1081B
|
B. Farewell Party
| 1,500 |
constructive algorithms; implementation
|
Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.Chouti remembered that \(n\) persons took part in that party. To make the party funnier, each person wore one hat among \(n\) kinds of weird hats numbered \(1, 2, \ldots n\). It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.After the party, the \(i\)-th person said that there were \(a_i\) persons wearing a hat differing from his own.It has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let \(b_i\) be the number of hat type the \(i\)-th person was wearing, Chouti wants you to find any possible \(b_1, b_2, \ldots, b_n\) that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.
|
The first line contains a single integer \(n\) (\(1 \le n \le 10^5\)), the number of persons in the party.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le n-1\)), the statements of people.
|
If there is no solution, print a single line ""Impossible"".Otherwise, print ""Possible"" and then \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(1 \le b_i \le n\)).If there are multiple answers, print any of them.
|
In the answer to the first example, all hats are the same, so every person will say that there were no persons wearing a hat different from kind \(1\).In the answer to the second example, the first and the second person wore the hat with type \(1\) and all other wore a hat of type \(2\).So the first two persons will say there were three persons with hats differing from their own. Similarly, three last persons will say there were two persons wearing a hat different from their own.In the third example, it can be shown that no solution exists.In the first and the second example, other possible configurations are possible.
|
Input: 30 0 0 | Output: Possible1 1 1
|
Medium
| 2 | 954 | 222 | 211 | 10 |
1,915 |
D
|
1915D
|
D. Unnatural Language Processing
| 900 |
greedy; implementation; strings
|
Lura was bored and decided to make a simple language using the five letters \(\texttt{a}\), \(\texttt{b}\), \(\texttt{c}\), \(\texttt{d}\), \(\texttt{e}\). There are two types of letters: vowels — the letters \(\texttt{a}\) and \(\texttt{e}\). They are represented by \(\textsf{V}\). consonants — the letters \(\texttt{b}\), \(\texttt{c}\), and \(\texttt{d}\). They are represented by \(\textsf{C}\). There are two types of syllables in the language: \(\textsf{CV}\) (consonant followed by vowel) or \(\textsf{CVC}\) (vowel with consonant before and after). For example, \(\texttt{ba}\), \(\texttt{ced}\), \(\texttt{bab}\) are syllables, but \(\texttt{aa}\), \(\texttt{eda}\), \(\texttt{baba}\) are not.A word in the language is a sequence of syllables. Lura has written a word in the language, but she doesn't know how to split it into syllables. Help her break the word into syllables.For example, given the word \(\texttt{bacedbab}\), it would be split into syllables as \(\texttt{ba.ced.bab}\) (the dot \(\texttt{.}\) represents a syllable boundary).
|
The input consists of multiple test cases. The first line contains an integer \(t\) (\(1 \leq t \leq 100\)) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 2 \cdot 10^5\)) — the length of the word.The second line of each test case contains a string consisting of \(n\) lowercase Latin characters — the word. All words given are valid words in the language; that is, they only use the letters \(\texttt{a}\), \(\texttt{b}\), \(\texttt{c}\), \(\texttt{d}\), \(\texttt{e}\), and each word is made up of several syllables.The sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For test case, output a string denoting the word split into syllables by inserting a dot \(\texttt{.}\) between every pair of adjacent syllables.If there are multiple possible splittings, output any of them. The input is given in such a way that at least one possible splitting exists.
|
Input: 68bacedbab4baba13daddecabeddad3dac6dacdac22dababbabababbabbababba | Output: ba.ced.bab ba.ba dad.de.ca.bed.dad dac dac.dac da.bab.ba.ba.bab.bab.ba.bab.ba
|
Beginner
| 3 | 1,054 | 686 | 285 | 19 |
|
1,713 |
A
|
1713A
|
A. Traveling Salesman Problem
| 800 |
geometry; greedy; implementation
|
You are living on an infinite plane with the Cartesian coordinate system on it. In one move you can go to any of the four adjacent points (left, right, up, down).More formally, if you are standing at the point \((x, y)\), you can: go left, and move to \((x - 1, y)\), or go right, and move to \((x + 1, y)\), or go up, and move to \((x, y + 1)\), or go down, and move to \((x, y - 1)\). There are \(n\) boxes on this plane. The \(i\)-th box has coordinates \((x_i,y_i)\). It is guaranteed that the boxes are either on the \(x\)-axis or the \(y\)-axis. That is, either \(x_i=0\) or \(y_i=0\).You can collect a box if you and the box are at the same point. Find the minimum number of moves you have to perform to collect all of these boxes if you have to start and finish at the point \((0,0)\).
|
The first line contains a single integer \(t\) (\(1 \le t \le 100\)) — the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 100\)) — the number of boxes.The \(i\)-th line of the following \(n\) lines contains two integers \(x_i\) and \(y_i\) (\(-100 \le x_i, y_i \le 100\)) — the coordinate of the \(i\)-th box. It is guaranteed that either \(x_i=0\) or \(y_i=0\).Do note that the sum of \(n\) over all test cases is not bounded.
|
For each test case output a single integer — the minimum number of moves required.
|
In the first test case, a possible sequence of moves that uses the minimum number of moves required is shown below. $$$\((0,0) \to (1,0) \to (1,1) \to (1, 2) \to (0,2) \to (-1,2) \to (-1,1) \to (-1,0) \to (-1,-1) \to (-1,-2) \to (0,-2) \to (0,-1) \to (0,0)\)\( In the second test case, a possible sequence of moves that uses the minimum number of moves required is shown below. \)\((0,0) \to (0,1) \to (0,2) \to (-1, 2) \to (-2,2) \to (-3,2) \to (-3,1) \to (-3,0) \to (-3,-1) \to (-2,-1) \to (-1,-1) \to (0,-1) \to (0,0)\)$$$ In the third test case, we can collect all boxes without making any moves.
|
Input: 340 -21 0-1 00 230 2-3 00 -110 0 | Output: 12 12 0
|
Beginner
| 3 | 793 | 481 | 82 | 17 |
832 |
A
|
832A
|
A. Sasha and Sticks
| 800 |
games; math
|
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players take turns crossing out exactly k sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than k sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.
|
The first line contains two integers n and k (1 ≤ n, k ≤ 1018, k ≤ n) — the number of sticks drawn by Sasha and the number k — the number of sticks to be crossed out on each turn.
|
If Sasha wins, print ""YES"" (without quotes), otherwise print ""NO"" (without quotes).You can print each letter in arbitrary case (upper of lower).
|
In the first example Sasha crosses out 1 stick, and then there are no sticks. So Lena can't make a move, and Sasha wins.In the second example Sasha crosses out 4 sticks, then Lena crosses out 4 sticks, and after that there are only 2 sticks left. Sasha can't make a move. The players make equal number of moves, so Sasha doesn't win.
|
Input: 1 1 | Output: YES
|
Beginner
| 2 | 659 | 179 | 148 | 8 |
1,804 |
E
|
1804E
|
E. Routing
| 2,400 |
bitmasks; brute force; dfs and similar; dp; graphs
|
Ada operates a network that consists of \(n\) servers and \(m\) direct connections between them. Each direct connection between a pair of distinct servers allows bidirectional transmission of information between these two servers. Ada knows that these \(m\) direct connections allow to directly or indirectly transmit information between any two servers in this network. We say that server \(v\) is a neighbor of server \(u\) if there exists a direct connection between these two servers.Ada needs to configure her network's WRP (Weird Routing Protocol). For each server \(u\) she needs to select exactly one of its neighbors as an auxiliary server \(a(u)\). After all \(a(u)\) are set, routing works as follows. Suppose server \(u\) wants to find a path to server \(v\) (different from \(u\)). Server \(u\) checks all of its direct connections to other servers. If it sees a direct connection with server \(v\), it knows the path and the process terminates. If the path was not found at the first step, server \(u\) asks its auxiliary server \(a(u)\) to find the path. Auxiliary server \(a(u)\) follows this process starting from the first step. After \(a(u)\) finds the path, it returns it to \(u\). Then server \(u\) constructs the resulting path as the direct connection between \(u\) and \(a(u)\) plus the path from \(a(u)\) to \(v\). As you can see, this procedure either produces a correct path and finishes or keeps running forever. Thus, it is critically important for Ada to configure her network's WRP properly.Your goal is to assign an auxiliary server \(a(u)\) for each server \(u\) in the given network. Your assignment should make it possible to construct a path from any server \(u\) to any other server \(v\) using the aforementioned procedure. Or you should report that such an assignment doesn't exist.
|
The first line of the input contains two integers \(n\) and \(m\) (\(2 \leq n \leq 20\), \(n - 1 \leq m \leq \frac{n \cdot (n - 1)}{2}\)) — the number of servers and the number of direct connections in the given network.Then follow \(m\) lines containing two integers \(u_i\) and \(v_i\) (\(1 \leq u_i, v_i \leq n\), \(u_i \ne v_i\)) each, the \(i\)-th line describes the \(i\)-th direct connection.It is guaranteed that there is no more than one direct connection between any two servers. It is guaranteed that there is a direct or indirect route (consisting only of the given direct connections) between any two servers.
|
If there is no way to assign an auxiliary server \(a(u)\) for each server \(u\) in such a way that WRP will be able to find a path from any server \(u\) to any other server \(v\), print ""No"" in the only line of the output.Otherwise, print ""Yes"" in the first line of the output. In the second line of the output print \(n\) integers, the \(i\)-th of these integers should be equal to \(a(i)\) – the index of the auxiliary server for server \(i\). Do not forget that there must be a direct connection between server \(i\) and server \(a(i)\).You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
|
Input: 6 7 1 2 2 3 3 1 4 5 5 6 4 6 2 5 | Output: Yes 2 5 2 5 2 5
|
Expert
| 5 | 1,821 | 622 | 705 | 18 |
|
1,783 |
B
|
1783B
|
B. Matrix of Differences
| 1,100 |
constructive algorithms; math
|
For a square matrix of integers of size \(n \times n\), let's define its beauty as follows: for each pair of side-adjacent elements \(x\) and \(y\), write out the number \(|x-y|\), and then find the number of different numbers among them.For example, for the matrix \(\begin{pmatrix} 1 & 3\\ 4 & 2 \end{pmatrix}\) the numbers we consider are \(|1-3|=2\), \(|1-4|=3\), \(|3-2|=1\) and \(|4-2|=2\); there are \(3\) different numbers among them (\(2\), \(3\) and \(1\)), which means that its beauty is equal to \(3\).You are given an integer \(n\). You have to find a matrix of size \(n \times n\), where each integer from \(1\) to \(n^2\) occurs exactly once, such that its beauty is the maximum possible among all such matrices.
|
The first line contains a single integer \(t\) (\(1 \le t \le 49\)) – the number of test cases.The first (and only) line of each test case contains a single integer \(n\) (\(2 \le n \le 50\)).
|
For each test case, print \(n\) rows of \(n\) integers — a matrix of integers of size \(n \times n\), where each number from \(1\) to \(n^2\) occurs exactly once, such that its beauty is the maximum possible among all such matrices. If there are multiple answers, print any of them.
|
Input: 223 | Output: 1 3 4 2 1 3 4 9 2 7 5 8 6
|
Easy
| 2 | 727 | 192 | 282 | 17 |
|
2,041 |
B
|
2041B
|
B. Bowling Frame
| 1,200 |
binary search; brute force; math
|
Bowling is a national sport in Taiwan; everyone in the country plays the sport on a daily basis since their youth. Naturally, there are a lot of bowling alleys all over the country, and the competition between them is as intense as you can imagine.Maw-Shang owns one such bowling alley. To stand out from other competitors in the industry and draw attention from customers, he decided to hold a special event every month that features various unorthodox bowling rules. For the event this month, he came up with a new version of the game called X-pin bowling. In the traditional \(10\)-pin bowling game, a frame is built out of ten bowling pins forming a triangular shape of side length four. The pin closest to the player forms the first row, and the two pins behind it form the second row, and so on. Unlike the standard version, the game of \(X\)-pin bowling Maw-Shang designed allows a much larger number of pins that form a larger frame. The following figure shows a standard \(10\)-pin frame on the left, and on the right it shows a \(21\)-pin frame that forms a triangular shape of side length six which is allowed in the game of \(X\)-pin bowling. Being the national sport, the government of Taiwan strictly regulates and standardizes the manufacturing of bowling pins. There are two types of bowling pins allowed, one in black and the other in white, and the bowling alley Maw-Shang owns has \(w\) white pins and \(b\) black pins. To make this new game exciting for the customers, Maw-Shang wants to build the largest possible frame from these \(w+b\) pins. However, even though he is okay with using both colors in building the frame, for aesthetic reasons, Maw-Shang still wants the colors of the pins on the same row to be identical. For example, the following figure shows two possible frames of side length six, but only the left one is acceptable to Maw-Shang since the other one has white and black pins mixed in the third row. The monthly special event is happening in just a few hours. Please help Maw-Shang calculate the side length of the largest frame that he can build from his \(w+b\) pins!
|
The first line of the input contains a single integer \(t\), the number of test cases. Each of the following \(t\) lines contains two integers \(w\) and \(b\), the number of white and black pins, respectively. \(1 \leq t \leq 100\) \(0 \leq w, b \leq 10^9\)
|
For each test case, output in a single line the side length \(k\) of the largest pin satisfying Maw-Shang's requirement you can build with the given pins.
|
Input: 41 23 23 312 0 | Output: 2 2 3 4
|
Easy
| 3 | 2,112 | 257 | 154 | 20 |
|
1,665 |
B
|
1665B
|
B. Array Cloning Technique
| 900 |
constructive algorithms; greedy; sortings
|
You are given an array \(a\) of \(n\) integers. Initially there is only one copy of the given array.You can do operations of two types: Choose any array and clone it. After that there is one more copy of the chosen array. Swap two elements from any two copies (maybe in the same copy) on any positions. You need to find the minimal number of operations needed to obtain a copy where all elements are equal.
|
The input consists of 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 a single integer \(n\) (\(1 \le n \le 10^5\)) — the length of the array \(a\).The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(-10^9 \le a_i \le 10^9\)) — the elements of the array \(a\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
|
For each test case output a single integer — the minimal number of operations needed to create at least one copy where all elements are equal.
|
In the first test case all elements in the array are already equal, that's why the answer is \(0\).In the second test case it is possible to create a copy of the given array. After that there will be two identical arrays:\([ \ 0 \ 1 \ 3 \ 3 \ 7 \ 0 \ ]\) and \([ \ 0 \ 1 \ 3 \ 3 \ 7 \ 0 \ ]\)After that we can swap elements in a way so all zeroes are in one array:\([ \ 0 \ \underline{0} \ \underline{0} \ 3 \ 7 \ 0 \ ]\) and \([ \ \underline{1} \ 1 \ 3 \ 3 \ 7 \ \underline{3} \ ]\)Now let's create a copy of the first array:\([ \ 0 \ 0 \ 0 \ 3 \ 7 \ 0 \ ]\), \([ \ 0 \ 0 \ 0 \ 3 \ 7 \ 0 \ ]\) and \([ \ 1 \ 1 \ 3 \ 3 \ 7 \ 3 \ ]\)Let's swap elements in the first two copies:\([ \ 0 \ 0 \ 0 \ \underline{0} \ \underline{0} \ 0 \ ]\), \([ \ \underline{3} \ \underline{7} \ 0 \ 3 \ 7 \ 0 \ ]\) and \([ \ 1 \ 1 \ 3 \ 3 \ 7 \ 3 \ ]\).Finally, we made a copy where all elements are equal and made \(6\) operations.It can be proven that no fewer operations are enough.
|
Input: 61178960 1 3 3 7 02-1000000000 100000000044 3 2 152 5 7 6 371 1 1 1 1 1 1 | Output: 0 6 2 5 7 0
|
Beginner
| 3 | 406 | 530 | 142 | 16 |
1,167 |
F
|
1167F
|
F. Scalar Queries
| 2,300 |
combinatorics; data structures; math; sortings
|
You are given an array \(a_1, a_2, \dots, a_n\). All \(a_i\) are pairwise distinct.Let's define function \(f(l, r)\) as follows: let's define array \(b_1, b_2, \dots, b_{r - l + 1}\), where \(b_i = a_{l - 1 + i}\); sort array \(b\) in increasing order; result of the function \(f(l, r)\) is \(\sum\limits_{i = 1}^{r - l + 1}{b_i \cdot i}\). Calculate \(\left(\sum\limits_{1 \le l \le r \le n}{f(l, r)}\right) \mod (10^9+7)\), i.e. total sum of \(f\) for all subsegments of \(a\) modulo \(10^9+7\).
|
The first line contains one integer \(n\) (\(1 \le n \le 5 \cdot 10^5\)) — the length of array \(a\).The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\), \(a_i \neq a_j\) for \(i \neq j\)) — array \(a\).
|
Print one integer — the total sum of \(f\) for all subsegments of \(a\) modulo \(10^9+7\)
|
Description of the first example: \(f(1, 1) = 5 \cdot 1 = 5\); \(f(1, 2) = 2 \cdot 1 + 5 \cdot 2 = 12\); \(f(1, 3) = 2 \cdot 1 + 4 \cdot 2 + 5 \cdot 3 = 25\); \(f(1, 4) = 2 \cdot 1 + 4 \cdot 2 + 5 \cdot 3 + 7 \cdot 4 = 53\); \(f(2, 2) = 2 \cdot 1 = 2\); \(f(2, 3) = 2 \cdot 1 + 4 \cdot 2 = 10\); \(f(2, 4) = 2 \cdot 1 + 4 \cdot 2 + 7 \cdot 3 = 31\); \(f(3, 3) = 4 \cdot 1 = 4\); \(f(3, 4) = 4 \cdot 1 + 7 \cdot 2 = 18\); \(f(4, 4) = 7 \cdot 1 = 7\);
|
Input: 4 5 2 4 7 | Output: 167
|
Expert
| 4 | 497 | 240 | 89 | 11 |
702 |
D
|
702D
|
D. Road to Post Office
| 1,900 |
math
|
Vasiliy has a car and he wants to get from home to the post office. The distance which he needs to pass equals to d kilometers.Vasiliy's car is not new — it breaks after driven every k kilometers and Vasiliy needs t seconds to repair it. After repairing his car Vasiliy can drive again (but after k kilometers it will break again, and so on). In the beginning of the trip the car is just from repair station.To drive one kilometer on car Vasiliy spends a seconds, to walk one kilometer on foot he needs b seconds (a < b).Your task is to find minimal time after which Vasiliy will be able to reach the post office. Consider that in every moment of time Vasiliy can left his car and start to go on foot.
|
The first line contains 5 positive integers d, k, a, b, t (1 ≤ d ≤ 1012; 1 ≤ k, a, b, t ≤ 106; a < b), where: d — the distance from home to the post office; k — the distance, which car is able to drive before breaking; a — the time, which Vasiliy spends to drive 1 kilometer on his car; b — the time, which Vasiliy spends to walk 1 kilometer on foot; t — the time, which Vasiliy spends to repair his car.
|
Print the minimal time after which Vasiliy will be able to reach the post office.
|
In the first example Vasiliy needs to drive the first 2 kilometers on the car (in 2 seconds) and then to walk on foot 3 kilometers (in 12 seconds). So the answer equals to 14 seconds.In the second example Vasiliy needs to drive the first 2 kilometers on the car (in 2 seconds), then repair his car (in 5 seconds) and drive 2 kilometers more on the car (in 2 seconds). After that he needs to walk on foot 1 kilometer (in 4 seconds). So the answer equals to 13 seconds.
|
Input: 5 2 1 4 10 | Output: 14
|
Hard
| 1 | 701 | 404 | 81 | 7 |
49 |
C
|
49C
|
C. Disposition
| 1,700 |
constructive algorithms; math
|
Vasya bought the collected works of a well-known Berland poet Petya in n volumes. The volumes are numbered from 1 to n. He thinks that it does not do to arrange the book simply according to their order. Vasya wants to minimize the number of the disposition’s divisors — the positive integers i such that for at least one j (1 ≤ j ≤ n) is true both: j mod i = 0 and at the same time p(j) mod i = 0, where p(j) is the number of the tome that stands on the j-th place and mod is the operation of taking the division remainder. Naturally, one volume can occupy exactly one place and in one place can stand exactly one volume.Help Vasya — find the volume disposition with the minimum number of divisors.
|
The first line contains number n (1 ≤ n ≤ 100000) which represents the number of volumes and free places.
|
Print n numbers — the sought disposition with the minimum divisor number. The j-th number (1 ≤ j ≤ n) should be equal to p(j) — the number of tome that stands on the j-th place. If there are several solutions, print any of them.
|
Input: 2 | Output: 2 1
|
Medium
| 2 | 698 | 105 | 228 | 0 |
|
1,204 |
C
|
1204C
|
C. Anna, Svyatoslav and Maps
| 1,700 |
dp; graphs; greedy; shortest paths
|
The main characters have been omitted to be short.You are given a directed unweighted graph without loops with \(n\) vertexes and a path in it (that path is not necessary simple) given by a sequence \(p_1, p_2, \ldots, p_m\) of \(m\) vertexes; for each \(1 \leq i < m\) there is an arc from \(p_i\) to \(p_{i+1}\).Define the sequence \(v_1, v_2, \ldots, v_k\) of \(k\) vertexes as good, if \(v\) is a subsequence of \(p\), \(v_1 = p_1\), \(v_k = p_m\), and \(p\) is one of the shortest paths passing through the vertexes \(v_1\), \(\ldots\), \(v_k\) in that order.A sequence \(a\) is a subsequence of a sequence \(b\) if \(a\) can be obtained from \(b\) by deletion of several (possibly, zero or all) elements. It is obvious that the sequence \(p\) is good but your task is to find the shortest good subsequence.If there are multiple shortest good subsequences, output any of them.
|
The first line contains a single integer \(n\) (\(2 \le n \le 100\)) — the number of vertexes in a graph. The next \(n\) lines define the graph by an adjacency matrix: the \(j\)-th character in the \(i\)-st line is equal to \(1\) if there is an arc from vertex \(i\) to the vertex \(j\) else it is equal to \(0\). It is guaranteed that the graph doesn't contain loops.The next line contains a single integer \(m\) (\(2 \le m \le 10^6\)) — the number of vertexes in the path. The next line contains \(m\) integers \(p_1, p_2, \ldots, p_m\) (\(1 \le p_i \le n\)) — the sequence of vertexes in the path. It is guaranteed that for any \(1 \leq i < m\) there is an arc from \(p_i\) to \(p_{i+1}\).
|
In the first line output a single integer \(k\) (\(2 \leq k \leq m\)) — the length of the shortest good subsequence. In the second line output \(k\) integers \(v_1\), \(\ldots\), \(v_k\) (\(1 \leq v_i \leq n\)) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.
|
Below you can see the graph from the first example:The given path is passing through vertexes \(1\), \(2\), \(3\), \(4\). The sequence \(1-2-4\) is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes \(1\), \(2\) and \(4\) in that order is \(1-2-3-4\). Note that subsequences \(1-4\) and \(1-3-4\) aren't good because in both cases the shortest path passing through the vertexes of these sequences is \(1-3-4\).In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.In the fourth example, the paths \(1-2-4\) and \(1-3-4\) are the shortest paths passing through the vertexes \(1\) and \(4\).
|
Input: 4 0110 0010 0001 1000 4 1 2 3 4 | Output: 3 1 2 4
|
Medium
| 4 | 881 | 692 | 349 | 12 |
219 |
B
|
219B
|
B. Special Offer! Super Price 999 Bourles!
| 1,400 |
implementation
|
Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors.Polycaprus calculated that the optimal celling price for such scissors would be p bourles. However, he read somewhere that customers are attracted by prices that say something like ""Special Offer! Super price 999 bourles!"". So Polycarpus decided to lower the price a little if it leads to the desired effect.Polycarpus agrees to lower the price by no more than d bourles so that the number of nines at the end of the resulting price is maximum. If there are several ways to do it, he chooses the maximum possible price.Note, Polycarpus counts only the trailing nines in a price.
|
The first line contains two integers p and d (1 ≤ p ≤ 1018; 0 ≤ d < p) — the initial price of scissors and the maximum possible price reduction.Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
|
Print the required price — the maximum price that ends with the largest number of nines and that is less than p by no more than d.The required number shouldn't have leading zeroes.
|
Input: 1029 102 | Output: 999
|
Easy
| 1 | 796 | 287 | 180 | 2 |
|
1,530 |
G
|
1530G
|
G. What a Reversal
| 3,300 |
constructive algorithms
|
You have two strings \(a\) and \(b\) of equal length \(n\) consisting of characters 0 and 1, and an integer \(k\).You need to make strings \(a\) and \(b\) equal.In one step, you can choose any substring of \(a\) containing exactly \(k\) characters 1 (and arbitrary number of characters 0) and reverse it. Formally, if \(a = a_1 a_2 \ldots a_n\), you can choose any integers \(l\) and \(r\) (\(1 \le l \le r \le n\)) such that there are exactly \(k\) ones among characters \(a_l, a_{l+1}, \ldots, a_r\), and set \(a\) to \(a_1 a_2 \ldots a_{l-1} a_r a_{r-1} \ldots a_l a_{r+1} a_{r+2} \ldots a_n\).Find a way to make \(a\) equal to \(b\) using at most \(4n\) reversals of the above kind, or determine that such a way doesn't exist. The number of reversals doesn't have to be minimized.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 2000\)). Description of the test cases follows.Each test case consists of three lines. The first line of each test case contains two integers \(n\) and \(k\) (\(1 \le n \le 2000\); \(0 \le k \le n\)).The second line contains string \(a\) of length \(n\).The third line contains string \(b\) of the same length. Both strings consist of characters 0 and 1.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2000\).
|
For each test case, if it's impossible to make \(a\) equal to \(b\) in at most \(4n\) reversals, print a single integer \(-1\).Otherwise, print an integer \(m\) (\(0 \le m \le 4n\)), denoting the number of reversals in your sequence of steps, followed by \(m\) pairs of integers \(l_i, r_i\) (\(1 \le l_i \le r_i \le n\)), denoting the boundaries of the substrings of \(a\) to be reversed, in chronological order. Each substring must contain exactly \(k\) ones at the moment of reversal.Note that \(m\) doesn't have to be minimized. If there are multiple answers, print any.
|
In the first test case, after the first reversal \(a = \) 011010, after the second reversal \(a = \) 010110, after the third reversal \(a = \) 010101.
|
Input: 6 6 1 101010 010101 6 3 101010 010101 6 0 101010 010101 6 6 101010 010101 4 2 0000 1111 9 2 011100101 101001011 | Output: 3 1 2 3 4 5 6 1 1 6 -1 -1 -1 5 4 8 8 9 3 6 1 4 3 6
|
Master
| 1 | 784 | 548 | 574 | 15 |
1,438 |
F
|
1438F
|
F. Olha and Igor
| 3,000 |
interactive; probabilities; trees
|
This is an interactive problem.Igor wants to find the key to Olha's heart. The problem is, that it's at the root of a binary tree.There is a perfect binary tree of height \(h\) consisting of \(n = 2^{h} - 1\) nodes. The nodes have been assigned distinct labels from \(1\) to \(n\). However, Igor only knows \(h\) and does not know which label corresponds to which node. To find key to Olha's heart he needs to find the label assigned to the root by making queries of the following type at most \(n+420\) times: Select three distinct labels \(u\), \(v\) and \(w\) (\(1 \leq u,v,w \leq n\)). In response, Olha (the grader) will tell him the label of the lowest common ancestor of nodes labelled \(u\) and \(v\), if the tree was rooted at the node labelled \(w\) instead. Help Igor to find the root!Note: the grader is not adaptive: the labels are fixed before any queries are made.
|
The first and only line contains a single integer \(h\) (\(3 \le h \le 18\)) — the height of the tree.
|
The labels corresponding to the tree in the example are [\(4\),\(7\),\(2\),\(6\),\(1\),\(5\),\(3\)], meaning the root is labelled \(4\), and for \(1 < i \le n\), the parent of \(p_i\) is \(p_{ \lfloor{\frac{i}{2}}\rfloor }\).
|
Input: 3 2 7 4 | Output: ? 7 3 5 ? 1 6 4 ? 1 5 4 ! 4
|
Master
| 3 | 879 | 102 | 0 | 14 |
|
2,085 |
D
|
2085D
|
D. Serval and Kaitenzushi Buffet
| 2,000 |
data structures; graph matchings; greedy
|
Serval has just found a Kaitenzushi buffet restaurant. Kaitenzushi means that there is a conveyor belt in the restaurant, delivering plates of sushi in front of the customer, Serval.In this restaurant, each plate contains exactly \(k\) pieces of sushi and the \(i\)-th plate has a deliciousness \(d_i\). Serval will have a meal in this restaurant for \(n\) minutes, and within the \(n\) minutes, he must eat up all the pieces of sushi he took from the belt.Denote the counter for uneaten taken pieces of sushi as \(r\). Initially, \(r=0\). In the \(i\)-th minute (\(1\leq i\leq n\)), only the \(i\)-th plate of sushi will be delivered in front of Serval, and he can do one of the following: Take the \(i\)-th plate of sushi (whose deliciousness is \(d_i\)) from the belt, and \(r\) will be increased by \(k\); Eat one uneaten piece of sushi that he took from the belt before, and \(r\) will be decreased by \(1\). Note that you can do this only if \(r>0\); Or, do nothing, and \(r\) will remain unchanged. Note that after the \(n\) minutes, the value of \(r\) must be \(0\).Serval wants to maximize the sum of the deliciousnesses of all the plates he took. Help him find it out!
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The first line of each test case contains two integers \(n\) and \(k\) (\(1\leq k<n\leq 2\cdot 10^5\)) — the number of minutes of the meal and the number of sushi pieces in each plate.The second line contains \(n\) integers \(d_1, d_2, \ldots, d_n\) (\(1\leq d_i\leq 10^9\)) — the deliciousness of each plate.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot 10^5\).
|
For each test case, print a single integer — the maximum possible sum of the deliciousnesses of all the plates Serval took.
|
In the first test case, it can be shown that Serval can eat up at most one plate of sushi. Since the second plate of sushi has the greatest deliciousness \(6\) among all the plates, he will take it from the belt in the second minute, and then eat it up in the following \(2\) minutes. Minute\(1\)\(2\)\(3\)\(4\)\(5\)Action — TakeEatEat — \(r\) after action\(0\)\(2\)\(1\)\(0\)\(0\)Deliciousnesses gained\(0\)\(6\)\(6\)\(6\)\(6\) In the second test case, it can be shown that it is optimal for Serval to eat up the first, third, and sixth plates of sushi. The sum of the deliciousnesses of these plates is \(3 + 4 + 9 = 16\). Minute\(1\)\(2\)\(3\)\(4\)\(5\)\(6\)\(7\)ActionTakeEatTakeEat — TakeEat\(r\) after action\(1\)\(0\)\(1\)\(0\)\(0\)\(1\)\(0\)Deliciousnesses gained\(3\)\(3\)\(7\)\(7\)\(7\)\(16\)\(16\)
|
Input: 55 23 6 4 1 27 13 1 4 1 5 9 24 34 3 2 16 21 3 5 2 4 66 11000000000 1 1000000000 1 1000000000 1 | Output: 6 16 4 6 3000000000
|
Hard
| 3 | 1,178 | 562 | 123 | 20 |
1,713 |
F
|
1713F
|
F. Lost Array
| 2,900 |
bitmasks; combinatorics; constructive algorithms; dp; math
|
My orzlers, we can optimize this problem from \(O(S^3)\) to \(O\left(T^\frac{5}{9}\right)\)!— Spyofgame, founder of Orzlim religionA long time ago, Spyofgame invented the famous array \(a\) (\(1\)-indexed) of length \(n\) that contains information about the world and life. After that, he decided to convert it into the matrix \(b\) (\(0\)-indexed) of size \((n + 1) \times (n + 1)\) which contains information about the world, life and beyond.Spyofgame converted \(a\) into \(b\) with the following rules. \(b_{i,0} = 0\) if \(0 \leq i \leq n\); \(b_{0,i} = a_{i}\) if \(1 \leq i \leq n\); \(b_{i,j} = b_{i,j-1} \oplus b_{i-1,j}\) if \(1 \leq i, j \leq n\). Here \(\oplus\) denotes the bitwise XOR operation.Today, archaeologists have discovered the famous matrix \(b\). However, many elements of the matrix has been lost. They only know the values of \(b_{i,n}\) for \(1 \leq i \leq n\) (note that these are some elements of the last column, not the last row).The archaeologists want to know what a possible array of \(a\) is. Can you help them reconstruct any array that could be \(a\)?
|
The first line contains a single integer \(n\) (\(1 \leq n \leq 5 \cdot 10^5\)).The second line contains \(n\) integers \(b_{1,n}, b_{2,n}, \ldots, b_{n,n}\) (\(0 \leq b_{i,n} < 2^{30}\)).
|
If some array \(a\) is consistent with the information, print a line containing \(n\) integers \(a_1, a_2, \ldots, a_n\). If there are multiple solutions, output any.If such an array does not exist, output \(-1\) instead.
|
If we let \(a = [1,2,3]\), then \(b\) will be: \(\bf{0}\)\(\bf{1}\)\(\bf{2}\)\(\bf{3}\)\(\bf{0}\)\(1\)\(3\)\(0\)\(\bf{0}\)\(1\)\(2\)\(2\)\(\bf{0}\)\(1\)\(3\)\(1\) The values of \(b_{1,n}, b_{2,n}, \ldots, b_{n,n}\) generated are \([0,2,1]\) which is consistent with what the archaeologists have discovered.
|
Input: 3 0 2 1 | Output: 1 2 3
|
Master
| 5 | 1,089 | 188 | 221 | 17 |
316 |
B2
|
316B2
|
B2. EKG
| 1,600 |
dfs and similar; dp
|
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the ""virtual"" link in this chain, wondering where this legendary figure has left.The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
|
The first line contains two integers n (1 ≤ n ≤ 103) and x (1 ≤ x ≤ n) — the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ n) — the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.The input limits for scoring 30 points are (subproblem B1): It is guaranteed that the number of zero elements ai doesn't exceed 20. The input limits for scoring 100 points are (subproblems B1+B2): The number of zero elements ai is arbitrary.
|
Print all possible positions of the Smart Beaver in the line in the increasing order.
|
Picture for the fourth test.
|
Input: 6 12 0 4 0 6 0 | Output: 246
|
Medium
| 2 | 2,407 | 821 | 85 | 3 |
2,097 |
C
|
2097C
|
C. Bermuda Triangle
| 2,400 |
chinese remainder theorem; geometry; implementation; math; number theory
|
The Bermuda Triangle — a mysterious area in the Atlantic Ocean where, according to rumors, ships and airplanes disappear without a trace. Some blame magnetic anomalies, others — portals to other worlds, but the truth remains hidden in a fog of mysteries.A regular passenger flight 814 was traveling from Miami to Nassau on a clear sunny day. Nothing foreshadowed trouble until the plane entered a zone of strange flickering fog. Radio communication was interrupted, the instruments spun wildly, and flashes of unearthly light flickered outside the windows.For simplicity, we will assume that the Bermuda Triangle and the airplane are on a plane, and the vertices of the triangle have coordinates \((0, 0)\), \((0, n)\), and \((n, 0)\). Initially, the airplane is located at the point \((x, y)\) strictly inside the Bermuda Triangle and is moving with a velocity vector \((v_x, v_y)\). All instruments have failed, so the crew cannot control the airplane.The airplane can escape from the triangle if it ever reaches exactly one of the vertices of the triangle. However, if at any moment (possibly non-integer) the airplane hits the boundary of the triangle (but not at a vertex), its velocity vector is immediately reflected relative to that side\(^\dagger\), and the airplane continues to move in the new direction.Determine whether the airplane can ever escape from the Bermuda Triangle (i.e., reach exactly one of its vertices). If this is possible, also calculate how many times before that moment the airplane will hit the boundary of the triangle (each touch of the boundary, even at the same point, counts; crossing a vertex does not count).\(^\dagger\) Reflection occurs according to the usual laws of physics. The angle of incidence equals the angle of reflection.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The only line of each test case contains five integers \(n\), \(x\), \(y\), \(v_x\), and \(v_y\) (\(3 \le n \le 10^9\), \(1 \le x, y\), \(x+y < n\), \(1 \le v_x, v_y \le 10^9\)) — numbers describing the vertices of the triangle, the initial coordinates of the airplane, and the initial velocity vector.
|
For each test case, output a single integer — the number of times the airplane will hit the boundary of the triangle before it escapes. If the airplane never escapes from the triangle, output \(-1\).
|
An illustration for the first test case is provided below: In the second test case, the answer is the same as in the first, as all initial data, except for the speed, are the same, but the airplanes are initially moving in the same direction.In the third test case, the answer is \(-1\), as the airplane will move exclusively along the segments marked in green. An illustration is provided below:
|
Input: 66 2 2 5 26 2 2 20 84 1 2 1 14 1 1 1 24 1 1 2 16 2 3 2 3 | Output: 2 2 -1 -1 -1 5
|
Expert
| 5 | 1,772 | 464 | 199 | 20 |
1,070 |
I
|
1070I
|
I. Privatization of Roads in Berland
| 2,400 |
flows; graph matchings; graphs
|
There are \(n\) cities and \(m\) two-way roads in Berland, each road connecting two distinct cities.Recently the Berland government has made a tough decision to transfer ownership of the roads to private companies. In total, there are \(100500\) private companies in Berland, numbered by integers from \(1\) to \(100500\). After the privatization, every road should belong to exactly one company.The anti-monopoly committee demands that after the privatization each company can own at most two roads. The urbanists of Berland also stated their opinion: each city should be adjacent to the roads owned by at most \(k\) companies.Help the government to distribute the roads between the companies so that both conditions are satisfied. That is, each company gets at most two roads, and each city has roads of at most \(k\) distinct companies adjacent to it.
|
Input contains one or several test cases. The first line contains an integer \(t\) (\(1 \le t \le 300\)) — the number of test cases in the input. Solve test cases separately, test cases are completely independent and do not affect each other.The following lines describe the test cases. Each case starts with a line consisting of three space-separated integers \(n\), \(m\) and \(k\) (\(2 \le n \le 600\), \(1 \le m \le 600\), \(1 \le k \le n - 1\)) — the number of cities, the number of roads and the maximum diversity of the roads adjacent to a city.Then \(m\) lines follow, each having a pair of space-separated integers \(a_i\), \(b_i\) (\(1 \le a_i, b_i \le n\); \(a_i \ne b_i\)). It means that the \(i\)-th road connects cities \(a_i\) and \(b_i\). All roads are two-way. There is at most one road between a pair of the cities.The sum of \(n\) values for all test cases doesn't exceed \(600\). The sum of \(m\) values for all test cases doesn't exceed \(600\).
|
Print \(t\) lines: the \(i\)-th line should contain the answer for the \(i\)-th test case. For a test case, print a sequence of integers \(c_1, c_2, \dots, c_m\) separated by space, where \(c_i\) (\(1 \le c_i \le 100500\)) is the company which owns the \(i\)-th road in your plan. If there are multiple solutions, output any of them. If there is no solution for a test case, print \(c_1=c_2=\ldots=c_m=0\).
|
Input: 33 3 21 22 33 14 5 21 21 31 42 32 44 6 21 21 31 42 32 43 4 | Output: 1 2 3 2 1 1 2 3 0 0 0 0 0 0
|
Expert
| 3 | 854 | 966 | 406 | 10 |
|
1,702 |
G1
|
1702G1
|
G1. Passable Paths (easy version)
| 1,900 |
dfs and similar; trees
|
This is an easy version of the problem. The only difference between an easy and a hard version is in the number of queries.Polycarp grew a tree from \(n\) vertices. We remind you that a tree of \(n\) vertices is an undirected connected graph of \(n\) vertices and \(n-1\) edges that does not contain cycles.He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).For example, for a tree below sets \(\{3, 2, 5\}\), \(\{1, 5, 4\}\), \(\{1, 4\}\) are passable, and \(\{1, 3, 5\}\), \(\{1, 2, 3, 4, 5\}\) are not. Polycarp asks you to answer \(q\) queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable.
|
The first line of input contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) — number of vertices.Following \(n - 1\) lines a description of the tree..Each line contains two integers \(u\) and \(v\) (\(1 \le u, v \le n\), \(u \ne v\)) — indices of vertices connected by an edge.Following line contains single integer \(q\) (\(1 \le q \le 5\)) — number of queries.The following \(2 \cdot q\) lines contain descriptions of sets.The first line of the description contains an integer \(k\) (\(1 \le k \le n\)) — the size of the set.The second line of the description contains \(k\) of distinct integers \(p_1, p_2, \dots, p_k\) (\(1 \le p_i \le n\)) — indices of the vertices of the set.It is guaranteed that the sum of \(k\) values for all queries does not exceed \(2 \cdot 10^5\).
|
Output \(q\) lines, each of which contains the answer to the corresponding query. As an answer, output ""YES"" if the set is passable, and ""NO"" otherwise.You can output the answer in any case (for example, the strings ""yEs"", ""yes"", ""Yes"" and ""YES"" will be recognized as a positive answer).
|
Input: 5 1 2 2 3 2 4 4 5 5 3 3 2 5 5 1 2 3 4 5 2 1 4 3 1 3 5 3 1 5 4 | Output: YES NO YES NO YES
|
Hard
| 2 | 987 | 788 | 299 | 17 |
|
978 |
B
|
978B
|
B. File Name
| 800 |
greedy; strings
|
You can not just take the file and send it. When Polycarp trying to send a file in the social network ""Codehorses"", he encountered an unexpected problem. If the name of the file contains three or more ""x"" (lowercase Latin letters ""x"") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed.Determine the minimum number of characters to remove from the file name so after that the name does not contain ""xxx"" as a substring. Print 0 if the file name does not initially contain a forbidden substring ""xxx"".You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by \(1\). For example, if you delete the character in the position \(2\) from the string ""exxxii"", then the resulting string is ""exxii"".
|
The first line contains integer \(n\) \((3 \le n \le 100)\) — the length of the file name.The second line contains a string of length \(n\) consisting of lowercase Latin letters only — the file name.
|
Print the minimum number of characters to remove from the file name so after that the name does not contain ""xxx"" as a substring. If initially the file name dost not contain a forbidden substring ""xxx"", print 0.
|
In the first example Polycarp tried to send a file with name contains number \(33\), written in Roman numerals. But he can not just send the file, because it name contains three letters ""x"" in a row. To send the file he needs to remove any one of this letters.
|
Input: 6xxxiii | Output: 1
|
Beginner
| 2 | 916 | 199 | 215 | 9 |
348 |
B
|
348B
|
B. Apple Tree
| 2,100 |
dfs and similar; number theory; trees
|
You are given a rooted tree with n vertices. In each leaf vertex there's a single integer — the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf.A tree is balanced if for every vertex v of the tree all its subtrees, corresponding to the children of vertex v, are of equal weight. Count the minimum number of apples that you need to remove from the tree (specifically, from some of its leaves) in order to make the tree balanced. Notice that you can always achieve the goal by just removing all apples.
|
The first line contains integer n (2 ≤ n ≤ 105), showing the number of vertices in the tree. The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 108), ai is the number of apples in the vertex number i. The number of apples in non-leaf vertices is guaranteed to be zero. Then follow n - 1 lines, describing the tree edges. Each line contains a pair of integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi) — the vertices connected by an edge. The vertices are indexed from 1 to n. Vertex 1 is the root.
|
Print a single integer — the minimum number of apples to remove in order to make the tree balanced.Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the sin, cout streams cin, cout or the %I64d specifier.
|
Input: 60 0 12 13 5 61 21 31 42 52 6 | Output: 6
|
Hard
| 3 | 661 | 497 | 258 | 3 |
|
1,251 |
D
|
1251D
|
D. Salary Changing
| 1,900 |
binary search; greedy; sortings
|
You are the head of a large enterprise. \(n\) people work at you, and \(n\) is odd (i. e. \(n\) is not divisible by \(2\)).You have to distribute salaries to your employees. Initially, you have \(s\) dollars for it, and the \(i\)-th employee should get a salary from \(l_i\) to \(r_i\) dollars. You have to distribute salaries in such a way that the median salary is maximum possible.To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: the median of the sequence \([5, 1, 10, 17, 6]\) is \(6\), the median of the sequence \([1, 2, 1]\) is \(1\). It is guaranteed that you have enough money to pay the minimum salary, i.e \(l_1 + l_2 + \dots + l_n \le s\).Note that you don't have to spend all your \(s\) dollars on salaries.You have to answer \(t\) test cases.
|
The first line contains one integer \(t\) (\(1 \le t \le 2 \cdot 10^5\)) — the number of test cases.The first line of each query contains two integers \(n\) and \(s\) (\(1 \le n < 2 \cdot 10^5\), \(1 \le s \le 2 \cdot 10^{14}\)) — the number of employees and the amount of money you have. The value \(n\) is not divisible by \(2\).The following \(n\) lines of each query contain the information about employees. The \(i\)-th line contains two integers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le 10^9\)).It is guaranteed that the sum of all \(n\) over all queries does not exceed \(2 \cdot 10^5\).It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. \(\sum\limits_{i=1}^{n} l_i \le s\).
|
For each test case print one integer — the maximum median salary that you can obtain.
|
In the first test case, you can distribute salaries as follows: \(sal_1 = 12, sal_2 = 2, sal_3 = 11\) (\(sal_i\) is the salary of the \(i\)-th employee). Then the median salary is \(11\).In the second test case, you have to pay \(1337\) dollars to the only employee.In the third test case, you can distribute salaries as follows: \(sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7\). Then the median salary is \(6\).
|
Input: 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 | Output: 11 1337 6
|
Hard
| 3 | 848 | 733 | 85 | 12 |
839 |
C
|
839C
|
C. Journey
| 1,500 |
dfs and similar; dp; graphs; probabilities; trees
|
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.
|
The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities.Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road.It is guaranteed that one can reach any city from any other by the roads.
|
Print a number — the expected length of their journey. The journey starts in the city 1.Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
|
In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
|
Input: 41 21 32 4 | Output: 1.500000000000000
|
Medium
| 5 | 861 | 304 | 320 | 8 |
2,077 |
D
|
2077D
|
D. Maximum Polygon
| 3,100 |
brute force; data structures; greedy; implementation; math
|
Given an array \(a\) of length \(n\), determine the lexicographically largest\(^{\text{∗}}\) subsequence\(^{\text{†}}\) \(s\) of \(a\) such that \(s\) can be the side lengths of a polygon.Recall that \(s\) can be the side lengths of a polygon if and only if \(|s| \geq 3\) and$$$\( 2 \cdot \max(s_1, s_2, \ldots, s_{|s|}) < s_1 + s_2 + \ldots + s_{|s|}. \)\(If no such subsequence \)s\( exists, print \)-1\(.\)^{\text{∗}}\(A sequence \)x\( is lexicographically smaller than a sequence \)y\( if and only if one of the following holds: \)x\( is a prefix of \)y\(, but \)x \ne y\(; in the first position where \)x\( and \)y\( differ, the sequence \)x\( has a smaller element than the corresponding element in \)y\(.\)^{\text{†}}\(A sequence \)x\( is a subsequence of a sequence \)y\( if \)x\( can be obtained from \)y$$$ by deleting several (possibly zero or all) elements.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The first line of each test case contains a single integer \(n\) (\(3 \leq n \leq 2 \cdot 10^5\)) — the length of the array \(a\).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 10^9\)) — the array \(a\).It is guaranteed that the total sum of all values of \(n\) across all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, output the answer in the following format:If the answer exists, output the following.In the first line, output the integer \(k\) (\(1 \leq k \leq n\)) — the length of the subsequence \(s\).In the second line, output \(k\) integers \(s_1, s_2, \ldots, s_k\) (\(1 \leq s_i \leq 10^9\), \(s\) is a subsequence of \(a\)) — the subsequence \(s\). Note that the desired output is the value, not the index.Otherwise, output a single line with the integer \(-1\).
|
In the first test case, there are no subsequences that can be the side lengths of a polygon.In the second test case, there are \(2\) subsequences that can be the side lengths of a polygon: \(1, 4, 2, 3\) and \(4, 2, 3\). The latter is the lexicographically larger subsequence.
|
Input: 533 1 241 4 2 361 6 4 5 3 2643 12 99 53 22 479 764 54 73 22 23 1 | Output: -1 3 4 2 3 4 6 5 3 2 5 43 99 53 22 4 4 54 73 23 1
|
Master
| 5 | 870 | 517 | 475 | 20 |
276 |
B
|
276B
|
B. Little Girl and Game
| 1,300 |
games; greedy
|
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string ""abba"" is a palindrome and string ""abc"" isn't. Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.
|
The input contains a single line, containing string s (1 ≤ |s| ≤ 103). String s consists of lowercase English letters.
|
In a single line print word ""First"" if the first player wins (provided that both players play optimally well). Otherwise, print word ""Second"". Print the words without the quotes.
|
Input: aba | Output: First
|
Easy
| 2 | 706 | 118 | 182 | 2 |
|
1,778 |
E
|
1778E
|
E. The Tree Has Fallen!
| 2,500 |
bitmasks; dfs and similar; math; trees
|
Recently, a tree has fallen on Bob's head from the sky. The tree has \(n\) nodes. Each node \(u\) of the tree has an integer number \(a_u\) written on it. But the tree has no fixed root, as it has fallen from the sky.Bob is currently studying the tree. To add some twist, Alice proposes a game. First, Bob chooses some node \(r\) to be the root of the tree. After that, Alice chooses a node \(v\) and tells him. Bob then can pick one or more nodes from the subtree of \(v\). His score will be the bitwise XOR of all the values written on the nodes picked by him. Bob has to find the maximum score he can achieve for the given \(r\) and \(v\).As Bob is not a good problem-solver, he asks you to help him find the answer. Can you help him? You need to find the answers for several combinations of \(r\) and \(v\) for the same tree.Recall that a tree is a connected undirected graph without cycles. The subtree of a node \(u\) is the set of all nodes \(y\) such that the simple path from \(y\) to the root passes through \(u\). Note that \(u\) is in the subtree of \(u\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^5\)). The description of the test cases follows.The first line contains an integer \(n\) (\(2\leq n\leq 2 \cdot 10^5\)) — the number of nodes of the tree. The next line contains \(n\) space-separated integers \(a_1, a_2, \dots, a_n\) (\(1\leq a_i\leq 10^9\)) — the values written on the nodes. Each of the next \(n-1\) lines contain two integers \(u\) and \(v\) (\(1\leq u, v\leq n\); \(u\neq v\)), denoting there is an undirected edge between node \(u\) and node \(v\). It is guaranteed that the given edges form a tree.The next line contains an integer \(q\) (\(1\leq q\leq 2 \cdot 10^5\)) — the number of queries. Each of the next \(q\) lines contains two integers \(r\) and \(v\) (\(1\leq r, v\leq n\)) — the root node Bob defines, and the node Alice chooses.It is guaranteed that the sum of \(n\) and the sum of \(q\) over all test cases don't exceed \(2 \cdot 10^5\).
|
For each test case, in each query, print a line containing an integer denoting the maximum score Bob can achieve.
|
In each of the below figures, the green-colored node is the node picked by Bob, and the red-colored node is the node picked by Alice. The values of the nodes are placed in the blue boxes beside the nodes.Consider the first example. In the first query, if we put the root node \(4\) at the top of the tree, the tree looks like the below figure: Tree with root node \(4\) in the first query. The nodes in the subtree of the node \(2\) are \([2,1,5,6,3]\). Among them, Bob can pick node \(3\), node \(5\), and node \(6\). His score will be \(a_3 \oplus a_5 \oplus a_6 = 8 \oplus 6 \oplus 1 = 15\). He can't achieve any score more than this.In the second query, if the root node \(3\) is placed at the top of the tree, the tree looks like the below figure: Tree with root node \(3\) in the second query. The only node in the subtree of the node \(5\) is \(5\). Bob can only pick the node \(5\). His score will be \(a_5 = 6\).In the third query, if the root node \(1\) is placed at the top of the tree, the tree looks like this: Tree with root node \(1\) in the third query. The nodes in the subtree of the node \(2\) are \([2,3,6,4]\). Among them, Bob can pick node \(2\), node \(3\), and node \(4\). His score will be \(a_2 \oplus a_3 \oplus a_4 = 12 \oplus 8 \oplus 25 = 29\). He is not able to score higher than that.
|
Input: 3612 12 8 25 6 11 51 22 62 32 434 23 51 223 81 242 22 11 21 133 8 71 22 322 22 1 | Output: 15 6 29 11 3 8 11 15 3
|
Expert
| 4 | 1,068 | 986 | 113 | 17 |
1,885 |
A
|
1885A
|
A. Deterministic Scheduling for Extended Reality over 5G and Beyond
| 0 |
*special
|
Background Extended reality (XR) service is a promising application for future communications. In wireless communications, XR data are transmitted over radio between base stations and mobile terminals. A region is usually divided into multiple cells, each of which is equipped with a base station to serve users. One base station usually serves multiple users, and multiple base stations may serve one user at the same time.TaskThe task of this competition is to design a scheduling algorithm for XR service. By properly allocating radio resources, we want to maximize the number of XR data frames that are successfully transmitted. A diagram is provided below for illustration: The transmission of a data frame is failed when it cannot be completely transmitted during the permitted transmission time window. Therefore, the objective of this task can be modeled as: $$$\( \mathcal{P}: \max \sum_j f_j \tag{1} \)\( \)\( f_j=\left\{\begin{array}{c} 1, g_j \geq T B S_j \\ 0, g_j< T B S_j \end{array}\right. \tag{2} \)\( Here, \)f_j\( represents the transmission result of the \)j\(-th frame: when the actual transmitted bits \)g_j\( (computed via (5)) is not less than the size of the frame, i.e., \)TBS_j\( (transport block size), the frame would be successfully transmitted so that \)f_j=1\(. Otherwise, \)f_j=0\(.To achieve better user experience, scheduling algorithm should be proposed to efficiently assign the limited radio resources: Time domain resource, which is divided into several transmission time intervals (TTIs), each TTI corresponds to a transmission time of \)0.5\(ms. Frequency domain resource, which is divided into several resource block groups (Resource Block Group, RBG), each RBG corresponds to a transmission bandwidth of \)5760\( kHz. Power domain resource: each cell has a fixed maximum transmission power to serve users. Summarily, two optimization variables are introduced to represent the scheduling result: \)\( b_{r n t}^{(k)} \in\{0,1\} \tag{3} \)\( \)\( p_{ {rnt }}^{(k)} \geq 0 , \quad \sum_r \sum_n p_{ {rnt }}^{(k)} \leq R, \quad \sum_n p_{ {rnt }}^{(k)} \leq 4 \tag{4} \)\( Here, \)b_{rnt}^{(k)}\( is a Boolean variable denoting whether the \)r\(-th RBG of cell \)k\( is allocated to user \)n\( at TTI \)t\(, and \)p_{rnt}^{(k)}\( is a nonnegative continuous variable denoting the power allocated to user \)n\( in the \)r\(-th RBG of cell \)k\( at TTI \)t\(. For each TTI of each cell, the power range of each RBG is between \)0\( and \)4\(, and the total power of all RBGs can not be larger than \)R\(.When the radio resources are allocated to the users, the XR data transmission can be provided for them. Assume that the \)j\(-th frame belongs to the \)n\(-th user, the actual transmitted bits for the frame, i.e., \)g_j\( can be given by:\)\( g_{j}= W\times \sum_{t=t_{0, j}}^{t_{1, j}} \sum_k \sum_r b_{r n t}^{(k)} \times \log _2\left(1+s_{n t}^{(k)}\right). \tag{5} \)\( Note that \)W\times \mathrm{log}_2 (1+s_{nt}^{(k)} ) \( is the well-known Shannon formula, which represents the transmitted data volume, where \)s_{nt}^{(k)}\( represents the transmission SINR (Signal-to-Interference-plus-Noise-Ratio) of user \)n\( in cell \)k\( at TTI \)t\(, and \)W=192\( is the constant number of available frequency resounce elements of one RBG. \)t_{0,j}\( and \)t_{1,j}\( denote the start TTI and the end TTI of frame \)j\(, respectively. The physical meaning of Formula (5) is that the number of bits transmitted within the valid time period, \)t_{0,j}\sim t_{1,j}\(, will be counted as valid transmission bits for the \)j\(-th frame. Finally, we give the expression of SINR, which may be complicated but corresponds to the actual physical transmission:\)\( s_{nt}^{\left( k \right)} = {\left( {\prod\limits_{r,b_{rnt}^{\left( k \right)} = 1} {s_{rnt}^{\left( k \right)}} } \right)^{\frac{1}{{\sum\nolimits_r {b_{rnt}^{\left( k \right)}} }}}} \tag{6} \)\( \)\( s_{r n t}^{(k)}=\frac{s_{0, r n t}^{(k)} \times p_{r n t}^{(k)} \times \prod_{m \neq n} e^{d^{(k)}_{mrn} \times b_{r m t}^{(k)}}}{1+\sum_{k^{\prime} \neq k, n^{\prime} \neq n} s_{0, r n t}^{(k^{\prime})} \times p_{r n^{\prime} t}^{\left(k^{\prime}\right)} \times e^{-d^{(k^{\prime})}_{n^{\prime}rn}}} \tag{7} \)\(Formula (6) shows the computation of user-level effective SINR: the transmission SINR of user \)n\(, i.e., \)s_{nt}^{(k)}\(, is the geometric mean of the SINRs of scheduled RBGs. Then, formula (7) shows the computation of RBG-level effective SINR. \)s_{0,rnt}^{(k)}\( is a given constant denoting the initial SINR on RBG \)r\( of cell \)k\( at TTI \)t\(, which indicates the quality of the channel. Another given constant value \)d^{(k)}_{mrn}\( represents the interference factor between user \)m\( and user \)n\( on RBG \)r\(, when user \)m\( is scheduled on cell \)k\(. Note that \)d^{(k)}_{mrn}=d^{(k)}_{nrm}\le 0$$$, which reveals that scheduling multiple users on the same RBG-TTI resource will cause a decrease in the SINR of each user.To sum up, participants are required to find an efficient radio resource allocation, so that more XR data frames can be successfully transmitted.
|
The input of a single test has \((4 + R \cdot K \cdot T + N \cdot R \cdot K + 1 + J)\) lines, which contains user number \(N\), cell number \(K\), TTI number \(T\), RBG number \(R\), initial SINRs \(s_{0, r n t}^{(k)}\), interference factors \(d_{mrn}\), frame number \(J\) and information about \(J\) frames. The details are as follows: Line \(1\): User number \(N\), integer, \(1 \leq N \leq 100\). Users are numbered from \(0\) to \(N - 1\). Line \(2\): Cell number \(K\), integer, \(1 \leq K \leq 10\). Cells are numbered from \(0\) to \(K - 1\). Line \(3\): TTI number \(T\), integer, \(1 \leq T \leq 1000\). TTIs are numbered from \(0\) to \(T - 1\). Line \(4\): RBG number \(R\), integer, \(1 \leq R \leq 10\). RBGs are numbered from \(0\) to \(R - 1\). Line \(5\) to \((4+R \cdot K\cdot T)\): Initial SINRs \(s_{0, r n t}^{(k)}\), float, \(0 < s_{0, r n t}^{(k)} < 10\,000\). Each line has \(N\) elements, corresponding to \(N\) users. \(s_{0, r n t}^{(k)}\) is the \((n+1)\)-th element of line \((5+r+k \cdot R+t \cdot K \cdot R)\). Line \((5+R \cdot K \cdot T)\) to \((4+R \cdot K \cdot T + N \cdot R \cdot K)\): Interference factors \(d^{(k)}_{mrn}\), float, \(-2 \leq d^{(k)}_{mrn} \leq 0\). Each line has \(N\) elements, corresponding to \(N\) users. \(d^{(k)}_{mrn}\) is the \((n+1)\)-th element of line \((5+R \cdot K \cdot T+m+r \cdot N + k \cdot R \cdot N)\). Line \((5+R \cdot K \cdot T + N \cdot R \cdot K)\): Frame number \(J\), integer, \(1 \leq J \leq 5000\). Last \(J\) lines: Frame information. Each line contains \(5\) integers corresponding to a frame, which are, in order: frame ID \(j\in\{0,\ldots,J-1\}\) in increasing order, size \(TBS_j\) (\(0 < TBS_j \leq 100\,000\)), user ID it belongs to, first TTI \(t_{0,j} \in\{0,\ldots,T-1\}\), and number of TTIs \(t_{d,j} \in \left[ {1,100} \right]\). Last TTI for frame \(j\) can be found as \(t_{1,j}=t_{0,j}+t_{d,j}-1\); it is guaranteed that \(t_{1,j} \le T - 1\). It is guaranteed that each user has at most one frame at each TTI.
|
Output for a certain input is the optimization result of \(p_{r n t}^{(k)}\) (float), which has \(R \cdot K \cdot T\) lines. Each line has \(N\) elements, corresponding to \(N\) users. \(p_{r n t}^{(k)}\) is the \((n+1)\)-th element of line \((1+r+k \cdot R+t \cdot K \cdot R)\). Note that the optimization result of \(b_{r n t}^{(k)}\) does not need to be output, because \(p_{r n t}^{(k)}>0\) and \(p_{r n t}^{(k)} = 0\) means \(b_{r n t}^{(k)}=1\) and \(b_{r n t}^{(k)} = 0\), respectively.Please note that if the outputs do not meet the constraint (4), it will be judged as an incorrect answer and get score \(0\). Besides, transmit on some TTIs out of time window is valid, but usually results in a lower score due to resources waste.
|
Two sets of tests are prepared in this problem. For the duration of the competition, each submission is tested on the preliminary set of tests. When the competition is finished, for each contestant:The jury takes the latest submission with non-zero score on preliminary tests;This submission is tested on the final set of tests for the final rank;The two sets of tests are generated from the same pool of data, based on the real word data.
|
Input: 2 2 2 1 1.3865 11.3865 1.3865 11.3865 2.3865 2.3865 2.3865 2.3865 0 -2 -2 0 0 -2 -2 0 2 0 250 0 0 2 1 25 1 0 2 | Output: 0.000000 0.004950 0.000000 0.004950 0.245039 0.000000 0.245039 0.000000
|
Beginner
| 1 | 5,101 | 2,009 | 739 | 18 |
221 |
B
|
221B
|
B. Little Elephant and Numbers
| 1,300 |
implementation
|
The Little Elephant loves numbers. He has a positive integer x. The Little Elephant wants to find the number of positive integers d, such that d is the divisor of x, and x and d have at least one common (the same) digit in their decimal representations. Help the Little Elephant to find the described number.
|
A single line contains a single integer x (1 ≤ x ≤ 109).
|
In a single line print an integer — the answer to the problem.
|
Input: 1 | Output: 1
|
Easy
| 1 | 308 | 56 | 62 | 2 |
|
1,968 |
F
|
1968F
|
F. Equal XOR Segments
| 1,800 |
binary search; data structures
|
Let us call an array \(x_1,\dots,x_m\) interesting if it is possible to divide the array into \(k>1\) parts so that bitwise XOR of values from each part are equal. More formally, you must split array \(x\) into \(k\) consecutive segments, each element of \(x\) must belong to exactly \(1\) segment. Let \(y_1,\dots,y_k\) be the XOR of elements from each part respectively. Then \(y_1=y_2=\dots=y_k\) must be fulfilled.For example, if \(x = [1, 1, 2, 3, 0]\), you can split it as follows: \([\color{blue}1], [\color{green}1], [\color{red}2, \color{red}3, \color{red}0]\). Indeed \(\color{blue}1=\color{green}1=\color{red}2 \oplus \color{red}3\oplus \color{red}0\).You are given an array \(a_1,\dots,a_n\). Your task is to answer \(q\) queries: For fixed \(l\), \(r\), determine whether the subarray \(a_l,a_{l+1},\dots,a_r\) is interesting.
|
The 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 \(q\) (\(2 \le n \le 2 \cdot 10^5\), \(1 \le q \le 2 \cdot 10^5\)) — the number of elements in the array and the number of queries respectively.The next line contains \(n\) integers \(a_1,\dots,a_n\) (\(0 \le a_i < 2^{30}\)) — elements of the array.Each of the next \(q\) lines contains two integers \(l\) and \(r\) (\(1 \le l < r \le n\)) describing the query.It is guaranteed that the sum of \(n\) over all testcases does not exceed \(2 \cdot 10^5\).It is guaranteed that the sum of \(q\) over all testcases does not exceed \(2 \cdot 10^5\).
|
For each query, output ""YES"" if the subarray is interesting and ""NO"" otherwise.You can output ""Yes"" and ""No"" in any case (for example, the strings ""yES"", ""yes"", and ""Yes"" will be recognized as correct answers).
|
Explanation for the first test case:The first query is described in the statement.In the second query, we should divide \([1,2,3]\). A possible division is \([1,2],[3]\), since \(1\oplus 2=3\).It can be shown that for queries \(3,4,5\), the subarrays are not interesting.
|
Input: 45 51 1 2 3 01 52 43 51 33 45 51 2 3 4 51 52 43 51 32 37 412 9 10 9 10 11 91 51 72 62 711 40 0 1 0 0 1 0 1 1 0 11 22 56 97 11 | Output: YES YES NO NO NO YES NO NO YES NO NO NO NO NO YES NO YES YES
|
Medium
| 2 | 839 | 703 | 224 | 19 |
1,515 |
H
|
1515H
|
H. Phoenix and Bits
| 3,500 |
bitmasks; brute force; data structures; sortings
|
Phoenix loves playing with bits — specifically, by using the bitwise operations AND, OR, and XOR. He has \(n\) integers \(a_1, a_2, \dots, a_n\), and will perform \(q\) of the following queries: replace all numbers \(a_i\) where \(l \le a_i \le r\) with \(a_i\) AND \(x\); replace all numbers \(a_i\) where \(l \le a_i \le r\) with \(a_i\) OR \(x\); replace all numbers \(a_i\) where \(l \le a_i \le r\) with \(a_i\) XOR \(x\); output how many distinct integers \(a_i\) where \(l \le a_i \le r\). For each query, Phoenix is given \(l\), \(r\), and \(x\). Note that he is considering the values of the numbers, not their indices.
|
The first line contains two integers \(n\) and \(q\) (\(1 \le n \le 2 \cdot 10^5\); \(1 \le q \le 10^5\)) — the number of integers and the number of queries, respectively.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(0 \le a_i < 2^{20}\)) — the integers that Phoenix starts with.The next \(q\) lines contain the queries. For each query, the first integer of each line is \(t\) (\(1 \le t \le 4\)) — the type of query.If \(t \in \{1, 2, 3\}\), then three integers \(l_i\), \(r_i\), and \(x_i\) will follow (\(0 \le l_i, r_i, x_i < 2^{20}\); \(l_i \le r_i\)).Otherwise, if \(t=4\), two integers \(l_i\) and \(r_i\) will follow (\(0 \le l_i \le r_i < 2^{20}\)).It is guaranteed that there is at least one query where \(t=4\).
|
Print the answer for each query where \(t=4\).
|
In the first example: For the first query, \(2\) is replaced by \(2\) AND \(2 = 2\) and \(3\) is replaced with \(3\) AND \(2 = 2\). The set of numbers is \(\{1, 2, 4, 5\}\). For the second query, there are \(3\) distinct numbers between \(2\) and \(5\): \(2\), \(4\), and \(5\). For the third query, \(2\) is replaced by \(2\) XOR \(3 = 1\), \(4\) is replaced by \(4\) XOR \(3 = 7\), and \(5\) is replaced by \(5\) XOR \(3 = 6\). The set of numbers is \(\{1, 6, 7\}\). For the fourth query, there are \(2\) distinct numbers between \(1\) and \(6\): \(1\) and \(6\). For the fifth query, \(1\) is replaced by \(1\) OR \(8 = 9\). The set of numbers is \(\{6, 7, 9\}\). For the sixth query, there is one distinct number between \(8\) and \(10\): \(9\).
|
Input: 5 6 5 4 3 2 1 1 2 3 2 4 2 5 3 2 5 3 4 1 6 2 1 1 8 4 8 10 | Output: 3 2 1
|
Master
| 4 | 628 | 744 | 46 | 15 |
2,022 |
A
|
2022A
|
A. Bus to Pénjamo
| 800 |
constructive algorithms; greedy; implementation; math
|
Ya vamos llegando a Péeeenjamoo ♫♫♫ There are \(n\) families travelling to Pénjamo to witness Mexico's largest-ever ""walking a chicken on a leash"" marathon. The \(i\)-th family has \(a_i\) family members. All families will travel using a single bus consisting of \(r\) rows with \(2\) seats each.A person is considered happy if: Another family member is seated in the same row as them, or They are sitting alone in their row (with an empty seat next to them). Determine the maximum number of happy people in an optimal seating arrangement. Note that everyone must be seated in the bus.It is guaranteed that all family members will fit on the bus. Formally, it is guaranteed that \(\displaystyle\sum_{i=1}^{n}a_i \le 2r\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 1000\)). The description of the test cases follows.The first line of each test case contains two integers \(n\) and \(r\) (\(1 \le n \le 100\); \(1 \le r \le 500\)) — the number of families and the number of rows in the bus.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10\)) — the number of family members in each family.
|
For each test case, output the maximum number of happy people in an optimal seating arrangement.
|
In the first test case, the two members of the first family can sit together in the first row, while the two members of the second family can sit together in the second row. The remaining member of the second family can sit in the third row along with a member of the third family. This seating arrangement is shown below, where the \(4\) happy people are colored green. \(\color{green}{1}\)\(\color{green}{1}\)\(\color{green}{2}\)\(\color{green}{2}\)\(2\)\(3\) In the second test case, a possible seating arrangement with \(6\) happy people is shown below. \(\color{green}{3}\)\(\color{green}{3}\)\(\color{green}{1}\)\(\color{green}{1}\)\(\color{green}{2}\)\(\color{green}{2}\) In the third test case, a possible seating arrangement with \(6\) happy people is shown below. \(\color{green}{4}\)\(\color{green}{4}\)\(\color{green}{}\)\(\color{green}{2}\)\(\color{green}{3}\)\(\color{green}{3}\)\(\color{green}{1}\)\(\color{green}{}\)\(\color{green}{}\)\(\color{green}{}\)
|
Input: 43 32 3 13 32 2 24 51 1 2 24 53 1 1 3 | Output: 4 6 6 6
|
Beginner
| 4 | 723 | 469 | 96 | 20 |
1,316 |
F
|
1316F
|
F. Battalion Strength
| 2,800 |
data structures; divide and conquer; probabilities
|
There are \(n\) officers in the Army of Byteland. Each officer has some power associated with him. The power of the \(i\)-th officer is denoted by \(p_{i}\). As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these \(n\) officers and calls this subset a battalion.(All \(2^n\) subsets of the \(n\) officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be \(a_{1},a_{2},\ldots,a_{k}\), where \(a_1 \le a_2 \le \dots \le a_k\). The strength of this battalion is equal to \(a_1a_2 + a_2a_3 + \dots + a_{k-1}a_k\). (If the size of Battalion is \(\leq 1\), then the strength of this battalion is \(0\)).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be \(q\) changes. Each one of the form \(i\) \(x\) indicating that \(p_{i}\) is changed to \(x\).You need to find the strength of the army initially and after each of these \(q\) updates.Note that the changes are permanent.The strength should be found by modulo \(10^{9}+7\). Formally, let \(M=10^{9}+7\). It can be shown that the answer can be expressed as an irreducible fraction \(p/q\), where \(p\) and \(q\) are integers and \(q\not\equiv 0 \bmod M\)). Output the integer equal to \(p\cdot q^{-1} \bmod M\). In other words, output such an integer \(x\) that \(0 \leq x < M\) and \(x ⋅ q \equiv p \bmod M\)).
|
The first line of the input contains a single integer \(n\) (\(1 \leq n \leq 3⋅10^{5}\)) — the number of officers in Byteland's Army.The second line contains \(n\) integers \(p_{1},p_{2},\ldots,p_{n}\) (\(1 \leq p_{i} \leq 10^{9}\)).The third line contains a single integer \(q\) (\(1 \leq q \leq 3⋅10^{5}\)) — the number of updates.Each of the next \(q\) lines contains two integers \(i\) and \(x\) (\(1 \leq i \leq n\), \( 1 \leq x \leq 10^{9}\)), indicating that \(p_{i}\) is updated to \(x\) .
|
In the first line output the initial strength of the army.In \(i\)-th of the next \(q\) lines, output the strength of the army after \(i\)-th update.
|
In first testcase, initially, there are four possible battalions {} Strength = \(0\) {\(1\)} Strength = \(0\) {\(2\)} Strength = \(0\) {\(1,2\)} Strength = \(2\) So strength of army is \(\frac{0+0+0+2}{4}\) = \(\frac{1}{2}\)After changing \(p_{1}\) to \(2\), strength of battallion {\(1,2\)} changes to \(4\), so strength of army becomes \(1\).After changing \(p_{2}\) to \(1\), strength of battalion {\(1,2\)} again becomes \(2\), so strength of army becomes \(\frac{1}{2}\).
|
Input: 2 1 2 2 1 2 2 1 | Output: 500000004 1 500000004
|
Master
| 3 | 1,682 | 497 | 149 | 13 |
485 |
A
|
485A
|
A. Factory
| 1,400 |
implementation; math; matrices
|
One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were x details in the factory storage, then by the end of the day the factory has to produce (remainder after dividing x by m) more details. Unfortunately, no customer has ever bought any mythical detail, so all the details produced stay on the factory. The board of directors are worried that the production by the given plan may eventually stop (that means that there will be а moment when the current number of details on the factory is divisible by m). Given the number of details a on the first day and number m check if the production stops at some moment.
|
The first line contains two integers a and m (1 ≤ a, m ≤ 105).
|
Print ""Yes"" (without quotes) if the production will eventually stop, otherwise print ""No"".
|
Input: 1 5 | Output: No
|
Easy
| 3 | 714 | 62 | 94 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.