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
1,210
C
1210C
C. Kamil and Making a Stream
2,000
math; number theory; trees
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached \(100\) million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?You're given a tree β€” a connected undirected graph consisting of \(n\) vertices connected by \(n - 1\) edges. The tree is rooted at vertex \(1\). A vertex \(u\) is called an ancestor of \(v\) if it lies on the shortest path between the root and \(v\). In particular, a vertex is an ancestor of itself.Each vertex \(v\) is assigned its beauty \(x_v\) β€” a non-negative integer not larger than \(10^{12}\). This allows us to define the beauty of a path. Let \(u\) be an ancestor of \(v\). Then we define the beauty \(f(u, v)\) as the greatest common divisor of the beauties of all vertices on the shortest path between \(u\) and \(v\). Formally, if \(u=t_1, t_2, t_3, \dots, t_k=v\) are the vertices on the shortest path between \(u\) and \(v\), then \(f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})\). Here, \(\gcd\) denotes the greatest common divisor of a set of numbers. In particular, \(f(u, u) = \gcd(x_u) = x_u\).Your task is to find the sum$$$\( \sum_{u\text{ is an ancestor of }v} f(u, v). \)\(As the result might be too large, please output it modulo \)10^9 + 7\(.Note that for each \)y\(, \)\gcd(0, y) = \gcd(y, 0) = y\(. In particular, \)\gcd(0, 0) = 0$$$.
The first line contains a single integer \(n\) (\(2 \le n \le 100\,000\)) β€” the number of vertices in the tree.The following line contains \(n\) integers \(x_1, x_2, \dots, x_n\) (\(0 \le x_i \le 10^{12}\)). The value \(x_v\) denotes the beauty of vertex \(v\).The following \(n - 1\) lines describe the edges of the tree. Each of them contains two integers \(a, b\) (\(1 \le a, b \le n\), \(a \neq b\)) β€” the vertices connected by a single edge.
Output the sum of the beauties on all paths \((u, v)\) such that \(u\) is ancestor of \(v\). This sum should be printed modulo \(10^9 + 7\).
The following figure shows all \(10\) possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to \(42\):
Input: 5 4 5 6 0 8 1 2 1 3 1 4 4 5 | Output: 42
Hard
3
1,408
446
140
12
467
E
467E
E. Alex and Complicated Task
2,300
data structures; dp; greedy
After you have read all the problems, probably, you think Alex is genius person. That's true! One day he came up with the following task.Given a sequence of integer numbers a1, a2, ..., an. You are to find a longest sequence b1, b2, ..., b4m, that satisfies the following conditions: b4k + 1 = b4k + 3 for all valid integer k; b4k + 2 = b4k + 4 for all valid integer k; sequence b is subsequence of a (not necessarily contiguous subsequence). And finally... Alex had given this complicated task to George, and George gave it to you. Help George to cope with the task.
The first line contains a single integer n (1 ≀ n ≀ 5Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109).
In the first line print a single integer 4m β€” the maximal possible length of required sequence b. In the second line print 4m integers b1, b2, ..., b4m, that is required sequence.If there are multiple optimal answers you may print any of them.
Input: 43 5 3 5 | Output: 43 5 3 5
Expert
3
567
125
243
4
633
F
633F
F. The Chocolate Spree
2,600
dfs and similar; dp; graphs; trees
Alice and Bob have a tree (undirected acyclic connected graph). There are ai chocolates waiting to be picked up in the i-th vertex of the tree. First, they choose two different vertices as their starting positions (Alice chooses first) and take all the chocolates contained in them.Then, they alternate their moves, selecting one vertex at a time and collecting all chocolates from this node. To make things more interesting, they decided that one can select a vertex only if he/she selected a vertex adjacent to that one at his/her previous turn and this vertex has not been already chosen by any of them during other move.If at any moment one of them is not able to select the node that satisfy all the rules, he/she will skip his turns and let the other person pick chocolates as long as he/she can. This goes on until both of them cannot pick chocolates any further.Due to their greed for chocolates, they want to collect as many chocolates as possible. However, as they are friends they only care about the total number of chocolates they obtain together. What is the maximum total number of chocolates they may pick?
The first line of the input contains the single integer n (2 ≀ n ≀ 100 000) β€” the number of vertices in the tree.The second line contains n integers ai (1 ≀ ai ≀ 109), i-th of these numbers stands for the number of chocolates stored at the node i.Then follow n - 1 lines that describe the tree. Each of them contains two integers ui and vi (1 ≀ ui, vi ≀ n) β€” indices of vertices connected by the i-th edge.
Print the number of chocolates Alice and Bob can collect together if they behave optimally.
In the first sample, Alice may start at the vertex 9 and Bob at vertex 8. Alice will select vertex 1 and Bob has no options now. Alice selects the vertex 7 and they both stop.In the second sample, both of them will pick either of the nodes alternately.
Input: 91 2 3 4 5 6 7 8 91 21 31 41 51 61 71 81 9 | Output: 25
Expert
4
1,122
406
91
6
1,333
E
1333E
E. Road to 1600
2,400
brute force; constructive algorithms
Egor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help!Before you start solving the problem, Egor wants to remind you how the chess pieces move. Chess rook moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, it can stop. The queen walks in all directions vertically and diagonally at any distance. You can see the examples below. To reach the goal, Egor should research the next topic:There is an \(N \times N\) board. Each cell of the board has a number from \(1\) to \(N ^ 2\) in it and numbers in all cells are distinct.In the beginning, some chess figure stands in the cell with the number \(1\). Note that this cell is already considered as visited. After that every move is determined by the following rules: Among all not visited yet cells to which the figure can get in one move, it goes to the cell that has minimal number. If all accessible cells were already visited and some cells are not yet visited, then the figure is teleported to the not visited cell that has minimal number. If this step happens, the piece pays a fee of \(1\) vun. If all cells are already visited, the process is stopped. Egor should find an \(N \times N\) board on which the rook pays strictly less vuns than the queen during the round with this numbering. Help him to find such \(N \times N\) numbered board, or tell that it doesn't exist.
The only line contains one integer \(N\) β€” the size of the board, \(1\le N \le 500\).
The output should contain \(N\) lines.In \(i\)-th line output \(N\) numbers β€” numbers on the \(i\)-th row of the board. All numbers from \(1\) to \(N \times N\) must be used exactly once.On your board rook must pay strictly less vuns than the queen.If there are no solutions, print \(-1\).If there are several solutions, you can output any of them.
In case we have \(1 \times 1\) board, both rook and queen do not have a chance to pay fees.In second sample rook goes through cells \(1 \to 3 \to 4 \to 6 \to 9 \to 5 \to 7 \to 13 \to 2 \to 8 \to 16 \to 11 \to 10 \to 12 \to 15 \to \textbf{(1 vun)} \to 14\). Queen goes through \(1 \to 3 \to 4 \to 2 \to 5 \to 6 \to 9 \to 7 \to 13 \to 8 \to 11 \to 10 \to 12 \to 15 \to \textbf{(1 vun)} \to 14 \to \textbf{(1 vun)} \to 16\).As a result rook pays 1 vun and queen pays 2 vuns.
Input: 1 | Output: -1
Expert
2
1,436
85
348
13
1,178
D
1178D
D. Prime Graph
1,500
constructive algorithms; greedy; math; number theory
Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled!When building the graph, he needs four conditions to be satisfied: It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. The number of vertices must be exactly \(n\) β€” a number he selected. This number is not necessarily prime. The total number of edges must be prime. The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for \(n = 4\). The first graph (left one) is invalid as the degree of vertex \(2\) (and \(4\)) equals to \(1\), which is not prime. The second graph (middle one) is invalid as the total number of edges is \(4\), which is not a prime number. The third graph (right one) is a valid answer for \(n = 4\). Note that the graph can be disconnected.Please help Bob to find any such graph!
The input consists of a single integer \(n\) (\(3 \leq n \leq 1\,000\)) β€” the number of vertices.
If there is no graph satisfying the conditions, print a single line containing the integer \(-1\).Otherwise, first print a line containing a prime number \(m\) (\(2 \leq m \leq \frac{n(n-1)}{2}\)) β€” the number of edges in the graph. Then, print \(m\) lines, the \(i\)-th of which containing two integers \(u_i\), \(v_i\) (\(1 \leq u_i, v_i \leq n\)) β€” meaning that there is an edge between vertices \(u_i\) and \(v_i\). The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops.If there are multiple solutions, you may print any of them.Note that the graph can be disconnected.
The first example was described in the statement.In the second example, the degrees of vertices are \([7, 5, 2, 2, 3, 2, 2, 3]\). Each of these numbers is prime. Additionally, the number of edges, \(13\), is also a prime number, hence both conditions are satisfied.
Input: 4 | Output: 5 1 2 1 3 2 3 2 4 3 4
Medium
4
1,067
97
617
11
1,630
C
1630C
C. Paint the Middle
2,200
dp; greedy; sortings; two pointers
You are given \(n\) elements numbered from \(1\) to \(n\), the element \(i\) has value \(a_i\) and color \(c_i\), initially, \(c_i = 0\) for all \(i\).The following operation can be applied: Select three elements \(i\), \(j\) and \(k\) (\(1 \leq i < j < k \leq n\)), such that \(c_i\), \(c_j\) and \(c_k\) are all equal to \(0\) and \(a_i = a_k\), then set \(c_j = 1\). Find the maximum value of \(\sum\limits_{i=1}^n{c_i}\) that can be obtained after applying the given operation any number of times.
The first line contains an integer \(n\) (\(3 \leq n \leq 2 \cdot 10^5\)) β€” the number of elements.The second line consists of \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \leq a_i \leq n\)), where \(a_i\) is the value of the \(i\)-th element.
Print a single integer in a line β€” the maximum value of \(\sum\limits_{i=1}^n{c_i}\) that can be obtained after applying the given operation any number of times.
In the first test, it is possible to apply the following operations in order:
Input: 7 1 2 1 2 7 4 7 | Output: 2
Hard
4
501
243
161
16
62
C
62C
C. Inquisition
2,300
geometry; implementation; sortings
In Medieval times existed the tradition of burning witches at steaks together with their pets, black cats. By the end of the 15-th century the population of black cats ceased to exist. The difficulty of the situation led to creating the EIC - the Emergency Inquisitory Commission.The resolution #666 says that a white cat is considered black when and only when the perimeter of its black spots exceeds the acceptable norm. But what does the acceptable norm equal to? Every inquisitor will choose it himself depending on the situation. And your task is to find the perimeter of black spots on the cat's fur.The very same resolution says that the cat's fur is a white square with the length of 105. During the measurement of spots it is customary to put the lower left corner of the fur into the origin of axes (0;0) and the upper right one β€” to the point with coordinates (105;105). The cats' spots are nondegenerate triangles. The spots can intersect and overlap with each other, but it is guaranteed that each pair of the triangular spots' sides have no more than one common point.We'll regard the perimeter in this problem as the total length of the boarders where a cat's fur changes color.
The first input line contains a single integer n (0 ≀ n ≀ 100). It is the number of spots on the cat's fur. The i-th of the last n lines contains 6 integers: x1i, y1i, x2i, y2i, x3i, y3i. They are the coordinates of the i-th triangular spot (0 < xji, yji < 105).
Print a single number, the answer to the problem, perimeter of the union of triangles. Your answer should differ from the correct one in no more than 10 - 6.
Input: 11 1 2 1 1 2 | Output: 3.4142135624
Expert
3
1,193
262
157
0
1,907
C
1907C
C. Removal of Unattractive Pairs
1,200
constructive algorithms; greedy; math; strings
Vlad found a string \(s\) consisting of \(n\) lowercase Latin letters, and he wants to make it as short as possible.To do this, he can remove any pair of adjacent characters from \(s\) any number of times, provided they are different. For example, if \(s\)=racoon, then by removing one pair of characters he can obtain the strings coon, roon, raon, and raco, but he cannot obtain racn (because the removed letters were the same) or rcon (because the removed letters were not adjacent).What is the minimum length Vlad can achieve by applying any number of deletions?
The first line of the input contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. Descriptions of the test cases follow.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the length of the string \(s\).The second line of each test case contains the string \(s\) consisting of \(n\) lowercase Latin letters.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output a single numberβ€”the minimum length of the string \(s\), after removing pairs of adjacent characters with different values.
In the first test case of the example, you need to act as follows: ""aabc"" \(\rightarrow\) ""ac"" \(\rightarrow\) """". Note that with a different order of deletions, the string will not become empty.
Input: 104aabc5abaca10avbvvcvvvd7abcdefg5dabbb8aacebeaa7bbbbacc6dacfcc6fdfcdc9dbdcfbbdc | Output: 0 1 2 1 1 0 1 0 0 1
Easy
4
565
474
149
19
690
D2
690D2
D2. The Wall (medium)
1,800
combinatorics
Heidi the Cow is aghast: cracks in the northern Wall? Zombies gathering outside, forming groups, preparing their assault? This must not happen! Quickly, she fetches her HC2 (Handbook of Crazy Constructions) and looks for the right chapter:How to build a wall: Take a set of bricks. Select one of the possible wall designs. Computing the number of possible designs is left as an exercise to the reader. Place bricks on top of each other, according to the chosen design. This seems easy enough. But Heidi is a Coding Cow, not a Constructing Cow. Her mind keeps coming back to point 2b. Despite the imminent danger of a zombie onslaught, she wonders just how many possible walls she could build with up to n bricks.A wall is a set of wall segments as defined in the easy version. How many different walls can be constructed such that the wall consists of at least 1 and at most n bricks? Two walls are different if there exist a column c and a row r such that one wall has a brick in this spot, and the other does not.Along with n, you will be given C, the width of the wall (as defined in the easy version). Return the number of different walls modulo 106 + 3.
The first line contains two space-separated integers n and C, 1 ≀ n ≀ 500000, 1 ≀ C ≀ 200000.
Print the number of different walls that Heidi could build, modulo 106 + 3.
The number 106 + 3 is prime.In the second sample case, the five walls are: B BB., .B, BB, B., and .BIn the third sample case, the nine walls are the five as in the second sample case and in addition the following four: B BB B B BB., .B, BB, and BB
Input: 5 1 | Output: 5
Medium
1
1,158
93
75
6
1,301
B
1301B
B. Motarack's Birthday
1,500
binary search; greedy; ternary search
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array \(a\) of \(n\) non-negative integers.Dark created that array \(1000\) years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer \(k\) (\(0 \leq k \leq 10^{9}\)) and replaces all missing elements in the array \(a\) with \(k\).Let \(m\) be the maximum absolute difference between all adjacent elements (i.e. the maximum value of \(|a_i - a_{i+1}|\) for all \(1 \leq i \leq n - 1\)) in the array \(a\) after Dark replaces all missing elements with \(k\).Dark should choose an integer \(k\) so that \(m\) is minimized. Can you help him?
The input consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains one integer \(n\) (\(2 \leq n \leq 10^{5}\)) β€” the size of the array \(a\).The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(-1 \leq a_i \leq 10 ^ {9}\)). If \(a_i = -1\), then the \(i\)-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of \(n\) for all test cases does not exceed \(4 \cdot 10 ^ {5}\).
Print the answers for each test case in the following format:You should print two integers, the minimum possible value of \(m\) and an integer \(k\) (\(0 \leq k \leq 10^{9}\)) that makes the maximum absolute difference between adjacent elements in the array \(a\) equal to \(m\).Make sure that after replacing all the missing elements with \(k\), the maximum absolute difference between adjacent elements becomes \(m\).If there is more than one possible \(k\), you can print any of them.
In the first test case after replacing all missing elements with \(11\) the array becomes \([11, 10, 11, 12, 11]\). The absolute difference between any adjacent elements is \(1\). It is impossible to choose a value of \(k\), such that the absolute difference between any adjacent element will be \(\leq 0\). So, the answer is \(1\).In the third test case after replacing all missing elements with \(6\) the array becomes \([6, 6, 9, 6, 3, 6]\). \(|a_1 - a_2| = |6 - 6| = 0\); \(|a_2 - a_3| = |6 - 9| = 3\); \(|a_3 - a_4| = |9 - 6| = 3\); \(|a_4 - a_5| = |6 - 3| = 3\); \(|a_5 - a_6| = |3 - 6| = 3\). So, the maximum difference between any adjacent elements is \(3\).
Input: 7 5 -1 10 -1 12 -1 5 -1 40 35 -1 35 6 -1 -1 9 -1 3 -1 2 -1 -1 2 0 -1 4 1 -1 3 -1 7 1 -1 7 5 2 -1 5 | Output: 1 11 5 35 3 6 0 42 0 0 1 2 3 4
Medium
3
828
643
487
13
319
A
319A
A. Malek Dance Club
1,600
combinatorics; math
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2n members and coincidentally Natalia Fan Club also has 2n members. Each member of MDC is assigned a unique id i from 0 to 2n - 1. The same holds for each member of NFC.One of the parts of this tradition is one by one dance, where each member of MDC dances with a member of NFC. A dance pair is a pair of numbers (a, b) such that member a from MDC dances with member b from NFC.The complexity of a pairs' assignment is the number of pairs of dancing pairs (a, b) and (c, d) such that a < c and b > d.You are given a binary number of length n named x. We know that member i from MDC dances with member from NFC. Your task is to calculate the complexity of this assignment modulo 1000000007 (109 + 7).Expression denotes applying Β«XORΒ» to numbers x and y. This operation exists in all modern programming languages, for example, in C++ and Java it denotes as Β«^Β», in Pascal β€” Β«xorΒ».
The first line of input contains a binary number x of lenght n, (1 ≀ n ≀ 100).This number may contain leading zeros.
Print the complexity of the given dance assignent modulo 1000000007 (109 + 7).
Input: 11 | Output: 6
Medium
2
1,035
116
78
3
486
C
486C
C. Palindrome Transformation
1,700
brute force; greedy; implementation
Nam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.There is a cursor pointing at some symbol of the string. Suppose that cursor is at position i (1 ≀ i ≀ n, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position i - 1 if i > 1 or to the end of the string (i. e. position n) otherwise. The same holds when he presses the right arrow key (if i = n, the cursor appears at the beginning of the string).When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key.Initially, the text cursor is at position p. Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?
The first line contains two space-separated integers n (1 ≀ n ≀ 105) and p (1 ≀ p ≀ n), the length of Nam's string and the initial position of the text cursor.The next line contains n lowercase characters of Nam's string.
Print the minimum number of presses needed to change string into a palindrome.
A string is a palindrome if it reads the same forward or reversed.In the sample test, initial Nam's string is: (cursor position is shown bold).In optimal solution, Nam may do 6 following steps:The result, , is now a palindrome.
Input: 8 3aeabcaez | Output: 6
Medium
3
1,242
221
78
4
1,556
G
1556G
G. Gates to Another World
3,300
bitmasks; data structures; dsu; two pointers
As mentioned previously William really likes playing video games. In one of his favorite games, the player character is in a universe where every planet is designated by a binary number from \(0\) to \(2^n - 1\). On each planet, there are gates that allow the player to move from planet \(i\) to planet \(j\) if the binary representations of \(i\) and \(j\) differ in exactly one bit.William wants to test you and see how you can handle processing the following queries in this game universe: Destroy planets with numbers from \(l\) to \(r\) inclusively. These planets cannot be moved to anymore. Figure out if it is possible to reach planet \(b\) from planet \(a\) using some number of planetary gates. It is guaranteed that the planets \(a\) and \(b\) are not destroyed.
The first line contains two integers \(n\), \(m\) (\(1 \leq n \leq 50\), \(1 \leq m \leq 5 \cdot 10^4\)), which are the number of bits in binary representation of each planets' designation and the number of queries, respectively.Each of the next \(m\) lines contains a query of two types:block l r β€” query for destruction of planets with numbers from \(l\) to \(r\) inclusively (\(0 \le l \le r < 2^n\)). It's guaranteed that no planet will be destroyed twice.ask a b β€” query for reachability between planets \(a\) and \(b\) (\(0 \le a, b < 2^n\)). It's guaranteed that planets \(a\) and \(b\) hasn't been destroyed yet.
For each query of type ask you must output ""1"" in a new line, if it is possible to reach planet \(b\) from planet \(a\) and ""0"" otherwise (without quotation marks).
The first example test can be visualized in the following way: Response to a query ask 0 7 is positive.Next after query block 3 6 the graph will look the following way (destroyed vertices are highlighted): Response to a query ask 0 7 is negative, since any path from vertex \(0\) to vertex \(7\) must go through one of the destroyed vertices.
Input: 3 3 ask 0 7 block 3 6 ask 0 7 | Output: 1 0
Master
4
772
620
168
15
1,662
A
1662A
A. Organizing SWERC
0
brute force; implementation
Gianni, SWERC's chief judge, received a huge amount of high quality problems from the judges and now he has to choose a problem set for SWERC.He received \(n\) problems and he assigned a beauty score and a difficulty to each of them. The \(i\)-th problem has beauty score equal to \(b_i\) and difficulty equal to \(d_i\). The beauty and the difficulty are integers between \(1\) and \(10\). If there are no problems with a certain difficulty (the possible difficulties are \(1,2,\dots,10\)) then Gianni will ask for more problems to the judges.Otherwise, for each difficulty between \(1\) and \(10\), he will put in the problem set one of the most beautiful problems with such difficulty (so the problem set will contain exactly \(10\) problems with distinct difficulties). You shall compute the total beauty of the problem set, that is the sum of the beauty scores of the problems chosen by Gianni.
Each test contains multiple test cases. The first line contains an integer \(t\) (\(1\le t\le 100\)) β€” the number of test cases. The descriptions of the \(t\) test cases follow.The first line of each test case contains the integer \(n\) (\(1\le n\le 100\)) β€” how many problems Gianni received from the judges.The next \(n\) lines contain two integers each. The \(i\)-th of such lines contains \(b_i\) and \(d_i\) (\(1\le b_i, d_i\le 10\)) β€” the beauty score and the difficulty of the \(i\)-th problem.
For each test case, print the total beauty of the problem set chosen by Gianni. If Gianni cannot create a problem set (because there are no problems with a certain difficulty) print the string MOREPROBLEMS (all letters are uppercase, there are no spaces).
In the first test case, Gianni has received only \(3\) problems, with difficulties \(3, 4, 7\) which are not sufficient to create a problem set (for example because there is not a problem with difficulty \(1\)).In the second test case, Gianni will create a problem set by taking the problems \(2\), \(3\), \(4\), \(5\), \(7\), \(8\), \(9\), \(10\), \(11\) (which have beauty equal to \(10\) and all difficulties from \(1\) to \(9\)) and one of the problems \(1\) and \(6\) (which have both beauty \(3\) and difficulty \(10\)). The total beauty of the resulting problem set is \(10\cdot 9 + 3 = 93\).
Input: 238 49 36 7123 1010 110 210 310 43 1010 510 610 710 810 91 10 | Output: MOREPROBLEMS 93
Beginner
2
899
501
255
16
2,089
B1
2089B1
B1. Canteen (Easy Version)
1,900
binary search; data structures; flows; greedy; two pointers
This is the easy version of the problem. The difference between the versions is that in this version, \(k=0\). You can hack only if you solved all versions of this problem. Ecrade has two sequences \(a_0, a_1, \ldots, a_{n - 1}\) and \(b_0, b_1, \ldots, b_{n - 1}\) consisting of integers. It is guaranteed that the sum of all elements in \(a\) does not exceed the sum of all elements in \(b\).Initially, Ecrade can make exactly \(k\) changes to the sequence \(a\). It is guaranteed that \(k\) does not exceed the sum of \(a\). In each change: Choose an integer \(i\) (\(0 \le i < n\)) such that \(a_i > 0\), and perform \(a_i := a_i - 1\). Then Ecrade will perform the following three operations sequentially on \(a\) and \(b\), which constitutes one round of operations: For each \(0 \le i < n\): \(t := \min(a_i, b_i), a_i := a_i - t, b_i := b_i - t\); For each \(0 \le i < n\): \(c_i := a_{(i - 1) \bmod n}\); For each \(0 \le i < n\): \(a_i := c_i\); Ecrade wants to know the minimum number of rounds required for all elements in \(a\) to become equal to \(0\) after exactly \(k\) changes to \(a\).However, this seems a bit complicated, so please help him!
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 2\cdot 10^4\)). The description of the test cases follows. The first line of each test case contains two integers \(n\), \(k\) (\(1 \le n \le 2 \cdot 10^5\), \(k = 0\)).The second line of each test case contains \(n\) integers \(a_0, a_1, \ldots, a_{n - 1}\) (\(1 \le a_i \le 10^9\)).The third line of each test case contains \(n\) integers \(b_0, b_1, \ldots, b_{n - 1}\) (\(1 \le b_i \le 10^9\)).It is guaranteed that the sum of \(n\) across all test cases does not exceed \(2\cdot 10^5\). It is also guaranteed that in each test case the sum of \(a\) does not exceed the sum of \(b\), and that \(k\) does not exceed the sum of \(a\).
For each test case, output the minimum number of rounds required for all elements in \(a\) to become equal to \(0\) after exactly \(k\) changes to \(a\).
In this version, Ecrade cannot make changes to \(a\).In the first test case: After the first round, \(a=[0,0,0],b=[4,0,0]\). In the second test case: After the first round, \(a=[3,0,0,1],b=[3,1,0,0]\); After the second round, \(a=[1,0,0,0],b=[0,1,0,0]\); After the third round, \(a=[0,1,0,0],b=[0,1,0,0]\); After the fourth round, \(a=[0,0,0,0],b=[0,0,0,0]\).
Input: 43 01 1 45 1 44 01 2 3 44 3 2 14 02 1 1 21 2 2 18 01 2 3 4 5 6 7 88 7 6 5 4 3 2 1 | Output: 1 4 4 8
Hard
5
1,161
746
153
20
1,165
C
1165C
C. Good String
1,300
greedy
Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. Note that the empty string is considered good.You are given a string \(s\), you have to delete minimum number of characters from this string so that it becomes good.
The first line contains one integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the number of characters in \(s\).The second line contains the string \(s\), consisting of exactly \(n\) lowercase Latin letters.
In the first line, print one integer \(k\) (\(0 \le k \le n\)) β€” the minimum number of characters you have to delete from \(s\) to make it good.In the second line, print the resulting string \(s\). If it is empty, you may leave the second line blank, or not print it at all.
Input: 4 good | Output: 0 good
Easy
1
528
204
274
11
1,433
E
1433E
E. Two Round Dances
1,300
combinatorics; math
One day, \(n\) people (\(n\) is an even number) met on a plaza and made two round dances, each round dance consists of exactly \(\frac{n}{2}\) people. Your task is to find the number of ways \(n\) people can make two round dances if each round dance consists of exactly \(\frac{n}{2}\) people. Each person should belong to exactly one of these two round dances.Round dance is a dance circle consisting of \(1\) or more people. Two round dances are indistinguishable (equal) if one can be transformed to another by choosing the first participant. For example, round dances \([1, 3, 4, 2]\), \([4, 2, 1, 3]\) and \([2, 1, 3, 4]\) are indistinguishable.For example, if \(n=2\) then the number of ways is \(1\): one round dance consists of the first person and the second one of the second person.For example, if \(n=4\) then the number of ways is \(3\). Possible options: one round dance β€” \([1,2]\), another β€” \([3,4]\); one round dance β€” \([2,4]\), another β€” \([3,1]\); one round dance β€” \([4,1]\), another β€” \([3,2]\). Your task is to find the number of ways \(n\) people can make two round dances if each round dance consists of exactly \(\frac{n}{2}\) people.
The input contains one integer \(n\) (\(2 \le n \le 20\)), \(n\) is an even number.
Print one integer β€” the number of ways to make two round dances. It is guaranteed that the answer fits in the \(64\)-bit integer data type.
Input: 2 | Output: 1
Easy
2
1,161
83
139
14
1,207
B
1207B
B. Square Filling
1,200
constructive algorithms; greedy; implementation
You are given two matrices \(A\) and \(B\). Each matrix contains exactly \(n\) rows and \(m\) columns. Each element of \(A\) is either \(0\) or \(1\); each element of \(B\) is initially \(0\).You may perform some operations with matrix \(B\). During each operation, you choose any submatrix of \(B\) having size \(2 \times 2\), and replace every element in the chosen submatrix with \(1\). In other words, you choose two integers \(x\) and \(y\) such that \(1 \le x < n\) and \(1 \le y < m\), and then set \(B_{x, y}\), \(B_{x, y + 1}\), \(B_{x + 1, y}\) and \(B_{x + 1, y + 1}\) to \(1\).Your goal is to make matrix \(B\) equal to matrix \(A\). Two matrices \(A\) and \(B\) are equal if and only if every element of matrix \(A\) is equal to the corresponding element of matrix \(B\).Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes \(B\) equal to \(A\). Note that you don't have to minimize the number of operations.
The first line contains two integers \(n\) and \(m\) (\(2 \le n, m \le 50\)).Then \(n\) lines follow, each containing \(m\) integers. The \(j\)-th integer in the \(i\)-th line is \(A_{i, j}\). Each integer is either \(0\) or \(1\).
If it is impossible to make \(B\) equal to \(A\), print one integer \(-1\).Otherwise, print any sequence of operations that transforms \(B\) into \(A\) in the following format: the first line should contain one integer \(k\) β€” the number of operations, and then \(k\) lines should follow, each line containing two integers \(x\) and \(y\) for the corresponding operation (set \(B_{x, y}\), \(B_{x, y + 1}\), \(B_{x + 1, y}\) and \(B_{x + 1, y + 1}\) to \(1\)). The condition \(0 \le k \le 2500\) should hold.
The sequence of operations in the first example: \(\begin{matrix} 0 & 0 & 0 & & 1 & 1 & 0 & & 1 & 1 & 1 & & 1 & 1 & 1 \\ 0 & 0 & 0 & \rightarrow & 1 & 1 & 0 & \rightarrow & 1 & 1 & 1 & \rightarrow & 1 & 1 & 1 \\ 0 & 0 & 0 & & 0 & 0 & 0 & & 0 & 0 & 0 & & 0 & 1 & 1 \end{matrix}\)
Input: 3 3 1 1 1 1 1 1 0 1 1 | Output: 3 1 1 1 2 2 2
Easy
3
984
231
508
12
258
D
258D
D. Little Elephant and Broken Sorting
2,600
dp; math; probabilities
The Little Elephant loves permutations of integers from 1 to n very much. But most of all he loves sorting them. To sort a permutation, the Little Elephant repeatedly swaps some elements. As a result, he must receive a permutation 1, 2, 3, ..., n.This time the Little Elephant has permutation p1, p2, ..., pn. Its sorting program needs to make exactly m moves, during the i-th move it swaps elements that are at that moment located at the ai-th and the bi-th positions. But the Little Elephant's sorting program happened to break down and now on every step it can equiprobably either do nothing or swap the required elements.Now the Little Elephant doesn't even hope that the program will sort the permutation, but he still wonders: if he runs the program and gets some permutation, how much will the result of sorting resemble the sorted one? For that help the Little Elephant find the mathematical expectation of the number of permutation inversions after all moves of the program are completed.We'll call a pair of integers i, j (1 ≀ i < j ≀ n) an inversion in permutatuon p1, p2, ..., pn, if the following inequality holds: pi > pj.
The first line contains two integers n and m (1 ≀ n, m ≀ 1000, n > 1) β€” the permutation size and the number of moves. The second line contains n distinct integers, not exceeding n β€” the initial permutation. Next m lines each contain two integers: the i-th line contains integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi) β€” the positions of elements that were changed during the i-th move.
In the only line print a single real number β€” the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10 - 6.
Input: 2 11 21 2 | Output: 0.500000000
Expert
3
1,136
382
168
2
598
D
598D
D. Igor In the Museum
1,700
dfs and similar; graphs; shortest paths
Igor is in the museum and he wants to see as many pictures as possible.Museum can be represented as a rectangular field of n Γ— m cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture.At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one.For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see.
First line of the input contains three integers n, m and k (3 ≀ n, m ≀ 1000, 1 ≀ k ≀ min(nΒ·m, 100 000)) β€” the museum dimensions and the number of starting positions to process.Each of the next n lines contains m symbols '.', '*' β€” the description of the museum. It is guaranteed that all border cells are impassable, so Igor can't go out from the museum.Each of the last k lines contains two integers x and y (1 ≀ x ≀ n, 1 ≀ y ≀ m) β€” the row and the column of one of Igor's starting positions respectively. Rows are numbered from top to bottom, columns β€” from left to right. It is guaranteed that all starting positions are empty cells.
Print k integers β€” the maximum number of pictures, that Igor can see if he starts in corresponding position.
Input: 5 6 3*******..*.********....*******2 22 54 3 | Output: 6410
Medium
3
767
636
108
5
1,351
B
1351B
B. Square?
900
brute force; implementation; math
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles.
The first line contains an integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases in the input. Then \(t\) test cases follow.Each test case is given in two lines.The first line contains two integers \(a_1\) and \(b_1\) (\(1 \le a_1, b_1 \le 100\)) β€” the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).The second line contains two integers \(a_2\) and \(b_2\) (\(1 \le a_2, b_2 \le 100\)) β€” the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).
Print \(t\) answers, each of which is a string ""YES"" (in the case of a positive answer) or ""NO"" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower).
Input: 3 2 3 3 1 3 2 1 3 3 3 1 3 | Output: Yes Yes No
Beginner
3
328
751
201
13
21
D
21D
D. Traveling Graph
2,400
bitmasks; graph matchings; graphs
You are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself).
The first line of the input contains two integers n and m (1 ≀ n ≀ 15, 0 ≀ m ≀ 2000), n is the amount of vertices, and m is the amount of edges. Following m lines contain edges as a triples x, y, w (1 ≀ x, y ≀ n, 1 ≀ w ≀ 10000), x, y are edge endpoints, and w is the edge length.
Output minimal cycle length or -1 if it doesn't exists.
Input: 3 31 2 12 3 13 1 1 | Output: 3
Expert
3
263
279
55
0
549
F
549F
F. Yura and Developers
2,800
data structures; divide and conquer
Yura has a team of k developers and a list of n tasks numbered from 1 to n. Yura is going to choose some tasks to be done this week. Due to strange Looksery habits the numbers of chosen tasks should be a segment of consecutive integers containing no less than 2 numbers, i. e. a sequence of form l, l + 1, ..., r for some 1 ≀ l < r ≀ n. Every task i has an integer number ai associated with it denoting how many man-hours are required to complete the i-th task. Developers are not self-confident at all, and they are actually afraid of difficult tasks. Knowing that, Yura decided to pick up a hardest task (the one that takes the biggest number of man-hours to be completed, among several hardest tasks with same difficulty level he chooses arbitrary one) and complete it on his own. So, if tasks with numbers [l, r] are chosen then the developers are left with r - l tasks to be done by themselves. Every developer can spend any integer amount of hours over any task, but when they are done with the whole assignment there should be exactly ai man-hours spent over the i-th task. The last, but not the least problem with developers is that one gets angry if he works more than another developer. A set of tasks [l, r] is considered good if it is possible to find such a distribution of work that allows to complete all the tasks and to have every developer working for the same amount of time (amount of work performed by Yura doesn't matter for other workers as well as for him).For example, let's suppose that Yura have chosen tasks with following difficulties: a = [1, 2, 3, 4], and he has three developers in his disposal. He takes the hardest fourth task to finish by himself, and the developers are left with tasks with difficulties [1, 2, 3]. If the first one spends an hour on the first task and an hour on the third one, the second developer spends two hours on the second task and the third developer spends two hours on the third task, then they are done, since every developer worked exactly for two hours and every task has been worked over for the required amount of time. As another example, if the first task required two hours instead of one to be completed then it would be impossible to assign the tasks in a way described above. Besides work, Yura is fond of problem solving. He wonders how many pairs (l, r) (1 ≀ l < r ≀ n) exists such that a segment [l, r] is good? Yura has already solved this problem, but he has no time to write the code. Please, help Yura and implement the solution for this problem.
The first line of input contains two positive integers: n and k (1 ≀ n ≀ 300 000, 1 ≀ k ≀ 1 000 000), the number of tasks in the list and the number of developers in Yura's disposal. The second line contains n integers ai (1 ≀ ai ≀ 109).
Output a single integer β€” the number of pairs (l, r) satisfying the conditions from the statement.
In the first sample there are three good segments: [1;3] β€” the hardest task requires 3 man-hours, so there are tasks left that require 1 and 2 man-hours. A solution is to make first developer work on the first task for an hour, while second and third developers work on the second task. Each developer works exactly one hour. [1;4] β€” the hardest task requires 4 man-hours, so there are tasks left that require 1, 2 and 3 man-hours. If the first developer spends an hour on the first task and an hour on the third one, the second developer spends two hours on the second task and the third developer spends two hours on the third task, then they are done, since every developer worked exactly for two hours. [3;4] β€” the hardest task requires 4 man-hours, so there is only one task left that requires 3 man-hours. A solution is to make each developer work for an hour.
Input: 4 31 2 3 4 | Output: 3
Master
2
2,527
237
98
5
1,263
A
1263A
A. Sweet Problem
1,100
math
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are \(r\) candies in it, the second pile contains only green candies and there are \(g\) candies in it, the third pile contains only blue candies and there are \(b\) candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
The first line contains integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases in the input. Then \(t\) test cases follow.Each test case is given as a separate line of the input. It contains three integers \(r\), \(g\) and \(b\) (\(1 \le r, g, b \le 10^8\)) β€” the number of red, green and blue candies, respectively.
Print \(t\) integers: the \(i\)-th printed integer is the answer on the \(i\)-th test case in the input.
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Input: 6 1 1 1 1 2 1 4 1 1 7 4 10 8 1 4 8 2 8 | Output: 1 2 2 10 5 9
Easy
1
586
325
104
12
815
E
815E
E. Karen and Neighborhood
2,900
binary search; constructive algorithms; implementation
It's been long after the events of the previous problems, and Karen has now moved on from student life and is looking to relocate to a new neighborhood. The neighborhood consists of n houses in a straight line, labelled 1 to n from left to right, all an equal distance apart.Everyone in this neighborhood loves peace and quiet. Because of this, whenever a new person moves into the neighborhood, he or she always chooses the house whose minimum distance to any occupied house is maximized. If there are multiple houses with the maximum possible minimum distance, he or she chooses the leftmost one.Note that the first person to arrive always moves into house 1.Karen is the k-th person to enter this neighborhood. If everyone, including herself, follows this rule, which house will she move into?
The first and only line of input contains two integers, n and k (1 ≀ k ≀ n ≀ 1018), describing the number of houses in the neighborhood, and that Karen was the k-th person to move in, respectively.
Output a single integer on a line by itself, the label of the house Karen will move into.
In the first test case, there are 6 houses in the neighborhood, and Karen is the fourth person to move in: The first person moves into house 1. The second person moves into house 6. The third person moves into house 3. The fourth person moves into house 2. In the second test case, there are 39 houses in the neighborhood, and Karen is the third person to move in: The first person moves into house 1. The second person moves into house 39. The third person moves into house 20.
Input: 6 4 | Output: 2
Master
3
796
197
89
8
1,485
D
1485D
D. Multiples and Power Differences
2,200
constructive algorithms; graphs; math; number theory
You are given a matrix \(a\) consisting of positive integers. It has \(n\) rows and \(m\) columns.Construct a matrix \(b\) consisting of positive integers. It should have the same size as \(a\), and the following conditions should be met: \(1 \le b_{i,j} \le 10^6\); \(b_{i,j}\) is a multiple of \(a_{i,j}\); the absolute value of the difference between numbers in any adjacent pair of cells (two cells that share the same side) in \(b\) is equal to \(k^4\) for some integer \(k \ge 1\) (\(k\) is not necessarily the same for all pairs, it is own for each pair). We can show that the answer always exists.
The first line contains two integers \(n\) and \(m\) (\(2 \le n,m \le 500\)).Each of the following \(n\) lines contains \(m\) integers. The \(j\)-th integer in the \(i\)-th line is \(a_{i,j}\) (\(1 \le a_{i,j} \le 16\)).
The output should contain \(n\) lines each containing \(m\) integers. The \(j\)-th integer in the \(i\)-th line should be \(b_{i,j}\).
In the first example, the matrix \(a\) can be used as the matrix \(b\), because the absolute value of the difference between numbers in any adjacent pair of cells is \(1 = 1^4\).In the third example: \(327\) is a multiple of \(3\), \(583\) is a multiple of \(11\), \(408\) is a multiple of \(12\), \(664\) is a multiple of \(8\); \(|408 - 327| = 3^4\), \(|583 - 327| = 4^4\), \(|664 - 408| = 4^4\), \(|664 - 583| = 3^4\).
Input: 2 2 1 2 2 3 | Output: 1 2 2 3
Hard
4
605
220
134
14
70
B
70B
B. Text Messaging
1,600
expression parsing; greedy; strings
Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split!Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).The little walrus's text looks in the following manner: TEXT ::= SENTENCE | SENTENCE SPACE TEXTSENTENCE ::= WORD SPACE SENTENCE | WORD ENDEND ::= {'.', '?', '!'}WORD ::= LETTER | LETTER WORDLETTER ::= {'a'..'z', 'A'..'Z'}SPACE ::= ' 'SPACE stands for the symbol of a space.So, how many messages did Fangy send?
The first line contains an integer n, which is the size of one message (2 ≀ n ≀ 255). The second line contains the text. The length of the text does not exceed 104 characters. It is guaranteed that the text satisfies the above described format. Specifically, this implies that the text is not empty.
On the first and only line print the number of text messages Fangy will need. If it is impossible to split the text, print ""Impossible"" without the quotes.
Let's take a look at the third sample. The text will be split into three messages: ""Hello!"", ""Do you like fish?"" and ""Why?"".
Input: 25Hello. I am a little walrus. | Output: 2
Medium
3
956
299
157
0
1,721
F
1721F
F. Matching Reduction
2,800
brute force; constructive algorithms; dfs and similar; flows; graph matchings; graphs; interactive
You are given a bipartite graph with \(n_1\) vertices in the first part, \(n_2\) vertices in the second part, and \(m\) edges. The maximum matching in this graph is the maximum possible (by size) subset of edges of this graph such that no vertex is incident to more than one chosen edge.You have to process two types of queries to this graph: \(1\) β€” remove the minimum possible number of vertices from this graph so that the size of the maximum matching gets reduced exactly by \(1\), and print the vertices that you have removed. Then, find any maximum matching in this graph and print the sum of indices of edges belonging to this matching; \(2\) β€” query of this type will be asked only after a query of type \(1\). As the answer to this query, you have to print the edges forming the maximum matching you have chosen in the previous query. Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.
The first line contains four integers \(n_1\), \(n_2\), \(m\) and \(q\) (\(1 \le n_1, n_2 \le 2 \cdot 10^5\); \(1 \le m \le \min(n_1 \cdot n_2, 2 \cdot 10^5)\); \(1 \le q \le 2 \cdot 10^5\)).Then \(m\) lines follow. The \(i\)-th of them contains two integers \(x_i\) and \(y_i\) (\(1 \le x_i \le n_1\); \(1 \le y_i \le n_2\)) meaning that the \(i\)-th edge connects the vertex \(x_i\) in the first part and the vertex \(y_i\) in the second part. There are no pairs of vertices that are connected by more than one edge.Then \(q\) lines follow. The \(i\)-th of them contains one integer, \(1\) or \(2\), denoting the \(i\)-th query. Additional constraints on queries: the number of queries of type \(1\) won't exceed the size of the maximum matching in the initial graph; the number of queries of type \(2\) won't exceed \(3\); each query of type \(2\) is preceded by a query of type \(1\); your solution is allowed to read the \(i\)-th query only after printing the answer for the \((i-1)\)-th query and flushing the output.
For a query of type \(1\), print the answer in three lines as follows: the first line should contain the number of vertices you remove; the second line should contain the indices of vertices you remove, as follows: if you remove the vertex \(x\) from the left part, print \(x\); if you remove the vertex \(y\) from the right part, print \(-y\) (negative index); the third line should contain the sum of indices of edges in some maximum matching in the resulting graph. The edges are numbered from \(1\) to \(m\). For a query of type \(2\), print the answer in two lines as follows: the first line should contain the size of the maximum matching; the second line should contain the indices of the edges belonging to the maximum matching. Note that the sum of these indices should be equal to the number you printed at the end of the previous query of type \(1\); After printing the answer to a query, don't forget to flush the output.
In this problem, you may receive the verdict ""Idleness Limit Exceeded"" since it is in online mode. If it happens, it means that either the output format is wrong, or you don't meet some constraint of the problem. You may treat this verdict as ""Wrong Answer"".For your convenience, the output for queries in the example is separated by the line ===. Don't print this line in your program, it is done only to make sure that it's easy to distinguish between answers for different queries in the statement.
Input: 3 4 4 4 2 2 1 3 2 1 3 4 1 2 1 2 | Output: 1 -4 3 === 2 1 2 === 1 2 2 === 1 2
Master
7
1,133
1,023
933
17
1,656
A
1656A
A. Good Pairs
800
math; sortings
You are given an array \(a_1, a_2, \ldots, a_n\) of positive integers. A good pair is a pair of indices \((i, j)\) with \(1 \leq i, j \leq n\) such that, for all \(1 \leq k \leq n\), the following equality holds:$$$\( |a_i - a_k| + |a_k - a_j| = |a_i - a_j|, \)\( where \)|x|\( denotes the absolute value of \)x\(.Find a good pair. Note that \)i\( can be equal to \)j$$$.
The input consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 1000\)) β€” the number of test cases. Description of the test cases follows.The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 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 \leq a_i \leq 10^9\)) where \(a_i\) is the \(i\)-th element of the array.The sum of \(n\) for all test cases is at most \(2 \cdot 10^5\).
For each test case, print a single line with two space-separated indices \(i\) and \(j\) which form a good pair of the array. The case \(i=j\) is allowed. It can be shown that such a pair always exists. If there are multiple good pairs, print any of them.
In the first case, for \(i = 2\) and \(j = 3\) the equality holds true for all \(k\): \(k = 1\): \(|a_2 - a_1| + |a_1 - a_3| = |2 - 5| + |5 - 7| = 5 = |2 - 7| = |a_2-a_3|\), \(k = 2\): \(|a_2 - a_2| + |a_2 - a_3| = |2 - 2| + |2 - 7| = 5 = |2 - 7| = |a_2-a_3|\), \(k = 3\): \(|a_2 - a_3| + |a_3 - a_3| = |2 - 7| + |7 - 7| = 5 = |2 - 7| = |a_2-a_3|\).
Input: 335 2 751 4 2 2 312 | Output: 2 3 1 2 1 1
Beginner
2
371
517
255
16
1,162
A
1162A
A. Zoning Restrictions Again
800
implementation
You are planning to build housing on a street. There are \(n\) spots available on the street on which you can build a house. The spots are labeled from \(1\) to \(n\) from left to right. In each spot, you can build a house with an integer height between \(0\) and \(h\).In each spot, if a house has height \(a\), you will gain \(a^2\) dollars from it.The city has \(m\) zoning restrictions. The \(i\)-th restriction says that the tallest house from spots \(l_i\) to \(r_i\) (inclusive) must be at most \(x_i\).You would like to build houses to maximize your profit. Determine the maximum profit possible.
The first line contains three integers \(n\), \(h\), and \(m\) (\(1 \leq n,h,m \leq 50\)) β€” the number of spots, the maximum height, and the number of restrictions.Each of the next \(m\) lines contains three integers \(l_i\), \(r_i\), and \(x_i\) (\(1 \leq l_i \leq r_i \leq n\), \(0 \leq x_i \leq h\)) β€” left and right limits (inclusive) of the \(i\)-th restriction and the maximum possible height in that range.
Print a single integer, the maximum profit you can make.
In the first example, there are \(3\) houses, the maximum height of a house is \(3\), and there are \(3\) restrictions. The first restriction says the tallest house between \(1\) and \(1\) must be at most \(1\). The second restriction says the tallest house between \(2\) and \(2\) must be at most \(3\). The third restriction says the tallest house between \(3\) and \(3\) must be at most \(2\).In this case, it is optimal to build houses with heights \([1, 3, 2]\). This fits within all the restrictions. The total profit in this case is \(1^2 + 3^2 + 2^2 = 14\).In the second example, there are \(4\) houses, the maximum height of a house is \(10\), and there are \(2\) restrictions. The first restriction says the tallest house from \(2\) to \(3\) must be at most \(8\). The second restriction says the tallest house from \(3\) to \(4\) must be at most \(7\).In this case, it's optimal to build houses with heights \([10, 8, 7, 7]\). We get a profit of \(10^2+8^2+7^2+7^2 = 262\). Note that there are two restrictions on house \(3\) and both of them must be satisfied. Also, note that even though there isn't any explicit restrictions on house \(1\), we must still limit its height to be at most \(10\) (\(h=10\)).
Input: 3 3 3 1 1 1 2 2 3 3 3 2 | Output: 14
Beginner
1
604
413
56
11
266
A
266A
A. Stones on the Table
800
implementation
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
The first line contains integer n (1 ≀ n ≀ 50) β€” the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals ""R"", if the i-th stone is red, ""G"", if it's green and ""B"", if it's blue.
Print a single integer β€” the answer to the problem.
Input: 3RRG | Output: 1
Beginner
1
282
349
51
2
1,041
C
1041C
C. Coffee Break
1,600
binary search; data structures; greedy; two pointers
Recently Monocarp got a job. His working day lasts exactly \(m\) minutes. During work, Monocarp wants to drink coffee at certain moments: there are \(n\) minutes \(a_1, a_2, \dots, a_n\), when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute). However, Monocarp's boss doesn't like when Monocarp takes his coffee breaks too often. So for the given coffee break that is going to be on minute \(a_i\), Monocarp must choose the day in which he will drink coffee during the said minute, so that every day at least \(d\) minutes pass between any two coffee breaks. Monocarp also wants to take these \(n\) coffee breaks in a minimum possible number of working days (he doesn't count days when he is not at work, and he doesn't take coffee breaks on such days). Take into account that more than \(d\) minutes pass between the end of any working day and the start of the following working day.For each of the \(n\) given minutes determine the day, during which Monocarp should take a coffee break in this minute. You have to minimize the number of days spent.
The first line contains three integers \(n\), \(m\), \(d\) \((1 \le n \le 2\cdot10^{5}, n \le m \le 10^{9}, 1 \le d \le m)\) β€” the number of coffee breaks Monocarp wants to have, the length of each working day, and the minimum number of minutes between any two consecutive coffee breaks.The second line contains \(n\) distinct integers \(a_1, a_2, \dots, a_n\) \((1 \le a_i \le m)\), where \(a_i\) is some minute when Monocarp wants to have a coffee break.
In the first line, write the minimum number of days required to make a coffee break in each of the \(n\) given minutes. In the second line, print \(n\) space separated integers. The \(i\)-th of integers should be the index of the day during which Monocarp should have a coffee break at minute \(a_i\). Days are numbered from \(1\). If there are multiple optimal solutions, you may print any of them.
In the first example, Monocarp can take two coffee breaks during the first day (during minutes \(1\) and \(5\), \(3\) minutes will pass between these breaks). One break during the second day (at minute \(2\)), and one break during the third day (at minute \(3\)).In the second example, Monocarp can determine the day of the break as follows: if the minute when he wants to take a break is odd, then this break is on the first day, if it is even, then this break is on the second day.
Input: 4 5 33 5 1 2 | Output: 33 1 1 2
Medium
4
1,139
456
399
10
1,080
E
1080E
E. Sonya and Matrix Beauty
2,400
strings
Sonya had a birthday recently. She was presented with the matrix of size \(n\times m\) and consist of lowercase Latin letters. We assume that the rows are numbered by integers from \(1\) to \(n\) from bottom to top, and the columns are numbered from \(1\) to \(m\) from left to right. Let's call a submatrix \((i_1, j_1, i_2, j_2)\) \((1\leq i_1\leq i_2\leq n; 1\leq j_1\leq j_2\leq m)\) elements \(a_{ij}\) of this matrix, such that \(i_1\leq i\leq i_2\) and \(j_1\leq j\leq j_2\). Sonya states that a submatrix is beautiful if we can independently reorder the characters in each row (not in column) so that all rows and columns of this submatrix form palidroms. Let's recall that a string is called palindrome if it reads the same from left to right and from right to left. For example, strings \(abacaba, bcaacb, a\) are palindromes while strings \(abca, acbba, ab\) are not.Help Sonya to find the number of beautiful submatrixes. Submatrixes are different if there is an element that belongs to only one submatrix.
The first line contains two integers \(n\) and \(m\) \((1\leq n, m\leq 250)\) β€” the matrix dimensions.Each of the next \(n\) lines contains \(m\) lowercase Latin letters.
Print one integer β€” the number of beautiful submatrixes.
In the first example, the following submatrixes are beautiful: \(((1, 1), (1, 1)); ((1, 2), (1, 2));\) \(((1, 3), (1, 3)); ((1, 1), (1, 3))\).In the second example, all submatrixes that consist of one element and the following are beautiful: \(((1, 1), (2, 1));\) \(((1, 1), (1, 3)); ((2, 1), (2, 3)); ((1, 1), (2, 3)); ((2, 1), (2, 2))\).Some of the beautiful submatrixes are: \(((1, 1), (1, 5)); ((1, 2), (3, 4));\) \(((1, 1), (3, 5))\).The submatrix \(((1, 1), (3, 5))\) is beautiful since it can be reordered as:acccaaabaaacccaIn such a matrix every row and every column form palindromes.
Input: 1 3 aba | Output: 4
Expert
1
1,018
170
56
10
1,862
D
1862D
D. Ice Cream Balls
1,300
binary search; combinatorics; constructive algorithms; math
Tema decided to improve his ice cream making skills. He has already learned how to make ice cream in a cone using exactly two balls.Before his ice cream obsession, Tema was interested in mathematics. Therefore, he is curious about the minimum number of balls he needs to have in order to make exactly \(n\) different types of ice cream.There are plenty possible ice cream flavours: \(1, 2, 3, \dots\). Tema can make two-balls ice cream with any flavours (probably the same).Two ice creams are considered different if their sets of ball flavours are different. For example, \(\{1, 2\} = \{2, 1\}\), but \(\{1, 1\} \neq \{1, 2\}\).For example, having the following ice cream balls: \(\{1, 1, 2\}\), Tema can make only two types of ice cream: \(\{1, 1\}\) and \(\{1, 2\}\).Note, that Tema do not need to make all the ice cream cones at the same time. This means that he making ice cream cones independently. Also in order to make a following cone \(\{x, x\}\) for some \(x\), Tema needs at least \(2\) balls of type \(x\).Help Tema answer this question. It can be shown that answer always exist.
Each test consists of multiple test cases. The first line of input contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. Then follows the description of the test cases.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^{18}\)) β€” the number of ice cream types that Tema wants to make.
For each test case, output a single integer β€” the minimum number of balls Tema needs to buy.
In the first sample, it is enough to have following balls types: \(\{1, 1\}\). Note, that set \(\{1\}\) if not enough since we need at least \(2\) balls of a type \(1\) in order to make such cone \(\{1, 1\}\).In the second sample, it is not possible to make it with \(2\) balls, but it can be done with these balls: \(\{1, 2, 3\}\).In the third sample, \(\{1, 2, 3, 4\}\) is optimal answer, so we can get following ice cream cones: \(\{1, 2\}\), \(\{1, 3\}\), \(\{1, 4\}\), \(\{2, 3\}\), \(\{2, 4\}\), \(\{3, 4\}\).
Input: 51361791000000000000000000 | Output: 2 3 4 27 2648956421
Easy
4
1,092
344
92
18
1,106
B
1106B
B. Lunar New Year and Food Ordering
1,500
data structures; implementation
Lunar New Year is approaching, and Bob is planning to go for a famous restaurant β€” ""Alice's"".The restaurant ""Alice's"" serves \(n\) kinds of food. The cost for the \(i\)-th kind is always \(c_i\). Initially, the restaurant has enough ingredients for serving exactly \(a_i\) dishes of the \(i\)-th kind. In the New Year's Eve, \(m\) customers will visit Alice's one after another and the \(j\)-th customer will order \(d_j\) dishes of the \(t_j\)-th kind of food. The \((i + 1)\)-st customer will only come after the \(i\)-th customer is completely served.Suppose there are \(r_i\) dishes of the \(i\)-th kind remaining (initially \(r_i = a_i\)). When a customer orders \(1\) dish of the \(i\)-th kind, the following principles will be processed. If \(r_i > 0\), the customer will be served exactly \(1\) dish of the \(i\)-th kind. The cost for the dish is \(c_i\). Meanwhile, \(r_i\) will be reduced by \(1\). Otherwise, the customer will be served \(1\) dish of the cheapest available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by \(1\). If there are no more dishes at all, the customer will leave angrily. Therefore, no matter how many dishes are served previously, the cost for the customer is \(0\).If the customer doesn't leave after the \(d_j\) dishes are served, the cost for the customer will be the sum of the cost for these \(d_j\) dishes.Please determine the total cost for each of the \(m\) customers.
The first line contains two integers \(n\) and \(m\) (\(1 \leq n, m \leq 10^5\)), representing the number of different kinds of food and the number of customers, respectively.The second line contains \(n\) positive integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 10^7\)), where \(a_i\) denotes the initial remain of the \(i\)-th kind of dishes.The third line contains \(n\) positive integers \(c_1, c_2, \ldots, c_n\) (\(1 \leq c_i \leq 10^6\)), where \(c_i\) denotes the cost of one dish of the \(i\)-th kind.The following \(m\) lines describe the orders of the \(m\) customers respectively. The \(j\)-th line contains two positive integers \(t_j\) and \(d_j\) (\(1 \leq t_j \leq n\), \(1 \leq d_j \leq 10^7\)), representing the kind of food and the number of dishes the \(j\)-th customer orders, respectively.
Print \(m\) lines. In the \(j\)-th line print the cost for the \(j\)-th customer.
In the first sample, \(5\) customers will be served as follows. Customer \(1\) will be served \(6\) dishes of the \(2\)-nd kind, \(1\) dish of the \(4\)-th kind, and \(1\) dish of the \(6\)-th kind. The cost is \(6 \cdot 3 + 1 \cdot 2 + 1 \cdot 2 = 22\). The remain of the \(8\) kinds of food will be \(\{8, 0, 2, 0, 4, 4, 7, 5\}\). Customer \(2\) will be served \(4\) dishes of the \(1\)-st kind. The cost is \(4 \cdot 6 = 24\). The remain will be \(\{4, 0, 2, 0, 4, 4, 7, 5\}\). Customer \(3\) will be served \(4\) dishes of the \(6\)-th kind, \(3\) dishes of the \(8\)-th kind. The cost is \(4 \cdot 2 + 3 \cdot 2 = 14\). The remain will be \(\{4, 0, 2, 0, 4, 0, 7, 2\}\). Customer \(4\) will be served \(2\) dishes of the \(3\)-rd kind, \(2\) dishes of the \(8\)-th kind. The cost is \(2 \cdot 3 + 2 \cdot 2 = 10\). The remain will be \(\{4, 0, 0, 0, 4, 0, 7, 0\}\). Customer \(5\) will be served \(7\) dishes of the \(7\)-th kind, \(3\) dishes of the \(1\)-st kind. The cost is \(7 \cdot 3 + 3 \cdot 6 = 39\). The remain will be \(\{1, 0, 0, 0, 4, 0, 0, 0\}\).In the second sample, each customer is served what they order except the last one, who leaves angrily without paying. For example, the second customer is served \(6\) dishes of the second kind, so the cost is \(66 \cdot 6 = 396\).In the third sample, some customers may not be served what they order. For example, the second customer is served \(6\) dishes of the second kind, \(6\) of the third and \(1\) of the fourth, so the cost is \(66 \cdot 6 + 666 \cdot 6 + 6666 \cdot 1 = 11058\).
Input: 8 5 8 6 2 1 4 5 7 5 6 3 3 2 6 2 3 2 2 8 1 4 4 7 3 4 6 10 | Output: 22 24 14 10 39
Medium
2
1,621
817
81
11
1,992
F
1992F
F. Valuable Cards
1,900
brute force; dp; greedy; number theory; two pointers
In his favorite cafe Kmes once again wanted to try the herring under a fur coat. Previously, it would not have been difficult for him to do this, but the cafe recently introduced a new purchasing policy.Now, in order to make a purchase, Kmes needs to solve the following problem: \(n\) cards with prices for different positions are laid out in front of him, on the \(i\)-th card there is an integer \(a_i\), among these prices there is no whole positive integer \(x\).Kmes is asked to divide these cards into the minimum number of bad segments (so that each card belongs to exactly one segment). A segment is considered bad if it is impossible to select a subset of cards with a product equal to \(x\). All segments, in which Kmes will divide the cards, must be bad.Formally, the segment \((l, r)\) is bad if there are no indices \(i_1 < i_2 < \ldots < i_k\) such that \(l \le i_1, i_k \le r\), and \(a_{i_1} \cdot a_{i_2} \ldots \cdot a_{i_k} = x\).Help Kmes determine the minimum number of bad segments in order to enjoy his favorite dish.
The first line contains a single integer \(t\) (\(1 \le t \le 10^3\)) β€” the number of test cases.The first line of each set of input data gives you \(2\) integers \(n\) and \(x\) (\(1 \le n \le 10^5, 2 \le x \le 10^5\)) β€” the number of cards and the integer, respectively.The second line of each set of input data contains \(n\) integers \(a_i\) (\(1 \le a_i \le 2 \cdot 10^5, a_i \neq x\)) β€” the prices on the cards.It is guaranteed that the sum of \(n\) over all sets of test data does not exceed \(10^5\).
For each set of input data, output the minimum number of bad segments.
Input: 86 42 3 6 2 1 29 10000050000 25000 12500 6250 3125 2 4 8 165 21 1 1 1 18 64 3 4 3 4 3 4 37 126 11 1 3 11 10 210 52 4 4 2 4 4 4 3 1 17 84 6 5 1 2 4 18 273 9 17 26 2 20 9 3 | Output: 3 2 1 1 2 1 3 3
Hard
5
1,041
508
70
19
706
E
706E
E. Working routine
2,500
data structures; implementation
Vasiliy finally got to work, where there is a huge amount of tasks waiting for him. Vasiliy is given a matrix consisting of n rows and m columns and q tasks. Each task is to swap two submatrices of the given matrix.For each task Vasiliy knows six integers ai, bi, ci, di, hi, wi, where ai is the index of the row where the top-left corner of the first rectangle is located, bi is the index of its column, ci is the index of the row of the top-left corner of the second rectangle, di is the index of its column, hi is the height of the rectangle and wi is its width.It's guaranteed that two rectangles in one query do not overlap and do not touch, that is, no cell belongs to both rectangles, and no two cells belonging to different rectangles share a side. However, rectangles are allowed to share an angle.Vasiliy wants to know how the matrix will look like after all tasks are performed.
The first line of the input contains three integers n, m and q (2 ≀ n, m ≀ 1000, 1 ≀ q ≀ 10 000) β€” the number of rows and columns in matrix, and the number of tasks Vasiliy has to perform.Then follow n lines containing m integers vi, j (1 ≀ vi, j ≀ 109) each β€” initial values of the cells of the matrix.Each of the following q lines contains six integers ai, bi, ci, di, hi, wi (1 ≀ ai, ci, hi ≀ n, 1 ≀ bi, di, wi ≀ m).
Print n lines containing m integers each β€” the resulting matrix.
Input: 4 4 21 1 2 21 1 2 23 3 4 43 3 4 41 1 3 3 2 23 1 1 3 2 2 | Output: 4 4 3 34 4 3 32 2 1 12 2 1 1
Expert
2
889
419
64
7
1,990
E2
1990E2
E2. Catch the Mole(Hard Version)
2,600
binary search; data structures; dfs and similar; divide and conquer; interactive; trees
This is the hard version of the problem. The only difference is the limit on the number of queries.This is an interactive problem.You are given a tree of \(n\) nodes with node \(1\) as its root node.There is a hidden mole in one of the nodes. To find its position, you can pick an integer \(x\) (\(1 \le x \le n\)) to make an inquiry to the jury. Next, the jury will return \(1\) when the mole is in subtree \(x\). Otherwise, the judge will return \(0\). If the judge returns \(0\) and the mole is not in root node \(1\), the mole will move to the parent node of the node it is currently on.Use at most \(160\) operations to find the current node where the mole is located.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 100\)). The description of the test cases follows.
In the first test case, the mole is in node \(2\) initially.For the query ""? 2"", the jury returns \(1\) because the mole is in subtree \(2\). After this query, the mole does not move.The answer \(2\) is the current node where the mole is located, so the answer is considered correct.In the second test case, the mole is in node \(6\) initially.For the query ""? 2"", the jury returns \(0\) because the mole is not in subtree \(2\). After this query, the mole moves from node \(6\) to node \(5\).For the query ""? 6"", the jury returns \(0\) because the mole is not in subtree \(6\). After this query, the mole moves from node \(5\) to node \(4\).For the query ""? 4"", the jury returns \(1\) because the mole is in subtree \(4\). After this query, the mole does not move.The answer \(4\) is the current node where the mole is located, so the answer is considered correct.Please note that the example is only for understanding the statement, and the queries in the example do not guarantee to determine the unique position of the mole.
Input: 2 2 1 2 1 6 1 2 1 3 1 4 4 5 5 6 0 0 1 | Output: ? 2 ! 2 ? 2 ? 6 ? 4 ! 4
Expert
6
673
160
0
19
1,420
C1
1420C1
C1. PokΓ©mon Army (easy version)
1,300
constructive algorithms; dp; greedy
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokΓ©mon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokΓ©mon! PokΓ©mon trainer Andrew decided to help Pikachu to build a pokΓ©mon army to resist.First, Andrew counted all the pokΓ©mon β€” there were exactly \(n\) pikachu. The strength of the \(i\)-th pokΓ©mon is equal to \(a_i\), and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array \(b\) from \(k\) indices such that \(1 \le b_1 < b_2 < \dots < b_k \le n\), and his army will consist of pokΓ©mons with forces \(a_{b_1}, a_{b_2}, \dots, a_{b_k}\).The strength of the army is equal to the alternating sum of elements of the subsequence; that is, \(a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots\).Andrew is experimenting with pokΓ©mon order. He performs \(q\) operations. In \(i\)-th operation Andrew swaps \(l_i\)-th and \(r_i\)-th pokΓ©mon.Note: \(q=0\) in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokΓ©mon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokΓ©mon, or team R will realize their tricky plan!
Each test contains multiple test cases.The first line contains one positive integer \(t\) (\(1 \le t \le 10^3\)) denoting the number of test cases. Description of the test cases follows.The first line of each test case contains two integers \(n\) and \(q\) (\(1 \le n \le 3 \cdot 10^5, q = 0\)) denoting the number of pokΓ©mon and number of operations respectively.The second line contains \(n\) distinct positive integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le n\)) denoting the strengths of the pokΓ©mon.\(i\)-th of the last \(q\) lines contains two positive integers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le n\)) denoting the indices of pokΓ©mon that were swapped in the \(i\)-th operation.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(3 \cdot 10^5\), and the sum of \(q\) over all test cases does not exceed \(3 \cdot 10^5\).
For each test case, print \(q+1\) integers: the maximal strength of army before the swaps and after each swap.
In third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be \(5βˆ’3+7=9\).
Input: 3 3 0 1 3 2 2 0 1 2 7 0 1 2 5 4 3 6 7 | Output: 3 2 9
Easy
3
1,445
864
110
14
1,181
C
1181C
C. Flag
1,900
brute force; combinatorics; dp; implementation
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in \(n \cdot m\) colored pieces that form a rectangle with \(n\) rows and \(m\) columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different. These subrectangles are flags. These subrectangles are not flags.
The first line contains two integers \(n\) and \(m\) (\(1 \le n, m \le 1\,000\)) β€” the number of rows and the number of columns on the blanket.Each of the next \(n\) lines contains \(m\) lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
In the only line print the number of subrectangles which form valid flags.
The selected subrectangles are flags in the first example.
Input: 4 3 aaa bbb ccb ddd | Output: 6
Hard
4
1,310
356
74
11
1,675
G
1675G
G. Sorting Pancakes
2,300
dp
Nastya baked \(m\) pancakes and spread them on \(n\) dishes. The dishes are in a row and numbered from left to right. She put \(a_i\) pancakes on the dish with the index \(i\).Seeing the dishes, Vlad decided to bring order to the stacks and move some pancakes. In one move, he can shift one pancake from any dish to the closest one, that is, select the dish \(i\) (\(a_i > 0\)) and do one of the following: if \(i > 1\), put the pancake on a dish with the previous index, after this move \(a_i = a_i - 1\) and \(a_{i - 1} = a_{i - 1} + 1\); if \(i < n\), put the pancake on a dish with the following index, after this move \(a_i = a_i - 1\) and \(a_{i + 1} = a_{i + 1} + 1\).Vlad wants to make the array \(a\)non-increasing, after moving as few pancakes as possible. Help him find the minimum number of moves needed for this.The array \(a=[a_1, a_2,\dots,a_n]\) is called non-increasing if \(a_i \ge a_{i+1}\) for all \(i\) from \(1\) to \(n-1\).
The first line of the input contains two numbers \(n\) and \(m\) (\(1 \le n, m \le 250\)) β€” the number of dishes and the number of pancakes, respectively.The second line contains \(n\) numbers \(a_i\) (\(0 \le a_i \le m\)), the sum of all \(a_i\) is equal to \(m\).
Print a single number: the minimum number of moves required to make the array \(a\) non-increasing.
In the first example, you first need to move the pancake from the dish \(1\), after which \(a = [4, 4, 2, 3, 3, 3]\). After that, you need to move the pancake from the dish \(2\) to the dish \(3\) and the array will become non-growing \(a = [4, 3, 3, 3, 3, 3]\).
Input: 6 19 5 3 2 3 3 3 | Output: 2
Expert
1
946
265
99
16
1,738
D
1738D
D. Permutation Addicts
1,900
constructive algorithms; data structures; dfs and similar; dsu; graphs; trees
Given a permutation \(a_1, a_2, \dots, a_n\) of integers from \(1\) to \(n\), and a threshold \(k\) with \(0 \leq k \leq n\), you compute a sequence \(b_1, b_2, \dots, b_n\) as follows. For every \(1 \leq i \leq n\) in increasing order, let \(x = a_i\). If \(x \leq k\), set \(b_{x}\) to the last element \(a_j\) (\(1 \leq j < i\)) that \(a_j > k\). If no such element \(a_j\) exists, set \(b_{x} = n+1\). If \(x > k\), set \(b_{x}\) to the last element \(a_j\) (\(1 \leq j < i\)) that \(a_j \leq k\). If no such element \(a_j\) exists, set \(b_{x} = 0\). Unfortunately, after the sequence \(b_1, b_2, \dots, b_n\) has been completely computed, the permutation \(a_1, a_2, \dots, a_n\) and the threshold \(k\) are discarded. Now you only have the sequence \(b_1, b_2, \dots, b_n\). Your task is to find any possible permutation \(a_1, a_2, \dots, a_n\) and threshold \(k\) that produce the sequence \(b_1, b_2, \dots, b_n\). It is guaranteed that there exists at least one pair of permutation \(a_1, a_2, \dots, a_n\) and threshold \(k\) that produce the sequence \(b_1, b_2, \dots, b_n\).A permutation of integers from \(1\) to \(n\) is a sequence of length \(n\) which contains all integers from \(1\) to \(n\) exactly once.
Each test contains multiple test cases. The first line contains an integer \(t\) (\(1 \leq t \leq 10^5\)) β€” the number of test cases. The following lines contain the description of each test case.The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 10^5\)), indicating the length of the permutation \(a\).The second line of each test case contains \(n\) integers \(b_1, b_2, \dots, b_n\) (\(0 \leq b_i \leq n+1\)), indicating the elements of the sequence \(b\).It is guaranteed that there exists at least one pair of permutation \(a_1, a_2, \dots, a_n\) and threshold \(k\) that produce the sequence \(b_1, b_2, \dots, b_n\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case, output the threshold \(k\) (\(0 \leq k \leq n\)) in the first line, and then output the permutation \(a_1, a_2, \dots, a_n\) (\(1 \leq a_i \leq n\)) in the second line such that the permutation \(a_1, a_2, \dots, a_n\) and threshold \(k\) produce the sequence \(b_1, b_2, \dots, b_n\). If there are multiple solutions, you can output any of them.
For the first test case, permutation \(a = [1,3,2,4]\) and threshold \(k = 2\) will produce sequence \(b\) as follows. When \(i = 1\), \(x = a_i = 1 \leq k\), there is no \(a_j\) (\(1 \leq j < i\)) that \(a_j > k\). Therefore, \(b_1 = n + 1 = 5\). When \(i = 2\), \(x = a_i = 3 > k\), the last element \(a_j\) that \(a_j \leq k\) is \(a_1\). Therefore, \(b_3 = a_1 = 1\). When \(i = 3\), \(x = a_i = 2 \leq k\), the last element \(a_j\) that \(a_j > k\) is \(a_2\). Therefore, \(b_2 = a_2 = 3\). When \(i = 4\), \(x = a_i = 4 > k\), the last element \(a_j\) that \(a_j \leq k\) is \(a_3\). Therefore, \(b_4 = a_3 = 2\). Finally, we obtain sequence \(b = [5,3,1,2]\). For the second test case, permutation \(a = [1,2,3,4,5,6]\) and threshold \(k = 3\) will produce sequence \(b\) as follows. When \(i = 1, 2, 3\), \(a_i \leq k\), there is no \(a_j\) (\(1 \leq j < i\)) that \(a_j > k\). Therefore, \(b_1 = b_2 = b_3 = n + 1 = 7\). When \(i = 4, 5, 6\), \(a_i > k\), the last element \(a_j\) that \(a_j \leq k\) is \(a_3\). Therefore, \(b_4 = b_5 = b_6 = a_3 = 3\). Finally, we obtain sequence \(b = [7,7,7,3,3,3]\). For the third test case, permutation \(a = [6,5,4,3,2,1]\) and threshold \(k = 3\) will produce sequence \(b\) as follows. When \(i = 1, 2, 3\), \(a_i > k\), there is no \(a_j\) (\(1 \leq j < i\)) that \(a_j \leq k\). Therefore, \(b_4 = b_5 = b_6 = 0\). When \(i = 4, 5, 6\), \(a_i \leq k\), the last element \(a_j\) that \(a_j > k\) is \(a_3\). Therefore, \(b_1 = b_2 = b_3 = a_3 = 4\). Finally, we obtain sequence \(b = [4,4,4,0,0,0]\).
Input: 345 3 1 267 7 7 3 3 364 4 4 0 0 0 | Output: 2 1 3 2 4 3 1 2 3 4 5 6 3 6 5 4 3 2 1
Hard
6
1,226
732
366
17
97
A
97A
A. Domino
2,400
brute force; implementation
Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2 Γ— 1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-61-1 1-2 1-3 1-4 1-5 1-62-2 2-3 2-4 2-5 2-63-3 3-4 3-5 3-64-4 4-5 4-65-5 5-66-6The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2 Γ— 2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β€” he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size n Γ— m and put there rectangular chips of sizes 1 Γ— 2 and 2 Γ— 1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round.
The first line contains two positive integers n and m (1 ≀ n, m ≀ 30). Each of the following n lines contains m characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from ""a"" to ""z"" and ""A"", ""B"" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct.It is also guaranteed that at least one solution exists.
Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next n lines containing m characters each, should contain a field from dots and numbers from 0 to 6 β€” any of the possible solutions. All dominoes should be different.
Input: 8 8.aabbcc..defghi.kdefghijklmnopqj.lmnopq..rstuvw.xrstuvwyxzzAABBy | Output: 10080.001122..001122.3344005533440055.225566..225566.6611334466113344
Expert
2
1,390
562
353
0
1,313
E
1313E
E. Concatenation with intersection
2,700
data structures; hashing; strings; two pointers
Vasya had three strings \(a\), \(b\) and \(s\), which consist of lowercase English letters. The lengths of strings \(a\) and \(b\) are equal to \(n\), the length of the string \(s\) is equal to \(m\). Vasya decided to choose a substring of the string \(a\), then choose a substring of the string \(b\) and concatenate them. Formally, he chooses a segment \([l_1, r_1]\) (\(1 \leq l_1 \leq r_1 \leq n\)) and a segment \([l_2, r_2]\) (\(1 \leq l_2 \leq r_2 \leq n\)), and after concatenation he obtains a string \(a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} \ldots a_{r_1} b_{l_2} b_{l_2 + 1} \ldots b_{r_2}\).Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: segments \([l_1, r_1]\) and \([l_2, r_2]\) have non-empty intersection, i.e. there exists at least one integer \(x\), such that \(l_1 \leq x \leq r_1\) and \(l_2 \leq x \leq r_2\); the string \(a[l_1, r_1] + b[l_2, r_2]\) is equal to the string \(s\).
The first line contains integers \(n\) and \(m\) (\(1 \leq n \leq 500\,000, 2 \leq m \leq 2 \cdot n\)) β€” the length of strings \(a\) and \(b\) and the length of the string \(s\).The next three lines contain strings \(a\), \(b\) and \(s\), respectively. The length of the strings \(a\) and \(b\) is \(n\), while the length of the string \(s\) is \(m\).All strings consist of lowercase English letters.
Print one integer β€” the number of ways to choose a pair of segments, which satisfy Vasya's conditions.
Let's list all the pairs of segments that Vasya could choose in the first example: \([2, 2]\) and \([2, 5]\); \([1, 2]\) and \([2, 4]\); \([5, 5]\) and \([2, 5]\); \([5, 6]\) and \([3, 5]\);
Input: 6 5aabbaabaaaabaaaaa | Output: 4
Master
4
978
400
102
13
1,918
A
1918A
A. Brick Wall
800
constructive algorithms; greedy; implementation; math
A brick is a strip of size \(1 \times k\), placed horizontally or vertically, where \(k\) can be an arbitrary number that is at least \(2\) (\(k \ge 2\)).A brick wall of size \(n \times m\) is such a way to place several bricks inside a rectangle \(n \times m\), that all bricks lie either horizontally or vertically in the cells, do not cross the border of the rectangle, and that each cell of the \(n \times m\) rectangle belongs to exactly one brick. Here \(n\) is the height of the rectangle \(n \times m\) and \(m\) is the width. Note that there can be bricks with different values of k in the same brick wall.The wall stability is the difference between the number of horizontal bricks and the number of vertical bricks. Note that if you used \(0\) horizontal bricks and \(2\) vertical ones, then the stability will be \(-2\), not \(2\).What is the maximal possible stability of a wall of size \(n \times m\)?It is guaranteed that under restrictions in the statement at least one \(n \times m\) wall exists.
The first line of the input contains one integer \(t\) (\(1 \le t \le 10\,000\)), the number of test cases. The only line of each test case contains two integers \(n\) and \(m\) (\(2 \le n,\,m \le 10^4\)).
For each test case, print one integer, the maximum stability of a wall of size \(n \times m\).
In the 1st test case, the maximum stability of \(2\) is obtained by placing two horizontal bricks \(1 \times 2\) one on top of the other.In the 2nd test case, one can get the maximum stability of \(28\) by placing \(4\) horizontal bricks \(1 \times 2\) in each of the \(7\) rows.
Input: 52 27 816 93 510000 10000 | Output: 2 28 64 6 50000000
Beginner
4
1,013
205
94
19
1,296
C
1296C
C. Yet Another Walking Robot
1,500
data structures; implementation
There is a robot on a coordinate plane. Initially, the robot is located at the point \((0, 0)\). Its path is described as a string \(s\) of length \(n\) consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point \((x, y)\) to the point \((x - 1, y)\); 'R' (right): means that the robot moves from the point \((x, y)\) to the point \((x + 1, y)\); 'U' (up): means that the robot moves from the point \((x, y)\) to the point \((x, y + 1)\); 'D' (down): means that the robot moves from the point \((x, y)\) to the point \((x, y - 1)\). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point \((x_e, y_e)\), then after optimization (i.e. removing some single substring from \(s\)) the robot also ends its path at the point \((x_e, y_e)\).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string \(s\)).Recall that the substring of \(s\) is such string that can be obtained from \(s\) by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of ""LURLLR"" are ""LU"", ""LR"", ""LURLLR"", ""URL"", but not ""RR"" and ""UL"".You have to answer \(t\) independent test cases.
The first line of the input contains one integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases.The next \(2t\) lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the length of the robot's path. The second line of the test case contains one string \(s\) consisting of \(n\) characters 'L', 'R', 'U', 'D' β€” the robot's path.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\) (\(\sum n \le 2 \cdot 10^5\)).
For each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers \(l\) and \(r\) such that \(1 \le l \le r \le n\) β€” endpoints of the substring you remove. The value \(r-l+1\) should be minimum possible. If there are several answers, print any of them.
Input: 4 4 LRUD 4 LURD 5 RRUDU 5 LLDDR | Output: 1 2 1 4 3 4 -1
Medium
2
1,835
560
371
12
1,610
A
1610A
A. Anti Light's Cell Guessing
900
math
You are playing a game on a \(n \times m\) grid, in which the computer has selected some cell \((x, y)\) of the grid, and you have to determine which one. To do so, you will choose some \(k\) and some \(k\) cells \((x_1, y_1),\, (x_2, y_2), \ldots, (x_k, y_k)\), and give them to the computer. In response, you will get \(k\) numbers \(b_1,\, b_2, \ldots b_k\), where \(b_i\) is the manhattan distance from \((x_i, y_i)\) to the hidden cell \((x, y)\) (so you know which distance corresponds to which of \(k\) input cells). After receiving these \(b_1,\, b_2, \ldots, b_k\), you have to be able to determine the hidden cell. What is the smallest \(k\) for which is it possible to always guess the hidden cell correctly, no matter what cell computer chooses?As a reminder, the manhattan distance between cells \((a_1, b_1)\) and \((a_2, b_2)\) is equal to \(|a_1-a_2|+|b_1-b_2|\).
The first line of the input contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. The description of test cases follows. The single line of each test case contains two integers \(n\) and \(m\) (\(1 \le n, m \le 10^9\)) β€” the number of rows and the number of columns in the grid.
For each test case print a single integer β€” the minimum \(k\) for that test case.
In the first test case, the smallest such \(k\) is \(2\), for which you can choose, for example, cells \((1, 1)\) and \((2, 1)\).Note that you can't choose cells \((1, 1)\) and \((2, 3)\) for \(k = 2\), as both cells \((1, 2)\) and \((2, 1)\) would give \(b_1 = 1, b_2 = 2\), so we wouldn't be able to determine which cell is hidden if computer selects one of those.In the second test case, you should choose \(k = 1\), for it you can choose cell \((3, 1)\) or \((1, 1)\).
Input: 2 2 3 3 1 | Output: 2 1
Beginner
1
879
307
81
16
1,099
B
1099B
B. Squares and Segments
1,100
binary search; constructive algorithms; math
Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw \(n\) squares in the snow with a side length of \(1\). For simplicity, we assume that Sofia lives on a plane and can draw only segments of length \(1\), parallel to the coordinate axes, with vertices at integer points.In order to draw a segment, Sofia proceeds as follows. If she wants to draw a vertical segment with the coordinates of the ends \((x, y)\) and \((x, y+1)\). Then Sofia looks if there is already a drawn segment with the coordinates of the ends \((x', y)\) and \((x', y+1)\) for some \(x'\). If such a segment exists, then Sofia quickly draws a new segment, using the old one as a guideline. If there is no such segment, then Sofia has to take a ruler and measure a new segment for a long time. Same thing happens when Sofia wants to draw a horizontal segment, but only now she checks for the existence of a segment with the same coordinates \(x\), \(x+1\) and the differing coordinate \(y\).For example, if Sofia needs to draw one square, she will have to draw two segments using a ruler: After that, she can draw the remaining two segments, using the first two as a guide: If Sofia needs to draw two squares, she will have to draw three segments using a ruler: After that, she can draw the remaining four segments, using the first three as a guide: Sofia is in a hurry, so she wants to minimize the number of segments that she will have to draw with a ruler without a guide. Help her find this minimum number.
The only line of input contains a single integer \(n\) (\(1 \le n \le 10^{9}\)), the number of squares that Sofia wants to draw.
Print single integer, the minimum number of segments that Sofia will have to draw with a ruler without a guide in order to draw \(n\) squares in the manner described above.
Input: 1 | Output: 2
Easy
3
1,566
128
172
10
2,114
F
2114F
F. Small Operations
2,000
binary search; brute force; dfs and similar; dp; math; number theory; sortings
Given an integer \(x\) and an integer \(k\). In one operation, you can perform one of two actions: choose an integer \(1 \le a \le k\) and assign \(x = x \cdot a\); choose an integer \(1 \le a \le k\) and assign \(x = \frac{x}{a}\), where the value of \(\frac{x}{a}\) must be an integer. Find the minimum number of operations required to make the number \(x\) equal to \(y\), or determine that it is impossible.
The first line of the input contains one integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The only line of each test case contains three integers \(x\), \(y\) and \(k\) (\(1 \le x, y, k \le 10^6\)).It is guaranteed that the sum of \(x\) and the sum of \(y\) across all test cases does not exceed \(10^8\).
For each test case, output \(-1\) if it is impossible to achieve \(x=y\) using the given operations, and the minimum number of required operations otherwise.
Input: 84 6 34 5 34 6 210 45 3780 23 4211 270 231 982800 131 6 2 | Output: 2 -1 -1 3 3 3 6 -1
Hard
7
411
320
157
21
731
A
731A
A. Night at the Museum
800
implementation; strings
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.Embosser is a special devise that allows to ""print"" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture: After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
The only line of input contains the name of some exhibit β€” the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Print one integer β€” the minimum number of rotations of the wheel, required to print the name given in the input.
To print the string from the first sample it would be optimal to perform the following sequence of rotations: from 'a' to 'z' (1 rotation counterclockwise), from 'z' to 'e' (5 clockwise rotations), from 'e' to 'u' (10 rotations counterclockwise), from 'u' to 's' (2 counterclockwise rotations). In total, 1 + 5 + 10 + 2 = 18 rotations are required.
Input: zeus | Output: 18
Beginner
2
1,138
198
112
7
755
C
755C
C. PolandBall and Forest
1,300
dfs and similar; dsu; graphs; interactive; trees
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.How many trees are there in the forest?
The first line contains single integer n (1 ≀ n ≀ 104) β€” the number of Balls living in the forest.The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≀ pi ≀ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.It's guaranteed that the sequence p corresponds to some valid forest.Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:In the first line, output the integer n (1 ≀ n ≀ 104) β€” the number of Balls and the integer m (0 ≀ m < n) β€” the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:5 31 23 44 5
You should output the number of trees in the forest where PolandBall lives.
In the first sample testcase, possible forest is: 1-2 3-4-5. There are 2 trees overall.In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.
Input: 52 1 5 3 3 | Output: 2
Easy
5
536
1,023
75
7
58
A
58A
A. Chat room
1,000
greedy; strings
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word ""hello"". For example, if Vasya types the word ""ahhellllloou"", it will be considered that he said hello, and if he types ""hlelo"", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word s.
The first and only line contains the word s, which Vasya typed. This word consisits of small Latin letters, its length is no less that 1 and no more than 100 letters.
If Vasya managed to say hello, print ""YES"", otherwise print ""NO"".
Input: ahhellllloou | Output: YES
Beginner
2
582
166
69
0
2,006
E
2006E
E. Iris's Full Binary Tree
3,100
brute force; data structures; dfs and similar; trees
Iris likes full binary trees.Let's define the depth of a rooted tree as the maximum number of vertices on the simple paths from some vertex to the root. A full binary tree of depth \(d\) is a binary tree of depth \(d\) with exactly \(2^d - 1\) vertices.Iris calls a tree a \(d\)-binary tree if some vertices and edges can be added to it to make it a full binary tree of depth \(d\). Note that any vertex can be chosen as the root of a full binary tree.Since performing operations on large trees is difficult, she defines the binary depth of a tree as the minimum \(d\) satisfying that the tree is \(d\)-binary. Specifically, if there is no integer \(d \ge 1\) such that the tree is \(d\)-binary, the binary depth of the tree is \(-1\).Iris now has a tree consisting of only vertex \(1\). She wants to add \(n - 1\) more vertices to form a larger tree. She will add the vertices one by one. When she adds vertex \(i\) (\(2 \leq i \leq n\)), she'll give you an integer \(p_i\) (\(1 \leq p_i < i\)), and add a new edge connecting vertices \(i\) and \(p_i\).Iris wants to ask you the binary depth of the tree formed by the first \(i\) vertices for each \(1 \le i \le n\). Can you tell her the answer?
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 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\) (\(2 \leq n \leq 5 \cdot 10^5\)) β€” the final size of the tree.The second line of each test case contains \(n - 1\) integers \(p_2, p_3, \ldots, p_n\) (\(1 \leq p_i < i\)) β€” descriptions of all edges of the tree.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5 \cdot 10^5\).
For each test case output \(n\) integers, \(i\)-th of them representing the binary depth of the tree formed by the first \(i\) vertices.
In the first test case, the final tree is shown below: The tree consisting of the vertex \(1\) has the binary depth \(1\) (the tree itself is a full binary tree of depth \(1\)). The tree consisting of the vertices \(1\) and \(2\) has the binary depth \(2\) (we can add the vertex \(3\) to make it a full binary tree of depth \(2\)). The tree consisting of the vertices \(1\), \(2\) and \(3\) has the binary depth \(2\) (the tree itself is a full binary tree of depth \(2\)).In the second test case, the formed full binary tree after adding some vertices to the tree consisting of \(n\) vertices is shown below (bolded vertices are added): The depth of the formed full binary tree is \(4\).In the fifth test case, the final tree is shown below: It can be proved that Iris can't form any full binary tree by adding vertices and edges, so the binary depth is \(-1\).
Input: 731 161 2 3 4 571 1 3 2 5 1101 1 2 1 4 2 4 5 8101 1 3 1 3 2 2 2 6201 1 2 2 4 4 5 5 7 6 8 6 11 14 11 8 13 13 12251 1 3 3 1 5 4 4 6 8 11 12 8 7 11 13 7 13 15 6 19 14 10 23 | Output: 1 2 2 1 2 2 3 3 4 1 2 2 3 3 4 4 1 2 2 3 3 3 4 4 5 5 1 2 2 3 3 4 4 4 -1 -1 1 2 2 3 3 4 4 4 4 5 5 5 5 6 6 6 6 6 6 7 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 6 7 7 7 7 7 8 8 8 8
Master
4
1,196
553
136
20
1,926
F
1926F
F. Vlad and Avoiding X
2,200
bitmasks; brute force; dfs and similar; dp; implementation
Vladislav has a grid of size \(7 \times 7\), where each cell is colored black or white. In one operation, he can choose any cell and change its color (black \(\leftrightarrow\) white).Find the minimum number of operations required to ensure that there are no black cells with four diagonal neighbors also being black. The left image shows that initially there are two black cells violating the condition. By flipping one cell, the grid will work.
The first line of input contains a single integer \(t\) (\(1 \leq t \leq 200\)) β€” the number of test cases. Then follows the description of the test cases.Each test case consists of \(7\) lines, each containing \(7\) characters. Each of these characters is either \(\texttt{W}\) or \(\texttt{B}\), denoting a white or black cell, respectively.
For each test case, output a single integer β€” the minimum number of operations required to ensure that there are no black cells with all four diagonal neighbors also being black.
The first test case is illustrated in the statement.The second test case is illustrated below: In the third test case, the grid already satisfies the condition.
Input: 4WWWWWWWWWWWBBBWWWWWBWWWBBBBBWWWBWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBBBBBWWBBBBBWWBBBBBWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWBBBBBWBBBBBBBBBBBBBBWWWWWWWBBBBBBBBBBBBBBBBBBBBB | Output: 1 2 0 5
Hard
5
446
343
178
19
1,117
G
1117G
G. Recursive Queries
2,500
data structures
You are given a permutation \(p_1, p_2, \dots, p_n\). You should answer \(q\) queries. Each query is a pair \((l_i, r_i)\), and you should calculate \(f(l_i, r_i)\).Let's denote \(m_{l, r}\) as the position of the maximum in subsegment \(p_l, p_{l+1}, \dots, p_r\).Then \(f(l, r) = (r - l + 1) + f(l, m_{l,r} - 1) + f(m_{l,r} + 1, r)\) if \(l \le r\) or \(0\) otherwise.
The first line contains two integers \(n\) and \(q\) (\(1 \le n \le 10^6\), \(1 \le q \le 10^6\)) β€” the size of the permutation \(p\) and the number of queries.The second line contains \(n\) pairwise distinct integers \(p_1, p_2, \dots, p_n\) (\(1 \le p_i \le n\), \(p_i \neq p_j\) for \(i \neq j\)) β€” permutation \(p\).The third line contains \(q\) integers \(l_1, l_2, \dots, l_q\) β€” the first parts of the queries.The fourth line contains \(q\) integers \(r_1, r_2, \dots, r_q\) β€” the second parts of the queries.It's guaranteed that \(1 \le l_i \le r_i \le n\) for all queries.
Print \(q\) integers β€” the values \(f(l_i, r_i)\) for the corresponding queries.
Description of the queries: \(f(2, 2) = (2 - 2 + 1) + f(2, 1) + f(3, 2) = 1 + 0 + 0 = 1\); \(f(1, 3) = (3 - 1 + 1) + f(1, 2) + f(4, 3) = 3 + (2 - 1 + 1) + f(1, 0) + f(2, 2) = 3 + 2 + (2 - 2 + 1) = 6\); \(f(1, 4) = (4 - 1 + 1) + f(1, 2) + f(4, 4) = 4 + 3 + 1 = 8\); \(f(2, 4) = (4 - 2 + 1) + f(2, 2) + f(4, 4) = 3 + 1 + 1 = 5\); \(f(1, 1) = (1 - 1 + 1) + 0 + 0 = 1\).
Input: 4 5 3 1 4 2 2 1 1 2 1 2 3 4 4 1 | Output: 1 6 8 5 1
Expert
1
370
581
80
11
519
D
519D
D. A and B and Interesting Substrings
1,800
data structures; dp; two pointers
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively.The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
Print the answer to the problem.
In the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Input: 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1xabcab | Output: 2
Medium
3
975
301
32
5
1,114
A
1114A
A. Got Any Grapes?
800
brute force; greedy; implementation
The Duck songFor simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen: Andrew, Dmitry and Michal should eat at least \(x\), \(y\) and \(z\) grapes, respectively. Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only. On the other hand, Dmitry is not a fan of black grapes β€” any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes. Michal has a common taste β€” he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with \(a\) green grapes, \(b\) purple grapes and \(c\) black grapes.However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
The first line contains three integers \(x\), \(y\) and \(z\) (\(1 \le x, y, z \le 10^5\)) β€” the number of grapes Andrew, Dmitry and Michal want to eat.The second line contains three integers \(a\), \(b\), \(c\) (\(1 \le a, b, c \le 10^5\)) β€” the number of green, purple and black grapes in the box.
If there is a grape distribution that allows everyone to be happy, print ""YES"", otherwise print ""NO"".
In the first example, there is only one possible distribution:Andrew should take \(1\) green grape, Dmitry should take \(3\) remaining green grapes and \(3\) purple grapes, and Michal will take \(2\) out of \(3\) available black grapes.In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Input: 1 6 24 3 3 | Output: YES
Beginner
3
1,292
299
105
11
1,884
E
1884E
E. Hard Design
2,800
greedy; implementation; math
Consider an array of integers \(b_0, b_1, \ldots, b_{n-1}\). Your goal is to make all its elements equal. To do so, you can perform the following operation several (possibly, zero) times: Pick a pair of indices \(0 \le l \le r \le n-1\), then for each \(l \le i \le r\) increase \(b_i\) by \(1\) (i. e. replace \(b_i\) with \(b_i + 1\)). After performing this operation you receive \((r - l + 1)^2\) coins. The value \(f(b)\) is defined as a pair of integers \((cnt, cost)\), where \(cnt\) is the smallest number of operations required to make all elements of the array equal, and \(cost\) is the largest total number of coins you can receive among all possible ways to make all elements equal within \(cnt\) operations. In other words, first, you need to minimize the number of operations, second, you need to maximize the total number of coins you receive.You are given an array of integers \(a_0, a_1, \ldots, a_{n-1}\). Please, find the value of \(f\) for all cyclic shifts of \(a\).Formally, for each \(0 \le i \le n-1\) you need to do the following: Let \(c_j = a_{(j + i) \pmod{n}}\) for each \(0 \le j \le n-1\). Find \(f(c)\). Since \(cost\) can be very large, output it modulo \((10^9 + 7)\).Please note that under a fixed \(cnt\) you need to maximize the total number of coins \(cost\), not its remainder modulo \((10^9 + 7)\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 2 \cdot 10^4\)). The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^6\)).The second line of each test case contains \(n\) integers \(a_0, a_1, \ldots, a_{n-1}\) (\(1 \le a_i \le 10^9\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^6\).
For each test case, for each \(0 \le i \le n-1\) output the value of \(f\) for the \(i\)-th cyclic shift of array \(a\): first, output \(cnt\) (the minimum number of operations), then output \(cost\) (the maximum number of coins these operations can give) modulo \(10^9 + 7\).
In the first test case, there is only one cycle shift, which is equal to \([1]\), and all its elements are already equal.In the second test case, you need to find the answer for three arrays: \(f([1, 3, 2]) = (3, 3)\). \(f([3, 2, 1]) = (2, 5)\). \(f([2, 1, 3]) = (2, 5)\). Consider the case of \([2, 1, 3]\). To make all elements equal, we can pick \(l = 1\) and \(r = 1\) on the first operation, which results in \([2, 2, 3]\). On the second operation we can pick \(l = 0\) and \(r = 1\), which results in \([3, 3, 3]\). We have used \(2\) operations, and the total number of coins received is \(1^2 + 2^2 = 5\).
Input: 51131 3 253 2 4 5 186 5 6 4 2 6 2 2410 10 10 10 | Output: 0 0 3 3 2 5 2 5 7 18 7 16 6 22 5 28 5 28 9 27 9 27 9 27 9 27 11 23 9 27 9 27 13 19 0 0 0 0 0 0 0 0
Master
3
1,338
454
276
18
1,807
D
1807D
D. Odd Queries
900
data structures; implementation
You have an array \(a_1, a_2, \dots, a_n\). Answer \(q\) queries of the following form: If we change all elements in the range \(a_l, a_{l+1}, \dots, a_r\) of the array to \(k\), will the sum of the entire array be odd? Note that queries are independent and do not affect future queries.
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 consists of \(2\) integers \(n\) and \(q\) (\(1 \le n \le 2 \cdot 10^5\); \(1 \le q \le 2 \cdot 10^5\)) β€” the length of the array and the number of queries.The second line of each test case consists of \(n\) integers \(a_i\) (\(1 \le a_i \le 10^9\)) β€” the array \(a\).The next \(q\) lines of each test case consists of \(3\) integers \(l,r,k\) (\(1 \le l \le r \le n\); \(1 \le k \le 10^9\)) β€” the queries.It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(2 \cdot 10^5\), and the sum of \(q\) doesn't exceed \(2 \cdot 10^5\).
For each query, output ""YES"" if the sum of the entire array becomes odd, and ""NO"" otherwise.You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
For the first test case: If the elements in the range \((2, 3)\) would get set to \(3\) the array would become \(\{2, 3, 3, 3, 2\}\), the sum would be \(2+3+3+3+2 = 13\) which is odd, so the answer is ""YES"". If the elements in the range \((2, 3)\) would get set to \(4\) the array would become \(\{2, 4, 4, 3, 2\}\), the sum would be \(2+4+4+3+2 = 15\) which is odd, so the answer is ""YES"". If the elements in the range \((1, 5)\) would get set to \(5\) the array would become \(\{5, 5, 5, 5, 5\}\), the sum would be \(5+5+5+5+5 = 25\) which is odd, so the answer is ""YES"". If the elements in the range \((1, 4)\) would get set to \(9\) the array would become \(\{9, 9, 9, 9, 2\}\), the sum would be \(9+9+9+9+2 = 38\) which is even, so the answer is ""NO"". If the elements in the range \((2, 4)\) would get set to \(3\) the array would become \(\{2, 3, 3, 3, 2\}\), the sum would be \(2+3+3+3+2 = 13\) which is odd, so the answer is ""YES"".
Input: 25 52 2 1 3 22 3 32 3 41 5 51 4 92 4 310 51 1 1 1 1 1 1 1 1 13 8 132 5 103 8 101 10 21 9 100 | Output: YES YES YES NO YES NO NO NO NO YES
Beginner
2
287
745
257
18
1,914
A
1914A
A. Problemsolving Log
800
implementation; strings
Monocarp is participating in a programming contest, which features \(26\) problems, named from 'A' to 'Z'. The problems are sorted by difficulty. Moreover, it's known that Monocarp can solve problem 'A' in \(1\) minute, problem 'B' in \(2\) minutes, ..., problem 'Z' in \(26\) minutes.After the contest, you discovered his contest log β€” a string, consisting of uppercase Latin letters, such that the \(i\)-th letter tells which problem Monocarp was solving during the \(i\)-th minute of the contest. If Monocarp had spent enough time in total on a problem to solve it, he solved it. Note that Monocarp could have been thinking about a problem after solving it.Given Monocarp's contest log, calculate the number of problems he solved during the contest.
The first line contains a single integer \(t\) (\(1 \le t \le 100\)) β€” the number of testcases.The first line of each testcase contains a single integer \(n\) (\(1 \le n \le 500\)) β€” the duration of the contest, in minutes.The second line contains a string of length exactly \(n\), consisting only of uppercase Latin letters, β€” Monocarp's contest log.
For each testcase, print a single integer β€” the number of problems Monocarp solved during the contest.
Input: 36ACBCBC7AAAAFPC22FEADBBDFFEDFFFDHHHADCC | Output: 3 1 4
Beginner
2
752
351
102
19
1,081
G
1081G
G. Mergesort Strikes Back
3,200
math; probabilities
Chouti thought about his very first days in competitive programming. When he had just learned to write merge sort, he thought that the merge sort is too slow, so he restricted the maximum depth of recursion and modified the merge sort to the following: Chouti found his idea dumb since obviously, this ""merge sort"" sometimes cannot sort the array correctly. However, Chouti is now starting to think of how good this ""merge sort"" is. Particularly, Chouti wants to know for a random permutation \(a\) of \(1, 2, \ldots, n\) the expected number of inversions after calling MergeSort(a, 1, n, k).It can be proved that the expected number is rational. For the given prime \(q\), suppose the answer can be denoted by \(\frac{u}{d}\) where \(gcd(u,d)=1\), you need to output an integer \(r\) satisfying \(0 \le r<q\) and \(rd \equiv u \pmod q\). It can be proved that such \(r\) exists and is unique.
The first and only line contains three integers \(n, k, q\) (\(1 \leq n, k \leq 10^5, 10^8 \leq q \leq 10^9\), \(q\) is a prime).
The first and only line contains an integer \(r\).
In the first example, all possible permutations are \([1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]\).With \(k=1\), MergeSort(a, 1, n, k) will only return the original permutation. Thus the answer is \(9/6=3/2\), and you should output \(499122178\) because \(499122178 \times 2 \equiv 3 \pmod {998244353}\).In the second example, all possible permutations are \([1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]\) and the corresponding outputs of MergeSort(a, 1, n, k) are \([1,2,3],[1,2,3],[2,1,3],[1,2,3],[2,3,1],[1,3,2]\) respectively. Thus the answer is \(4/6=2/3\), and you should output \(665496236\) because \(665496236 \times 3 \equiv 2 \pmod {998244353}\).
Input: 3 1 998244353 | Output: 499122178
Master
2
897
129
50
10
1,819
E
1819E
E. Roads in E City
3,200
interactive; math; probabilities; trees
This is an interactive problem.As is well known, the city ""E"" has never had its roads repaired in its a thousand and a half years old history. And only recently the city administration repaired some of them.It is known that in total in the city ""E"" there are \(n\) intersections and \(m\) roads, which can be used in both directions, numbered with integers from \(1\) to \(m\). The \(i\)-th road connects intersections with numbers \(a_i\) and \(b_i\).Among all \(m\) roads, some subset of the roads has been repaired, but you do not know which one. The only information you could get from the city's road services is that you can get from any intersection to any other intersection by driving only on the roads that have been repaired.You are a young entrepreneur, and decided to organize a delivery service of fresh raw meat in the city ""E"" (in this city such meat is called ""steaks"", it is very popular among the locals). You have already recruited a staff of couriers, but the couriers are willing to travel only on repaired roads. Now you have to find out which roads have already been repaired.The city administration has given you the city for a period of time, so you can make different queries of one of three types: Block the road with the number \(x\). In this case, movement on the road for couriers will be forbidden. Initially all roads are unblocked. Unblock the road with the number \(x\). In this case, couriers will be able to move on the road \(x\) if it is repaired. Try to deliver the order to the intersection with the number \(y\). In this case, one of your couriers will start moving from intersection with number \(s\) you don't know and deliver the order to intersection with number \(y\) if there is a path on unblocked repaired roads from intersection \(s\) to intersection \(y\). It is guaranteed that intersection \(s\) will be chosen beforehand. Unfortunately, the city is placed at your complete disposal for a short period of time, so you can make no more than \(100 \cdot m\) requests.
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 1\,000\)) β€” the number of test cases. The description of test cases follows.The first line contains two integers \(n\) and \(m\) (\(2 \le n \le 2\,000\), \(n - 1 \le m \le 2\,000\)) β€”the number of intersections and roads in the city ""E"".Each of the following \(m\) lines describes one road. The \(i\)-th of these lines contains two integers \(a_i\) and \(b_i\) (\(1 \le a_i, b_i \le n\)) β€” the ends of the \(i\)-th road. It is guaranteed that no road connects the city to itself, while it is possible that there are several roads between a pair of different intersections.It is guaranteed that the sum of \(n\) and the sum of \(m\) over all test cases does not exceed \(2\,000\).
In the first test case, road \(1\) was repaired, while road \(2\) was not. For the first delivery request, intersection \(1\) was selected as \(s\), and the path from intersection \(1\) to \(1\) exists. For the second delivery request, intersection \(1\) was selected as \(s\). Since the only repaired road was blocked, there was no path between intersections \(1\) and \(2\). For the third delivery request, intersection \(2\) was selected as \(s\), the path between intersections \(2\) and \(1\) exists along road \(1\), which is repaired and unblocked.In the second test case, intersections \(1\), \(3\), \(1\), \(2\), \(2\), \(3\), \(1\) were selected as starting intersections for delivery requests.
Input: 2 2 2 1 2 2 1 1 0 1 1 3 3 1 2 2 3 3 1 1 1 1 0 1 1 1 1 | Output: - 1 ? 1 ? 2 - 2 + 1 ? 1 ! 1 0 - 1 ? 2 ? 1 - 2 ? 3 ? 3 + 1 ? 3 ? 2 ? 1 ! 1 1 1
Master
4
2,027
786
0
18
1,009
E
1009E
E. Intercity Travelling
2,000
combinatorics; math; probabilities
Leha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car.The path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance between Moscow and Saratov is \(n\) km. Let's say that Moscow is situated at the point with coordinate \(0\) km, and Saratov β€” at coordinate \(n\) km.Driving for a long time may be really difficult. Formally, if Leha has already covered \(i\) kilometers since he stopped to have a rest, he considers the difficulty of covering \((i + 1)\)-th kilometer as \(a_{i + 1}\). It is guaranteed that for every \(i \in [1, n - 1]\) \(a_i \le a_{i + 1}\). The difficulty of the journey is denoted as the sum of difficulties of each kilometer in the journey.Fortunately, there may be some rest sites between Moscow and Saratov. Every integer point from \(1\) to \(n - 1\) may contain a rest site. When Leha enters a rest site, he may have a rest, and the next kilometer will have difficulty \(a_1\), the kilometer after it β€” difficulty \(a_2\), and so on.For example, if \(n = 5\) and there is a rest site in coordinate \(2\), the difficulty of journey will be \(2a_1 + 2a_2 + a_3\): the first kilometer will have difficulty \(a_1\), the second one β€” \(a_2\), then Leha will have a rest, and the third kilometer will have difficulty \(a_1\), the fourth β€” \(a_2\), and the last one β€” \(a_3\). Another example: if \(n = 7\) and there are rest sites in coordinates \(1\) and \(5\), the difficulty of Leha's journey is \(3a_1 + 2a_2 + a_3 + a_4\).Leha doesn't know which integer points contain rest sites. So he has to consider every possible situation. Obviously, there are \(2^{n - 1}\) different distributions of rest sites (two distributions are different if there exists some point \(x\) such that it contains a rest site in exactly one of these distributions). Leha considers all these distributions to be equiprobable. He wants to calculate \(p\) β€” the expected value of difficulty of his journey.Obviously, \(p \cdot 2^{n - 1}\) is an integer number. You have to calculate it modulo \(998244353\).
The first line contains one number \(n\) (\(1 \le n \le 10^6\)) β€” the distance from Moscow to Saratov.The second line contains \(n\) integer numbers \(a_1\), \(a_2\), ..., \(a_n\) (\(1 \le a_1 \le a_2 \le \dots \le a_n \le 10^6\)), where \(a_i\) is the difficulty of \(i\)-th kilometer after Leha has rested.
Print one number β€” \(p \cdot 2^{n - 1}\), taken modulo \(998244353\).
Input: 21 2 | Output: 5
Hard
3
2,203
308
69
10
1,073
B
1073B
B. Vasya and Books
1,000
implementation; math
Vasya has got \(n\) books, numbered from \(1\) to \(n\), arranged in a stack. The topmost book has number \(a_1\), the next one β€” \(a_2\), and so on. The book at the bottom of the stack has number \(a_n\). All numbers are distinct.Vasya wants to move all the books to his backpack in \(n\) steps. During \(i\)-th step he wants to move the book number \(b_i\) into his backpack. If the book with number \(b_i\) is in the stack, he takes this book and all the books above the book \(b_i\), and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order \([1, 2, 3]\) (book \(1\) is the topmost), and Vasya moves the books in the order \([2, 1, 3]\), then during the first step he will move two books (\(1\) and \(2\)), during the second step he will do nothing (since book \(1\) is already in the backpack), and during the third step β€” one book (the book number \(3\)). Note that \(b_1, b_2, \dots, b_n\) are distinct.Help Vasya! Tell him the number of books he will put into his backpack during each step.
The first line contains one integer \(n~(1 \le n \le 2 \cdot 10^5)\) β€” the number of books in the stack.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n~(1 \le a_i \le n)\) denoting the stack of books.The third line contains \(n\) integers \(b_1, b_2, \dots, b_n~(1 \le b_i \le n)\) denoting the steps Vasya is going to perform.All numbers \(a_1 \dots a_n\) are distinct, the same goes for \(b_1 \dots b_n\).
Print \(n\) integers. The \(i\)-th of them should be equal to the number of books Vasya moves to his backpack during the \(i\)-th step.
The first example is described in the statement.In the second example, during the first step Vasya will move the books \([3, 1, 4]\). After that only books \(2\) and \(5\) remain in the stack (\(2\) is above \(5\)). During the second step Vasya will take the books \(2\) and \(5\). After that the stack becomes empty, so during next steps Vasya won't move any books.
Input: 31 2 32 1 3 | Output: 2 0 1
Beginner
2
1,074
422
135
10
698
A
698A
A. Vacations
1,400
dp
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: on this day the gym is closed and the contest is not carried out; on this day the gym is closed and the contest is carried out; on this day the gym is open and the contest is not carried out; on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations.The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: to do sport on any two consecutive days, to write the contest on any two consecutive days.
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Input: 41 3 2 0 | Output: 2
Easy
1
1,022
591
194
6
1,067
D
1067D
D. Computer Game
3,100
dp; greedy; math; probabilities
Ivan plays some computer game. There are \(n\) quests in the game. Each quest can be upgraded once, this increases the reward for its completion. Each quest has \(3\) parameters \(a_{i}\), \(b_{i}\), \(p_{i}\): reward for completing quest before upgrade, reward for completing quest after upgrade (\(a_{i} < b_{i}\)) and probability of successful completing the quest.Each second Ivan can try to complete one quest and he will succeed with probability \(p_{i}\). In case of success Ivan will get the reward and opportunity to upgrade any one quest (not necessary the one he just completed). In case of failure he gets nothing. Quests do not vanish after completing.Ivan has \(t\) seconds. He wants to maximize expected value of his total gain after \(t\) seconds. Help him to calculate this value.
First line contains \(2\) integers \(n\) (\( 1 \le n \le 10^{5}\)) and \(t\) (\( 1 \le t \le 10^{10}\)) β€” number of quests and total time.Following \(n\) lines contain description of quests. Each description is \(3\) numbers \(a_{i}\) \(b_{i}\) \(p_{i}\) (\(1 \le a_{i} < b_{i} \le 10^{8}\), \(0 < p_{i} < 1\)) β€” reward for completing quest before upgrade, reward for completing quest after upgrade and probability of successful completing of quest. \(a_{i}\) and \(b_{i}\) are integers. All probabilities are given with at most \(9\) decimal places.
Print the expected value.Your answer will be accepted if absolute or relative error does not exceed \(10^{-6}\). Formally, let your answer be \(a\), and the jury's answer be \(b\). Your answer is considered correct if \(\frac{|a-b|}{max⁑(b, \,\, 1)} \le 10^{-6}\).
Input: 3 23 1000 0.51 2 0.483 20 0.3 | Output: 252.2500000000000
Master
4
797
550
264
10
23
A
23A
A. You're Given a String...
1,200
brute force; greedy
You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).
The first input line contains the string. It's guaranteed, that the string is non-empty, consists of lower-case Latin letters, and its length doesn't exceed 100.
Output one number β€” length of the longest substring that can be met in the string at least twice.
Input: abcd | Output: 0
Easy
2
204
161
97
0
1,027
G
1027G
G. X-mouse in the Campus
2,600
bitmasks; math; number theory
The campus has \(m\) rooms numbered from \(0\) to \(m - 1\). Also the \(x\)-mouse lives in the campus. The \(x\)-mouse is not just a mouse: each second \(x\)-mouse moves from room \(i\) to the room \(i \cdot x \mod{m}\) (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of the \(x\)-mouse is unknown.You are responsible to catch the \(x\)-mouse in the campus, so you are guessing about minimum possible number of traps (one trap in one room) you need to place. You are sure that if the \(x\)-mouse enters a trapped room, it immediately gets caught.And the only observation you made is \(\text{GCD} (x, m) = 1\).
The only line contains two integers \(m\) and \(x\) (\(2 \le m \le 10^{14}\), \(1 \le x < m\), \(\text{GCD} (x, m) = 1\)) β€” the number of rooms and the parameter of \(x\)-mouse.
Print the only integer β€” minimum number of traps you need to install to catch the \(x\)-mouse.
In the first example you can, for example, put traps in rooms \(0\), \(2\), \(3\). If the \(x\)-mouse starts in one of this rooms it will be caught immediately. If \(x\)-mouse starts in the \(1\)-st rooms then it will move to the room \(3\), where it will be caught.In the second example you can put one trap in room \(0\) and one trap in any other room since \(x\)-mouse will visit all rooms \(1..m-1\) if it will start in any of these rooms.
Input: 4 3 | Output: 3
Expert
3
674
177
94
10
1,157
A
1157A
A. Reachable Numbers
1,100
implementation
Let's denote a function \(f(x)\) in such a way: we add \(1\) to \(x\), then, while there is at least one trailing zero in the resulting number, we remove that zero. For example, \(f(599) = 6\): \(599 + 1 = 600 \rightarrow 60 \rightarrow 6\); \(f(7) = 8\): \(7 + 1 = 8\); \(f(9) = 1\): \(9 + 1 = 10 \rightarrow 1\); \(f(10099) = 101\): \(10099 + 1 = 10100 \rightarrow 1010 \rightarrow 101\). We say that some number \(y\) is reachable from \(x\) if we can apply function \(f\) to \(x\) some (possibly zero) times so that we get \(y\) as a result. For example, \(102\) is reachable from \(10098\) because \(f(f(f(10098))) = f(f(10099)) = f(101) = 102\); and any number is reachable from itself.You are given a number \(n\); your task is to count how many different numbers are reachable from \(n\).
The first line contains one integer \(n\) (\(1 \le n \le 10^9\)).
Print one integer: the number of different numbers that are reachable from \(n\).
The numbers that are reachable from \(1098\) are:\(1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1098, 1099\).
Input: 1098 | Output: 20
Easy
1
796
65
81
11
459
E
459E
E. Pashmak and Graph
1,900
dp; sortings
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
The first line contains two integers n, m (2 ≀ n ≀ 3Β·105; 1 ≀ m ≀ min(nΒ·(n - 1), 3Β·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≀ ui, vi ≀ n; 1 ≀ wi ≀ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi.It's guaranteed that the graph doesn't contain self-loops and multiple edges.
Print a single integer β€” the answer to the problem.
In the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Input: 3 31 2 12 3 13 1 1 | Output: 1
Hard
2
593
375
51
4
12
B
12B
B. Correct Solution?
1,100
implementation; sortings
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number n to Bob and said:β€”Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroes.β€”No problem! β€” said Bob and immediately gave her an answer.Alice said a random number, so she doesn't know whether Bob's answer is correct. Help her to find this out, because impatient brother is waiting for the verdict.
The first line contains one integer n (0 ≀ n ≀ 109) without leading zeroes. The second lines contains one integer m (0 ≀ m ≀ 109) β€” Bob's answer, possibly with leading zeroes.
Print OK if Bob's answer is correct and WRONG_ANSWER otherwise.
Input: 33101033 | Output: OK
Easy
2
538
175
63
0
1,101
D
1101D
D. GCD Counting
2,000
data structures; dfs and similar; dp; number theory; trees
You are given a tree consisting of \(n\) vertices. A number is written on each vertex; the number on vertex \(i\) is equal to \(a_i\).Let's denote the function \(g(x, y)\) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex \(x\) to vertex \(y\) (including these two vertices). Also let's denote \(dist(x, y)\) as the number of vertices on the simple path between vertices \(x\) and \(y\), including the endpoints. \(dist(x, x) = 1\) for every vertex \(x\).Your task is calculate the maximum value of \(dist(x, y)\) among such pairs of vertices that \(g(x, y) > 1\).
The first line contains one integer \(n\) β€” the number of vertices \((1 \le n \le 2 \cdot 10^5)\).The second line contains \(n\) integers \(a_1\), \(a_2\), ..., \(a_n\) \((1 \le a_i \le 2 \cdot 10^5)\) β€” the numbers written on vertices.Then \(n - 1\) lines follow, each containing two integers \(x\) and \(y\) \((1 \le x, y \le n, x \ne y)\) denoting an edge connecting vertex \(x\) with vertex \(y\). It is guaranteed that these edges form a tree.
If there is no pair of vertices \(x, y\) such that \(g(x, y) > 1\), print \(0\). Otherwise print the maximum value of \(dist(x, y)\) among such pairs.
Input: 32 3 41 22 3 | Output: 1
Hard
5
625
448
150
11
1,080
D
1080D
D. Olya and magical square
2,000
constructive algorithms; implementation; math
Recently, Olya received a magical square with the size of \(2^n\times 2^n\).It seems to her sister that one square is boring. Therefore, she asked Olya to perform exactly \(k\) splitting operations.A Splitting operation is an operation during which Olya takes a square with side \(a\) and cuts it into 4 equal squares with side \(\dfrac{a}{2}\). If the side of the square is equal to \(1\), then it is impossible to apply a splitting operation to it (see examples for better understanding).Olya is happy to fulfill her sister's request, but she also wants the condition of Olya's happiness to be satisfied after all operations.The condition of Olya's happiness will be satisfied if the following statement is fulfilled:Let the length of the side of the lower left square be equal to \(a\), then the length of the side of the right upper square should also be equal to \(a\). There should also be a path between them that consists only of squares with the side of length \(a\). All consecutive squares on a path should have a common side.Obviously, as long as we have one square, these conditions are met. So Olya is ready to fulfill her sister's request only under the condition that she is satisfied too. Tell her: is it possible to perform exactly \(k\) splitting operations in a certain order so that the condition of Olya's happiness is satisfied? If it is possible, tell also the size of the side of squares of which the path from the lower left square to the upper right one will consist.
The first line contains one integer \(t\) (\(1 \le t \le 10^3\)) β€” the number of tests.Each of the following \(t\) lines contains two integers \(n_i\) and \(k_i\) (\(1 \le n_i \le 10^9, 1 \le k_i \le 10^{18}\)) β€” the description of the \(i\)-th test, which means that initially Olya's square has size of \(2^{n_i}\times 2^{n_i}\) and Olya's sister asks her to do exactly \(k_i\) splitting operations.
Print \(t\) lines, where in the \(i\)-th line you should output ""YES"" if it is possible to perform \(k_i\) splitting operations in the \(i\)-th test in such a way that the condition of Olya's happiness is satisfied or print ""NO"" otherwise. If you printed ""YES"", then also print the \(log_2\) of the length of the side of the squares through space, along which you can build a path from the lower left square to the upper right one.You can output each letter in any case (lower or upper).If there are multiple answers, print any.
In each of the illustrations, the pictures are shown in order in which Olya applied the operations. The recently-created squares are highlighted with red.In the first test, Olya can apply splitting operations in the following order: Olya applies one operation on the only existing square. The condition of Olya's happiness will be met, since there is a path of squares of the same size from the lower left square to the upper right one: The length of the sides of the squares on the path is \(1\). \(log_2(1) = 0\).In the second test, Olya can apply splitting operations in the following order: Olya applies the first operation on the only existing square. She applies the second one on the right bottom square. The condition of Olya's happiness will be met, since there is a path of squares of the same size from the lower left square to the upper right one: The length of the sides of the squares on the path is \(2\). \(log_2(2) = 1\).In the third test, it takes \(5\) operations for Olya to make the square look like this: Since it requires her to perform \(7\) splitting operations, and it is impossible to perform them on squares with side equal to \(1\), then Olya cannot do anything more and the answer is ""NO"".
Input: 3 1 1 2 2 2 12 | Output: YES 0 YES 1 NO
Hard
3
1,494
400
534
10
1,468
H
1468H
H. K and Medians
2,200
constructive algorithms; greedy; math
Let's denote the median of a sequence \(s\) with odd length as the value in the middle of \(s\) if we sort \(s\) in non-decreasing order. For example, let \(s = [1, 2, 5, 7, 2, 3, 12]\). After sorting, we get sequence \([1, 2, 2, \underline{3}, 5, 7, 12]\), and the median is equal to \(3\).You have a sequence of \(n\) integers \([1, 2, \dots, n]\) and an odd integer \(k\).In one step, you choose any \(k\) elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them).For example, if you have a sequence \([1, 2, 3, 4, 5, 6, 7]\) (i.e. \(n=7\)) and \(k = 3\), then the following options for the first step are possible: choose \([1, \underline{2}, 3]\); \(2\) is their median, so it is not erased, and the resulting sequence is \([2, 4, 5, 6, 7]\); choose \([2, \underline{4}, 6]\); \(4\) is their median, so it is not erased, and the resulting sequence is \([1, 3, 4, 5, 7]\); choose \([1, \underline{6}, 7]\); \(6\) is their median, so it is not erased, and the resulting sequence is \([2, 3, 4, 5, 6]\); and several others. You can do zero or more steps. Can you get a sequence \(b_1\), \(b_2\), ..., \(b_m\) after several steps?You'll be given \(t\) test cases. Solve each test case independently.
The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases.The first line of each test case contains three integers \(n\), \(k\), and \(m\) (\(3 \le n \le 2 \cdot 10^5\); \(3 \le k \le n\); \(k\) is odd; \(1 \le m < n\)) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get.The second line of each test case contains \(m\) integers \(b_1, b_2, \dots, b_m\) (\(1 \le b_1 < b_2 < \dots < b_m \le n\)) β€” the sequence you'd like to get, given in the ascending order.It's guaranteed that the total sum of \(n\) over all test cases doesn't exceed \(2 \cdot 10^5\).
For each test case, print YES if you can obtain the sequence \(b\) or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).
In the first test case, you have sequence \([1, 2, 3]\). Since \(k = 3\) you have only one way to choose \(k\) elements β€” it's to choose all elements \([1, \underline{2}, 3]\) with median \(2\). That's why after erasing all chosen elements except its median you'll get sequence \([2]\). In other words, there is no way to get sequence \(b = [1]\) as the result. In the second test case, you have sequence \([1, 2, 3, 4, 5, 6, 7]\) and one of the optimal strategies is following: choose \(k = 3\) elements \([2, \underline{3}, 4]\) and erase them except its median; you'll get sequence \([1, 3, 5, 6, 7]\); choose \(3\) elements \([3, \underline{5}, 6]\) and erase them except its median; you'll get desired sequence \([1, 5, 7]\); In the fourth test case, you have sequence \([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]\). You can choose \(k=7\) elements \([2, 4, 6, \underline{7}, 8, 10, 13]\) and erase them except its median to get sequence \(b\).
Input: 43 3 117 3 31 5 710 5 34 5 613 7 71 3 5 7 9 11 12 | Output: NO YES NO YES
Hard
3
1,298
678
198
14
119
B
119B
B. Before Exam
1,900
constructive algorithms; implementation; sortings
Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...To prepare for the exam, one has to study proofs of n theorems. It is known that there will be k examination cards on the exam and each card contains distinct theorems. Besides, no theorem is mentioned in more than one card (that is, theorems won't be mentioned in any card). During the exam several students may get the same card.We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his level of proficiency in the i-th theorem by some number ai. The level of proficiency in some card is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 100) β€” the number of theorems and the number of cards correspondingly. The second line contains n integers ai (0 ≀ ai ≀ 100), the i-th number (1 ≀ i ≀ n) corresponds to Vasya's proficiency in the i-th theorem.The third line contains number q (0 ≀ q ≀ 100) β€” the number of people that have taken the exam before Vasya. Each of the following q lines contains the description of a student's card: integers from 1 to n inclusive. They are the numbers of theorems included in the card in the order in which they are enumerated in the input data. The numbers are given in an arbitrary order. It is guaranteed that the given cards are valid (that is, that all theorems in one card are different and that different people get cards that either don't contain the same theorems or coincide up to the theorems' permutation).
Print two real numbers, representing Vasya's minimum and maximum proficiency in the card he will get on the exam. The absolute or relative error should not exceed 10 - 6.
Let's analyze the first sample. Vasya's proficiency in the cards whose content he already knows equals 6 and 15.5 correspondingly. The three theorems that are left are only enough to make one exam card. If we consider all possible variants of theorems included in the card we can see that in the best case scenario Vasya gets the card that contains theorems 4 and 7 (his proficiency would equal 15.5) and in the worst case scenario he gets theorems 3 and 5 (his proficiency would equal 5).The ⌊ xβŒ‹ operation denotes taking integer part of real number x (rounding down).
Input: 7 37 15 0 19 10 5 1221 67 4 | Output: 5.0000000000 15.5000000000
Hard
3
1,239
871
170
1
1,716
F
1716F
F. Bags with Balls
2,500
combinatorics; dp; math; number theory
There are \(n\) bags, each bag contains \(m\) balls with numbers from \(1\) to \(m\). For every \(i \in [1, m]\), there is exactly one ball with number \(i\) in each bag.You have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball \(1\) from the first bag and the ball \(2\) from the second bag is not the same as taking the ball \(2\) from the first bag and the ball \(1\) from the second bag). After that, you calculate the number of balls with odd numbers among the ones you have taken. Let the number of these balls be \(F\).Your task is to calculate the sum of \(F^k\) over all possible ways to take \(n\) balls, one from each bag.
The first line contains one integer \(t\) (\(1 \le t \le 5000\)) β€” the number of test cases.Each test case consists of one line containing three integers \(n\), \(m\) and \(k\) (\(1 \le n, m \le 998244352\); \(1 \le k \le 2000\)).
For each test case, print one integer β€” the sum of \(F^k\) over all possible ways to take \(n\) balls, one from each bag. Since it can be huge, print it modulo \(998244353\).
Input: 52 3 81 1 11 5 103 7 20001337666 42424242 2000 | Output: 1028 1 3 729229716 652219904
Expert
4
681
230
174
17
744
E
744E
E. Hongcow Masters the Cyclic Shift
3,200
strings; two pointers
Hongcow's teacher heard that Hongcow had learned about the cyclic shift, and decided to set the following problem for him.You are given a list of n strings s1, s2, ..., sn contained in the list A.A list X of strings is called stable if the following condition holds.First, a message is defined as a concatenation of some elements of the list X. You can use an arbitrary element as many times as you want, and you may concatenate these elements in any arbitrary order. Let SX denote the set of of all messages you can construct from the list. Of course, this set has infinite size if your list is nonempty.Call a single message good if the following conditions hold: Suppose the message is the concatenation of k strings w1, w2, ..., wk, where each wi is an element of X. Consider the |w1| + |w2| + ... + |wk| cyclic shifts of the string. Let m be the number of these cyclic shifts of the string that are elements of SX. A message is good if and only if m is exactly equal to k. The list X is called stable if and only if every element of SX is good.Let f(L) be 1 if L is a stable list, and 0 otherwise.Find the sum of f(L) where L is a nonempty contiguous sublist of A (there are contiguous sublists in total).
The first line of input will contain a single integer n (1 ≀ n ≀ 30), denoting the number of strings in the list.The next n lines will each contain a string si ().
Print a single integer, the number of nonempty contiguous sublists that are stable.
For the first sample, there are 10 sublists to consider. Sublists [""a"", ""ab"", ""b""], [""ab"", ""b"", ""bba""], and [""a"", ""ab"", ""b"", ""bba""] are not stable. The other seven sublists are stable.For example, X = [""a"", ""ab"", ""b""] is not stable, since the message ""ab"" + ""ab"" = ""abab"" has four cyclic shifts [""abab"", ""baba"", ""abab"", ""baba""], which are all elements of SX.
Input: 4aabbbba | Output: 7
Master
2
1,210
163
83
7
1,073
C
1073C
C. Vasya and Robot
1,800
binary search; two pointers
Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell \((0, 0)\). Robot can perform the following four kinds of operations: U β€” move from \((x, y)\) to \((x, y + 1)\); D β€” move from \((x, y)\) to \((x, y - 1)\); L β€” move from \((x, y)\) to \((x - 1, y)\); R β€” move from \((x, y)\) to \((x + 1, y)\). Vasya also has got a sequence of \(n\) operations. Vasya wants to modify this sequence so after performing it the robot will end up in \((x, y)\).Vasya wants to change the sequence so the length of changed subsegment is minimum possible. This length can be calculated as follows: \(maxID - minID + 1\), where \(maxID\) is the maximum index of a changed operation, and \(minID\) is the minimum index of a changed operation. For example, if Vasya changes RRRRRRR to RLRRLRL, then the operations with indices \(2\), \(5\) and \(7\) are changed, so the length of changed subsegment is \(7 - 2 + 1 = 6\). Another example: if Vasya changes DDDD to DDRD, then the length of changed subsegment is \(1\). If there are no changes, then the length of changed subsegment is \(0\). Changing an operation means replacing it with some operation (possibly the same); Vasya can't insert new operations into the sequence or remove them.Help Vasya! Tell him the minimum length of subsegment that he needs to change so that the robot will go from \((0, 0)\) to \((x, y)\), or tell him that it's impossible.
The first line contains one integer number \(n~(1 \le n \le 2 \cdot 10^5)\) β€” the number of operations.The second line contains the sequence of operations β€” a string of \(n\) characters. Each character is either U, D, L or R.The third line contains two integers \(x, y~(-10^9 \le x, y \le 10^9)\) β€” the coordinates of the cell where the robot should end its path.
Print one integer β€” the minimum possible length of subsegment that can be changed so the resulting sequence of operations moves the robot from \((0, 0)\) to \((x, y)\). If this change is impossible, print \(-1\).
In the first example the sequence can be changed to LULUU. So the length of the changed subsegment is \(3 - 1 + 1 = 3\).In the second example the given sequence already leads the robot to \((x, y)\), so the length of the changed subsegment is \(0\).In the third example the robot can't end his path in the cell \((x, y)\).
Input: 5RURUU-2 3 | Output: 3
Medium
2
1,426
363
212
10
1,759
B
1759B
B. Lost Permutation
800
math
A sequence of \(n\) numbers is called a permutation if it contains all integers from \(1\) to \(n\) exactly once. For example, the sequences [\(3, 1, 4, 2\)], [\(1\)] and [\(2,1\)] are permutations, but [\(1,2,1\)], [\(0,1\)] and [\(1,3,4\)] β€” are not.Polycarp lost his favorite permutation and found only some of its elements β€” the numbers \(b_1, b_2, \dots b_m\). He is sure that the sum of the lost elements equals \(s\).Determine whether one or more numbers can be appended to the given sequence \(b_1, b_2, \dots b_m\) such that the sum of the added numbers equals \(s\), and the resulting new array is a permutation?
The first line of input contains a single integer \(t\) (\(1 \le t \le 100\)) β€”the number of test cases. Then the descriptions of the test cases follow.The first line of each test set contains two integers \(m\) and \(s\) (\(1 \le m \le 50\), \(1 \le s \le 1000\))β€”-the number of found elements and the sum of forgotten numbers.The second line of each test set contains \(m\) different integers \(b_1, b_2 \dots b_m\) (\(1 \le b_i \le 50\)) β€” the elements Polycarp managed to find.
Print \(t\) lines, each of which is the answer to the corresponding test set. Print as the answer YES if you can append several elements to the array \(b\), that their sum equals \(s\) and the result will be a permutation. Output NO otherwise.You can output the answer in any case (for example, yEs, yes, Yes and YES will be recognized as positive answer).
In the test case of the example, \(m=3, s=13, b=[3,1,4]\). You can append to \(b\) the numbers \(6,2,5\), the sum of which is \(6+2+5=13\). Note that the final array will become \([3,1,4,6,2,5]\), which is a permutation.In the second test case of the example, \(m=1, s=1, b=[1]\). You cannot append one or more numbers to \([1]\) such that their sum equals \(1\) and the result is a permutation.In the third test case of the example, \(m=3, s=3, b=[1,4,2]\). You can append the number \(3\) to \(b\). Note that the resulting array will be \([1,4,2,3]\), which is a permutation.
Input: 53 133 1 41 113 31 4 22 14 35 61 2 3 4 5 | Output: YES NO YES NO YES
Beginner
1
622
481
356
17
401
C
401C
C. Team
1,400
constructive algorithms; greedy; implementation
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that: there wouldn't be a pair of any side-adjacent cards with zeroes in a row; there wouldn't be a group of three consecutive cards containing numbers one. Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.
The first line contains two integers: n (1 ≀ n ≀ 106) β€” the number of cards containing number 0; m (1 ≀ m ≀ 106) β€” the number of cards containing number 1.
In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1.
Input: 1 2 | Output: 101
Easy
3
934
155
135
4
690
C3
690C3
C3. Brain Network (hard)
2,200
trees
Breaking news from zombie neurology! It turns out that – contrary to previous beliefs – every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zombie consumes a brain, a new brain appears in its nervous system and gets immediately connected to one of the already existing brains using a single brain connector. Researchers are now interested in monitoring the brain latency of a zombie. Your task is to write a program which, given a history of evolution of a zombie's nervous system, computes its brain latency at every stage.
The first line of the input contains one number n – the number of brains in the final nervous system (2 ≀ n ≀ 200000). In the second line a history of zombie's nervous system evolution is given. For convenience, we number all the brains by 1, 2, ..., n in the same order as they appear in the nervous system (the zombie is born with a single brain, number 1, and subsequently brains 2, 3, ..., n are added). The second line contains n - 1 space-separated numbers p2, p3, ..., pn, meaning that after a new brain k is added to the system, it gets connected to a parent-brain .
Output n - 1 space-separated numbers – the brain latencies after the brain number k is added, for k = 2, 3, ..., n.
Input: 612215 | Output: 1 2 2 3 4
Hard
1
596
574
115
6
802
O
802O
O. April Fools' Problem (hard)
2,900
binary search; data structures; flows
The plans for HC2 are rather far-fetched: we are just over 500 000 days away from HC2 3387, for example, and accordingly we are planning to have a couple hundred thousand problems in that edition (we hope that programming contests will become wildly more popular). The marmots need to get to work, and they could use a good plan...
Same as the medium version, but the limits have changed: 1 ≀ k ≀ n ≀ 500 000.
Same as the medium version.
Input: 8 43 8 7 9 9 4 6 82 5 9 4 3 8 9 1 | Output: 32
Master
3
331
77
27
8
1,804
D
1804D
D. Accommodation
2,000
brute force; dp; greedy; implementation
Annie is an amateur photographer. She likes to take pictures of giant residential buildings at night. She just took a picture of a huge rectangular building that can be seen as a table of \(n \times m\) windows. That means that the building has \(n\) floors and each floor has exactly \(m\) windows. Each window is either dark or bright, meaning there is light turned on in the room behind it.Annies knows that each apartment in this building is either one-bedroom or two-bedroom. Each one-bedroom apartment has exactly one window representing it on the picture, and each two-bedroom apartment has exactly two consecutive windows on the same floor. Moreover, the value of \(m\) is guaranteed to be divisible by \(4\) and it is known that each floor has exactly \(\frac{m}{4}\) two-bedroom apartments and exactly \(\frac{m}{2}\) one-bedroom apartments. The actual layout of apartments is unknown and can be different for each floor.Annie considers an apartment to be occupied if at least one of its windows is bright. She now wonders, what are the minimum and maximum possible number of occupied apartments if judged by the given picture?Formally, for each of the floors, she comes up with some particular apartments layout with exactly \(\frac{m}{4}\) two-bedroom apartments (two consecutive windows) and \(\frac{m}{2}\) one-bedroom apartments (single window). She then counts the total number of apartments that have at least one bright window. What is the minimum and maximum possible number she can get?
The first line of the input contains two positive integers \(n\) and \(m\) (\(1 \leq n \cdot m \leq 5 \cdot 10^5\)) β€” the number of floors in the building and the number of windows per floor, respectively. It is guaranteed that \(m\) is divisible by \(4\).Then follow \(n\) lines containing \(m\) characters each. The \(j\)-th character of the \(i\)-th line is ""0"" if the \(j\)-th window on the \(i\)-th floor is dark, and is ""1"" if this window is bright.
Print two integers, the minimum possible number of occupied apartments and the maximum possible number of occupied apartments, assuming each floor can have an individual layout of \(\frac{m}{4}\) two-bedroom and \(\frac{m}{2}\) one-bedroom apartments.
In the first example, each floor consists of one two-bedroom apartment and two one-bedroom apartments.The following apartment layout achieves the minimum possible number of occupied apartments equal to \(7\). |0 1|0|0||1 1|0|0||0|1 1|0||1|0 1|0||1|0|1 1|The following apartment layout achieves the maximum possible number of occupied apartments equal to \(10\). |0 1|0|0||1|1 0|0||0 1|1|0||1|0 1|0||1 0|1|1|
Input: 5 4 0100 1100 0110 1010 1011 | Output: 7 10
Hard
4
1,506
459
251
18
390
A
390A
A. Inna and Alarm Clock
0
implementation
Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 Γ— 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square.The morning has come. All n alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game: First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal. Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off. Inna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!
The first line of the input contains integer n (1 ≀ n ≀ 105) β€” the number of the alarm clocks. The next n lines describe the clocks: the i-th line contains two integers xi, yi β€” the coordinates of the i-th alarm clock (0 ≀ xi, yi ≀ 100).Note that a single point in the room can contain any number of alarm clocks and the alarm clocks can lie on the sides of the square that represents the room.
In a single line print a single integer β€” the minimum number of segments Inna will have to draw if she acts optimally.
In the first sample, Inna first chooses type ""vertical segments"", and then she makes segments with ends at : (0, 0), (0, 2); and, for example, (1, 0), (1, 1). If she paints horizontal segments, she will need at least 3 segments.In the third sample it is important to note that Inna doesn't have the right to change the type of the segments during the game. That's why she will need 3 horizontal or 3 vertical segments to end the game.
Input: 40 00 10 21 0 | Output: 2
Beginner
1
1,072
394
118
3
596
E
596E
E. Wilbur and Strings
2,500
dfs and similar; dp; graphs; strings
Wilbur the pig now wants to play with strings. He has found an n by m table consisting only of the digits from 0 to 9 where the rows are numbered 1 to n and the columns are numbered 1 to m. Wilbur starts at some square and makes certain moves. If he is at square (x, y) and the digit d (0 ≀ d ≀ 9) is written at position (x, y), then he must move to the square (x + ad, y + bd), if that square lies within the table, and he stays in the square (x, y) otherwise. Before Wilbur makes a move, he can choose whether or not to write the digit written in this square on the white board. All digits written on the whiteboard form some string. Every time a new digit is written, it goes to the end of the current string.Wilbur has q strings that he is worried about. For each string si, Wilbur wants to know whether there exists a starting position (x, y) so that by making finitely many moves, Wilbur can end up with the string si written on the white board.
The first line of the input consists of three integers n, m, and q (1 ≀ n, m, q ≀ 200) β€” the dimensions of the table and the number of strings to process, respectively.Each of the next n lines contains m digits from 0 and 9 giving the table itself.Then follow 10 lines. The i-th of them contains the values ai - 1 and bi - 1 ( - 200 ≀ ai, bi ≀ 200), i.e. the vector that Wilbur uses to make a move from the square with a digit i - 1 in it.There are q lines that follow. The i-th of them will contain a string si consisting only of digits from 0 to 9. It is guaranteed that the total length of these q strings won't exceed 1 000 000.
For each of the q strings, print ""YES"" if Wilbur can choose x and y in order to finish with this string after some finite number of moves. If it's impossible, than print ""NO"" for the corresponding string.
In the first sample, there is a 1 by 1 table consisting of the only digit 0. The only move that can be made is staying on the square. The first string can be written on the white board by writing 0 repeatedly. The second string cannot be written as there is no 2 on the table.
Input: 1 1 201 11 11 11 11 11 11 11 11 11 100000000000002413423432432 | Output: YESNO
Expert
4
951
632
208
5
1,609
F
1609F
F. Interesting Sections
2,800
data structures; divide and conquer; meet-in-the-middle; two pointers
William has an array of non-negative numbers \(a_1, a_2, \dots, a_n\). He wants you to find out how many segments \(l \le r\) pass the check. The check is performed in the following manner: The minimum and maximum numbers are found on the segment of the array starting at \(l\) and ending at \(r\). The check is considered to be passed if the binary representation of the minimum and maximum numbers have the same number of bits equal to 1.
The first line contains a single integer \(n\) (\(1 \le n \le 10^6\)), the size of array \(a\).The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(0 \le a_i \le 10^{18}\)), the contents of array \(a\).
Output a single number β€” the total number of segments that passed the check.
Input: 5 1 2 3 4 5 | Output: 9
Master
4
440
217
76
16
321
B
321B
B. Ciel and Duel
1,900
dp; flows; greedy
Fox Ciel is playing a card game with her friend Jiro.Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.Now is Ciel's battle phase, Ciel can do the following operation many times: Choose one of her cards X. This card mustn't be chosen before. If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then: If Y's position is Attack, then (X's strength) β‰₯ (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength). If Y's position is Defense, then (X's strength) > (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage. Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.
The first line contains two integers n and m (1 ≀ n, m ≀ 100) β€” the number of cards Jiro and Ciel have.Each of the next n lines contains a string position and an integer strength (0 ≀ strength ≀ 8000) β€” the position and strength of Jiro's current card. Position is the string ""ATK"" for attack, and the string ""DEF"" for defense.Each of the next m lines contains an integer strength (0 ≀ strength ≀ 8000) β€” the strength of Ciel's current card.
Output an integer: the maximal damage Jiro can get.
In the first test case, Ciel has 3 cards with same strength. The best strategy is as follows. First she uses one of these 3 cards to attack ""ATK 2000"" card first, this attack destroys that card and Jiro gets 2500 - 2000 = 500 damage. Then she uses the second card to destroy the ""DEF 1700"" card. Jiro doesn't get damage that time. Now Jiro has no cards so she can use the third card to attack and Jiro gets 2500 damage. So the answer is 500 + 2500 = 3000.In the second test case, she should use the ""1001"" card to attack the ""ATK 100"" card, then use the ""101"" card to attack the ""ATK 10"" card. Now Ciel still has cards but she can choose to end her battle phase. The total damage equals (1001 - 100) + (101 - 10) = 992.In the third test case note that she can destroy the ""ATK 0"" card by a card with strength equal to 0, but she can't destroy a ""DEF 0"" card with that card.
Input: 2 3ATK 2000DEF 1700250025002500 | Output: 3000
Hard
3
1,001
445
51
3
1,183
F
1183F
F. Topforces Strikes Back
2,100
brute force; math; sortings
One important contest will take place on the most famous programming platform (Topforces) very soon!The authors have a pool of \(n\) problems and should choose at most three of them into this contest. The prettiness of the \(i\)-th problem is \(a_i\). The authors have to compose the most pretty contest (in other words, the cumulative prettinesses of chosen problems should be maximum possible).But there is one important thing in the contest preparation: because of some superstitions of authors, the prettinesses of problems cannot divide each other. In other words, if the prettinesses of chosen problems are \(x, y, z\), then \(x\) should be divisible by neither \(y\), nor \(z\), \(y\) should be divisible by neither \(x\), nor \(z\) and \(z\) should be divisible by neither \(x\), nor \(y\). If the prettinesses of chosen problems are \(x\) and \(y\) then neither \(x\) should be divisible by \(y\) nor \(y\) should be divisible by \(x\). Any contest composed from one problem is considered good.Your task is to find out the maximum possible total prettiness of the contest composed of at most three problems from the given pool.You have to answer \(q\) independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
The first line of the input contains one integer \(q\) (\(1 \le q \le 2 \cdot 10^5\)) β€” the number of queries.The first line of the query contains one integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the number of problems.The second line of the query contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(2 \le a_i \le 2 \cdot 10^5\)), where \(a_i\) is the prettiness of the \(i\)-th problem.It is guaranteed that the sum of \(n\) over all queries does not exceed \(2 \cdot 10^5\).
For each query print one integer β€” the maximum possible cumulative prettiness of the contest composed of at most three problems from the given pool of problems in the query.
Input: 3 4 5 6 15 30 4 10 6 30 15 3 3 4 6 | Output: 30 31 10
Hard
3
1,275
478
173
11
1,592
B
1592B
B. Hemose Shopping
1,200
constructive algorithms; dsu; math; sortings
Hemose was shopping with his friends Samez, AhmedZ, AshrafEzz, TheSawan and O_E in Germany. As you know, Hemose and his friends are problem solvers, so they are very clever. Therefore, they will go to all discount markets in Germany.Hemose has an array of \(n\) integers. He wants Samez to sort the array in the non-decreasing order. Since it would be a too easy problem for Samez, Hemose allows Samez to use only the following operation:Choose indices \(i\) and \(j\) such that \(1 \le i, j \le n\), and \(\lvert i - j \rvert \geq x\). Then, swap elements \(a_i\) and \(a_j\).Can you tell Samez if there's a way to sort the array in the non-decreasing order by using the operation written above some finite number of times (possibly \(0\))?
Each test contains multiple test cases. The first line contains the number of test cases \(t\) \((1 \leq t \leq 10^5)\). Description of the test cases follows.The first line of each test case contains two integers \(n\) and \(x\) \((1 \leq x \leq n \leq 10^5)\).The second line of each test case contains \(n\) integers \(a_1, a_2, ..., a_n\) \((1 \leq a_i \leq 10^9)\).It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(2 \cdot 10^5\).
For each test case, you should output a single string. If Samez can sort the array in non-decreasing order using the operation written above, output ""YES"" (without quotes). Otherwise, output ""NO"" (without quotes).You can print each letter of ""YES"" and ""NO"" in any case (upper or lower).
In the first test case, you can't do any operations.In the second test case, the array is already sorted.In the third test case, you can do the operations as follows: \([5,1,2,3,4]\), \(swap(a_1,a_3)\) \([2,1,5,3,4]\), \(swap(a_2,a_5)\) \([2,4,5,3,1]\), \(swap(a_2,a_4)\) \([2,3,5,4,1]\), \(swap(a_1,a_5)\) \([1,3,5,4,2]\), \(swap(a_2,a_5)\) \([1,2,5,4,3]\), \(swap(a_3,a_5)\) \([1,2,3,4,5]\) (Here \(swap(a_i, a_j)\) refers to swapping elements at positions \(i\), \(j\)).
Input: 4 3 3 3 2 1 4 3 1 2 3 4 5 2 5 1 2 3 4 5 4 1 2 3 4 4 | Output: NO YES YES YES
Easy
4
741
461
294
15
1,670
E
1670E
E. Hemose on the Tree
2,200
bitmasks; constructive algorithms; dfs and similar; trees
After the last regional contest, Hemose and his teammates finally qualified to the ICPC World Finals, so for this great achievement and his love of trees, he gave you this problem as the name of his team ""Hemose 3al shagra"" (Hemose on the tree).You are given a tree of \(n\) vertices where \(n\) is a power of \(2\). You have to give each node and edge an integer value in the range \([1,2n -1]\) (inclusive), where all the values are distinct.After giving each node and edge a value, you should select some root for the tree such that the maximum cost of any simple path starting from the root and ending at any node or edge is minimized.The cost of the path between two nodes \(u\) and \(v\) or any node \(u\) and edge \(e\) is defined as the bitwise XOR of all the node's and edge's values between them, including the endpoints (note that in a tree there is only one simple path between two nodes or between a node and an edge).
The first line contains a single integer \(t\) (\(1 \le t \le 5\cdot 10^4\)) β€” the number of test cases. Then \(t\) test cases follow.The first line of each test case contains a single integer \(p\) (\(1 \le p \le 17\)), where \(n\) (the number of vertices in the tree) is equal to \(2^p\).Each of the next \(nβˆ’1\) lines contains two integers \(u\) and \(v\) (\(1 \le u,v \le n\)) meaning that there is an edge between the vertices \(u\) and \(v\) in the tree.It is guaranteed that the given graph is a tree.It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(3\cdot 10^5\).
For each test case on the first line print the chosen root.On the second line, print \(n\) integers separated by spaces, where the \(i\)-th integer represents the chosen value for the \(i\)-th node.On the third line, print \(n-1\) integers separated by spaces, where the \(i\)-th integer represents the chosen value for the \(i\)-th edge. The edges are numerated in the order of their appearance in the input data.If there are multiple solutions, you may output any.
The tree in the first test case with the weights of all nodes and edges is shown in the picture. The costs of all paths are: \(3\); \(3\oplus 7=4\); \(3\oplus 7\oplus 6=2\); \(3\oplus 2=1\); \(3\oplus 2\oplus 1=0\); \(3\oplus 2\oplus 1\oplus 4=4\); \(3\oplus 2\oplus 1\oplus 4\oplus 5=1\). The maximum cost of all these paths is \(4\). We can show that it is impossible to assign the values and choose the root differently to achieve a smaller maximum cost of all paths.The tree in the second test case:
Input: 221 22 33 431 22 33 41 51 65 75 8 | Output: 3 5 1 3 6 4 2 7 5 1 2 8 11 4 13 9 15 6 14 3 7 10 5 12
Hard
4
933
598
466
16
730
F
730F
F. Ber Patio
3,100
Polycarp is a regular customer at the restaurant ""Ber Patio"". He likes having lunches there.""Ber Patio"" has special discount program for regular customers. A customer can collect bonuses and partially cover expenses in the restaurant.Let's assume a customer currently has b bonuses and she has to pay r burles for a lunch. In this case the customer can use bonuses (1 bonus = 1 burle) to reduce the payment. She can cover at most half of the payment using bonuses. However, 1 bonus will be added to the customer's bonus balance per each 10 burles she paid.Formally: a customer can choose any number x of bonuses to use ()), the customer's bonus balance is reduced by x, the customer pays r - x burles, the customer's bonus balance is increased by ⌊(r - x) / 10βŒ‹ (i.e. integer division rounded down is used). Initially, there are b bonuses on Polycarp's account. Polycarp is going to have a lunch in ""Ber Patio"" for the next n days. He estimated the values a1, a2, ..., an, where ai is the number of burles in a receipt for the i-th day. The sum over all receipts doesn't exceed 105 burles.Write a program to find the minimum number of burles Polycarp has to spend and an optimal strategy to use bonuses.
The first line contains two integer numbers n and b (1 ≀ n ≀ 5000, 0 ≀ b ≀ 105) β€” number of days and initial number of bonuses Polycarp has.The second line contains the integer sequence a1, a2, ..., an (1 ≀ ai ≀ 1000), where ai is the amount of burles in the i-th day's receipt.It is guaranteed that the sum of all receipts does not exceed 105 burles.
On the first line, print the expected minimal number of burles to pay for all n receipts.On the second line, print the sequence of integer numbers b1, b2, ..., bn, where bi is the number of bonuses to use on the i-th day. If there are multiple solutions, print any of them.
Input: 3 2112 75 52 | Output: 1102 5 22
Master
0
1,209
351
273
7
1,764
G2
1764G2
G2. Doremy's Perfect DS Class (Medium Version)
3,000
binary search; interactive
The only difference between this problem and the other two versions is the maximum number of queries. In this version, you are allowed to ask at most \(\mathbf{25}\) queries. You can make hacks only if all versions of the problem are solved.This is an interactive problem.""Everybody! Doremy's Perfect Data Structure Class is about to start! Come and do your best if you want to have as much IQ as me!"" In today's Data Structure class, Doremy is teaching everyone a powerful data structure β€” Doremy tree! Now she gives you a quiz to prove that you are paying attention in class.Given an array \(a\) of length \(m\), Doremy tree supports the query \(Q(l,r,k)\), where \(1 \leq l \leq r \leq m\) and \(1 \leq k \leq m\), which returns the number of distinct integers in the array \(\left[\lfloor\frac{a_l}{k} \rfloor, \lfloor\frac{a_{l+1}}{k} \rfloor, \ldots, \lfloor\frac{a_r}{k} \rfloor\right]\).Doremy has a secret permutation \(p\) of integers from \(1\) to \(n\). You can make queries, in one query, you give \(3\) integers \(l,r,k\) (\(1 \leq l \leq r \leq n\), \(1 \leq k \leq n\)) and receive the value of \(Q(l,r,k)\) for the array \(p\). Can you find the index \(y\) (\(1 \leq y \leq n\)) such that \(p_y=1\) in at most \(\mathbf{25}\) queries?Note that the permutation \(p\) is fixed before any queries are made.
The permutation in the example is \([3,5,2,1,4]\).The input and output for example illustrate possible interaction on that test (empty lines are inserted only for clarity).In this interaction process: For the first query, \(\lfloor\frac{3}{4}\rfloor=0,\lfloor\frac{5}{4}\rfloor=1,\lfloor\frac{2}{4}\rfloor=0\), so the answer is \(2\). For the second query, \(\lfloor\frac{2}{3}\rfloor=0,\lfloor\frac{1}{3}\rfloor=0,\lfloor\frac{4}{3}\rfloor=1\), so the answer is still \(2\). For the third query, \(\lfloor\frac{2}{5}\rfloor=0,\lfloor\frac{1}{5}\rfloor=0\), so the answer is \(1\). For the fourth query, \(\lfloor\frac{2}{2}\rfloor=1,\lfloor\frac{1}{2}\rfloor=0,\lfloor\frac{4}{2}\rfloor=2\), so the answer is \(3\). The correct answer is got after \(4\) queries, so this process will be judged correct.
Input: 5 2 2 1 3 | Output: ? 1 3 4 ? 3 5 3 ? 3 4 5 ? 3 5 2 ! 4
Master
2
1,322
0
0
17
691
E
691E
E. Xor-sequences
1,900
matrices
You are given n integers a1, a2, ..., an.A sequence of integers x1, x2, ..., xk is called a ""xor-sequence"" if for every 1 ≀ i ≀ k - 1 the number of ones in the binary representation of the number xi xi + 1's is a multiple of 3 and for all 1 ≀ i ≀ k. The symbol is used for the binary exclusive or operation.How many ""xor-sequences"" of length k exist? Output the answer modulo 109 + 7.Note if a = [1, 1] and k = 1 then the answer is 2, because you should consider the ones from a as different.
The first line contains two integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1018) β€” the number of given integers and the length of the ""xor-sequences"".The second line contains n integers ai (0 ≀ ai ≀ 1018).
Print the only integer c β€” the number of ""xor-sequences"" of length k modulo 109 + 7.
Input: 5 215 1 2 4 8 | Output: 13
Hard
1
496
199
86
6
1,090
F
1090F
2,600
constructive algorithms; interactive
Expert
2
0
0
0
10
1,829
G
1829G
G. Hits Different
1,600
data structures; dp; implementation; math
In a carnival game, there is a huge pyramid of cans with \(2023\) rows, numbered in a regular pattern as shown. If can \(9^2\) is hit initially, then all cans colored red in the picture above would fall. You throw a ball at the pyramid, and it hits a single can with number \(n^2\). This causes all cans that are stacked on top of this can to fall (that is, can \(n^2\) falls, then the cans directly above \(n^2\) fall, then the cans directly above those cans, and so on). For example, the picture above shows the cans that would fall if can \(9^2\) is hit.What is the sum of the numbers on all cans that fall? Recall that \(n^2 = n \times n\).
The first line contains an integer \(t\) (\(1 \leq t \leq 1000\)) β€” the number of test cases.The only line of each test case contains a single integer \(n\) (\(1 \leq n \leq 10^6\)) β€” it means that the can you hit has label \(n^2\).
For each test case, output a single integer β€” the sum of the numbers on all cans that fall.Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++). For all valid inputs, the answer will always fit into 64-bit integer type.
The first test case is pictured in the statement. The sum of the numbers that fall is $$$\(1^2 + 2^2 + 3^2 + 5^2 + 6^2 + 9^2 = 1 + 4 + 9 + 25 + 36 + 81 = 156.\)\(In the second test case, only the can labeled \)1^2\( falls, so the answer is \)1^2=1\(.In the third test case, the cans labeled \)1^2\( and \)2^2\( fall, so the answer is \)1^2+2^2=1+4=5\(.In the fourth test case, the cans labeled \)1^2\( and \)3^2\( fall, so the answer is \)1^2+3^2=1+9=10\(.In the fifth test case, the cans labeled \)1^2\(, \)2^2\(, and \)4^2\( fall, so the answer is \)1^2+2^2+4^2=1+4+16=21$$$.
Input: 1091234561014341000000 | Output: 156 1 5 10 21 39 46 146 63145186 58116199242129511
Medium
4
644
232
352
18
1,179
B
1179B
B. Tolik and His Uncle
1,800
constructive algorithms
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a ""Discuss tasks"" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task.In this task you are given a cell field \(n \cdot m\), consisting of \(n\) rows and \(m\) columns, where point's coordinates \((x, y)\) mean it is situated in the \(x\)-th row and \(y\)-th column, considering numeration from one (\(1 \leq x \leq n, 1 \leq y \leq m\)). Initially, you stand in the cell \((1, 1)\). Every move you can jump from cell \((x, y)\), which you stand in, by any non-zero vector \((dx, dy)\), thus you will stand in the \((x+dx, y+dy)\) cell. Obviously, you can't leave the field, but also there is one more important condition β€” you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited).Tolik's uncle is a very respectful person. Help him to solve this task!
The first and only line contains two positive integers \(n, m\) (\(1 \leq n \cdot m \leq 10^{6}\)) β€” the number of rows and columns of the field respectively.
Print ""-1"" (without quotes) if it is impossible to visit every cell exactly once.Else print \(n \cdot m\) pairs of integers, \(i\)-th from them should contain two integers \(x_i, y_i\) (\(1 \leq x_i \leq n, 1 \leq y_i \leq m\)) β€” cells of the field in order of visiting, so that all of them are distinct and vectors of jumps between them are distinct too.Notice that the first cell should have \((1, 1)\) coordinates, according to the statement.
The vectors from the first example in the order of making jumps are \((0, 2), (0, -1), (1, 0), (0, 1), (0, -2)\).
Input: 2 3 | Output: 1 1 1 3 1 2 2 2 2 3 2 1
Medium
1
1,268
158
447
11
1,408
A
1408A
A. Circle Coloring
800
constructive algorithms
You are given three sequences: \(a_1, a_2, \ldots, a_n\); \(b_1, b_2, \ldots, b_n\); \(c_1, c_2, \ldots, c_n\).For each \(i\), \(a_i \neq b_i\), \(a_i \neq c_i\), \(b_i \neq c_i\).Find a sequence \(p_1, p_2, \ldots, p_n\), that satisfy the following conditions: \(p_i \in \{a_i, b_i, c_i\}\) \(p_i \neq p_{(i \mod n) + 1}\).In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements \(i,i+1\) adjacent for \(i<n\) and also elements \(1\) and \(n\)) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
The first line of input contains one integer \(t\) (\(1 \leq t \leq 100\)): the number of test cases.The first line of each test case contains one integer \(n\) (\(3 \leq n \leq 100\)): the number of elements in the given sequences.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 100\)).The third line contains \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(1 \leq b_i \leq 100\)).The fourth line contains \(n\) integers \(c_1, c_2, \ldots, c_n\) (\(1 \leq c_i \leq 100\)).It is guaranteed that \(a_i \neq b_i\), \(a_i \neq c_i\), \(b_i \neq c_i\) for all \(i\).
For each test case, print \(n\) integers: \(p_1, p_2, \ldots, p_n\) (\(p_i \in \{a_i, b_i, c_i\}\), \(p_i \neq p_{i \mod n + 1}\)).If there are several solutions, you can print any.
In the first test case \(p = [1, 2, 3]\).It is a correct answer, because: \(p_1 = 1 = a_1\), \(p_2 = 2 = b_2\), \(p_3 = 3 = c_3\) \(p_1 \neq p_2 \), \(p_2 \neq p_3 \), \(p_3 \neq p_1\) All possible correct answers to this test case are: \([1, 2, 3]\), \([1, 3, 2]\), \([2, 1, 3]\), \([2, 3, 1]\), \([3, 1, 2]\), \([3, 2, 1]\).In the second test case \(p = [1, 2, 1, 2]\).In this sequence \(p_1 = a_1\), \(p_2 = a_2\), \(p_3 = a_3\), \(p_4 = a_4\). Also we can see, that no two adjacent elements of the sequence are equal.In the third test case \(p = [1, 3, 4, 3, 2, 4, 2]\).In this sequence \(p_1 = a_1\), \(p_2 = a_2\), \(p_3 = b_3\), \(p_4 = b_4\), \(p_5 = b_5\), \(p_6 = c_6\), \(p_7 = c_7\). Also we can see, that no two adjacent elements of the sequence are equal.
Input: 5 3 1 1 1 2 2 2 3 3 3 4 1 2 1 2 2 1 2 1 3 4 3 4 7 1 3 3 1 1 1 1 2 4 4 3 2 2 4 4 2 2 2 4 4 2 3 1 2 1 2 3 3 3 1 2 10 1 1 1 2 2 2 3 3 3 1 2 2 2 3 3 3 1 1 1 2 3 3 3 1 1 1 2 2 2 3 | Output: 1 2 3 1 2 1 2 1 3 4 3 2 4 2 1 3 2 1 2 3 1 2 3 1 2 3 2
Beginner
1
716
596
181
14
130
E
130E
E. Tribonacci numbers
1,600
*special
Tribonacci numbers are a sequence of numbers, defined as follows: t0 = t1 = 0, t2 = 1, ti = ti - 1 + ti - 2 + ti - 3.You are given n; calculate n-th tribonacci number modulo 26.
The only line of input contains an integer n (1 ≀ n ≀ 1000).
Output n-th tribonacci number modulo 26.
Input: 4 | Output: 2
Medium
1
177
60
40
1
391
F2
391F2
F2. Stock Trading
0
greedy
This problem consists of three subproblems: for solving subproblem F1 you will receive 8 points, for solving subproblem F2 you will receive 15 points, and for solving subproblem F3 you will receive 10 points.Manao has developed a model to predict the stock price of a company over the next n days and wants to design a profit-maximizing trading algorithm to make use of these predictions. Unfortunately, Manao's trading account has the following restrictions: It only allows owning either zero or one shares of stock at a time; It only allows buying or selling a share of this stock once per day; It allows a maximum of k buy orders over the next n days; For the purposes of this problem, we define a trade to a be the act of buying one share of stock on day i, then holding the stock until some day j > i at which point the share is sold. To restate the above constraints, Manao is permitted to make at most k non-overlapping trades during the course of an n-day trading period for which Manao's model has predictions about the stock price.Even though these restrictions limit the amount of profit Manao can make compared to what would be achievable with an unlimited number of trades or the ability to hold more than one share at a time, Manao still has the potential to make a lot of money because Manao's model perfectly predicts the daily price of the stock. For example, using this model, Manao could wait until the price is low, then buy one share and hold until the price reaches a high value, then sell for a profit, and repeat this process up to k times until n days have passed.Nevertheless, Manao is not satisfied by having a merely good trading algorithm, and wants to develop an optimal strategy for trading subject to these constraints. Help Manao achieve this goal by writing a program that will determine when to buy and sell stock to achieve the greatest possible profit during the n-day trading period subject to the above constraints.
The first line contains two integers n and k, separated by a single space, with . The i-th of the following n lines contains a single integer pi (0 ≀ pi ≀ 1012), where pi represents the price at which someone can either buy or sell one share of stock on day i.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 F1 (8 points), n will be between 1 and 3000, inclusive. In subproblem F2 (15 points), n will be between 1 and 100000, inclusive. In subproblem F3 (10 points), n will be between 1 and 4000000, inclusive.
For this problem, the program will only report the amount of the optimal profit, rather than a list of trades that can achieve this profit.Therefore, the program should print one line containing a single integer, the maximum profit Manao can achieve over the next n days with the constraints of starting with no shares on the first day of trading, always owning either zero or one shares of stock, and buying at most k shares over the course of the n-day trading period.
In the first example, the best trade overall is to buy at a price of 1 on day 9 and sell at a price of 9 on day 10 and the second best trade overall is to buy at a price of 2 on day 1 and sell at a price of 9 on day 4. Since these two trades do not overlap, both can be made and the profit is the sum of the profits of the two trades. Thus the trade strategy looks like this: 2 | 7 | 3 | 9 | 8 | 7 | 9 | 7 | 1 | 9buy | | | sell | | | | | buy | sellThe total profit is then (9 - 2) + (9 - 1) = 15.In the second example, even though Manao is allowed up to 5 trades there are only 4 profitable trades available. Making a fifth trade would cost Manao money so he only makes the following 4: 2 | 7 | 3 | 9 | 8 | 7 | 9 | 7 | 1 | 9buy | sell | buy | sell | | buy | sell | | buy | sellThe total profit is then (7 - 2) + (9 - 3) + (9 - 7) + (9 - 1) = 21.
Input: 10 22739879719 | Output: 15
Beginner
1
1,954
690
470
3
1,958
F
1958F
F. Narrow Paths
2,000
*special; combinatorics
Monocarp is wandering through a matrix consisting of \(2\) rows and \(n\) columns. Let's denote the cell in the \(i\)-th row and \(j\)-th column as \((i, j)\). Monocarp starts at cell \((1, 1)\) and wants to reach cell \((2, n)\).In one move, Monocarp can move in one of two directions: right β€” from cell \((i, j)\) to cell \((i, j + 1)\); down β€” from cell \((i, j)\) to cell \((i + 1, j)\). Monocarp can't go outside the matrix.Polycarp wants to prevent Monocarp from freely wandering through the matrix. To do this, he wants to choose exactly \(k\) different cells in the matrix and block them. He cannot choose cells \((1, 1)\) and \((2, n)\).For each \(i\) from \(0\) to \(n\), Polycarp wants to know how many ways he can block exactly \(k\) cells, so that Monocarp has exactly \(i\) different paths from \((1, 1)\) to \((2, n)\). Two paths are considered different if there exists a cell that Monocarp visits in one path but not in the other.As the number of ways can be quite large, output it modulo \(10^9 + 7\).
The only line contains two integers \(n\) and \(k\) (\(2 \le n \le 2 \cdot 10^5\); \(2 \le k \le 2 \cdot n - 2\)) β€” the number of columns in the matrix and the number of cells Polycarp wants to block.
Output \(n + 1\) integers: for each \(i\) from \(0\) to \(n\), the number of ways to block exactly \(k\) cells, so that Monocarp has exactly \(i\) different paths from \((1, 1)\) to \((2, n)\). Output all answers modulo \(10^9 + 7\).
Input: 2 2 | Output: 1 0 0
Hard
2
1,019
200
233
19