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
712
E
712E
E. Memory and Casinos
2,500
data structures; math; probabilities
There are n casinos lined in a row. If Memory plays at casino i, he has probability pi to win and move to the casino on the right (i + 1) or exit the row (if i = n), and a probability 1 - pi to lose and move to the casino on the left (i - 1) or also exit the row (if i = 1). We say that Memory dominates on the interval i... j if he completes a walk such that, He starts on casino i. He never looses in casino i. He finishes his walk by winning in casino j. Note that Memory can still walk left of the 1-st casino and right of the casino n and that always finishes the process.Now Memory has some requests, in one of the following forms: 1 i a b: Set . 2 l r: Print the probability that Memory will dominate on the interval l... r, i.e. compute the probability that Memory will first leave the segment l... r after winning at casino r, if she starts in casino l. It is guaranteed that at any moment of time p is a non-decreasing sequence, i.e. pi ≀ pi + 1 for all i from 1 to n - 1.Please help Memory by answering all his requests!
The first line of the input contains two integers n and q(1 ≀ n, q ≀ 100 000), β€” number of casinos and number of requests respectively.The next n lines each contain integers ai and bi (1 ≀ ai < bi ≀ 109) β€” is the probability pi of winning in casino i.The next q lines each contain queries of one of the types specified above (1 ≀ a < b ≀ 109, 1 ≀ i ≀ n, 1 ≀ l ≀ r ≀ n).It's guaranteed that there will be at least one query of type 2, i.e. the output will be non-empty. Additionally, it is guaranteed that p forms a non-decreasing sequence at all times.
Print a real number for every request of type 2 β€” the probability that boy will ""dominate"" on that interval. Your answer will be considered correct if its absolute error does not exceed 10 - 4.Namely: let's assume that one of your answers is a, and the corresponding answer of the jury is b. The checker program will consider your answer correct if |a - b| ≀ 10 - 4.
Input: 3 131 31 22 32 1 12 1 22 1 32 2 22 2 32 3 31 2 2 32 1 12 1 22 1 32 2 22 2 32 3 3 | Output: 0.33333333330.20000000000.16666666670.50000000000.40000000000.66666666670.33333333330.25000000000.22222222220.66666666670.57142857140.6666666667
Expert
3
1,031
552
368
7
1,830
D
1830D
D. Mex Tree
2,800
brute force; dp; trees
You are given a tree with \(n\) nodes. For each node, you either color it in \(0\) or \(1\).The value of a path \((u,v)\) is equal to the MEX\(^\dagger\) of the colors of the nodes from the shortest path between \(u\) and \(v\).The value of a coloring is equal to the sum of values of all paths \((u,v)\) such that \(1 \leq u \leq v \leq n\).What is the maximum possible value of any coloring of the tree?\(^{\dagger}\) The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance: The MEX of \([2,2,1]\) is \(0\), because \(0\) does not belong to the array. The MEX of \([3,1,0,1]\) is \(2\), because \(0\) and \(1\) belong to the array, but \(2\) does not. The MEX of \([0,3,1,2]\) is \(4\) because \(0\), \(1\), \(2\), and \(3\) belong to the array, but \(4\) does not.
Each test contains multiple test cases. The first line of input contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. The description of test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the number of nodes in the tree.The following \(n-1\) lines of each test case contains \(2\) integers \(a_i\) and \(b_i\) (\(1 \leq a_i, b_i \leq n, a_i \neq b_i\)) β€” indicating an edge between vertices \(a_i\) and \(b_i\). It is guaranteed that the given edges form a tree.It is guaranteed that the sum of \(n\) across all test cases does not exceed \(2 \cdot 10^5\).
For each test case, print the maximum possible value of any coloring of the tree.
In the first sample, we will color vertex \(2\) in \(1\) and vertices \(1,3\) in \(0\). After this, we consider all paths: \((1,1)\) with value \(1\) \((1,2)\) with value \(2\) \((1,3)\) with value \(2\) \((2,2)\) with value \(0\) \((2,3)\) with value \(2\) \((3,3)\) with value \(1\) We notice the sum of values is \(8\) which is the maximum possible.
Input: 431 22 341 21 31 4101 21 33 43 51 65 72 86 96 101 | Output: 8 15 96 1
Master
3
835
651
81
18
1,278
C
1278C
C. Berry Jam
1,700
data structures; dp; greedy; implementation
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were \(2n\) jars of strawberry and blueberry jam.All the \(2n\) jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly \(n\) jars to his left and \(n\) jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten \(1\) jar to his left and then \(5\) jars to his right. There remained exactly \(3\) full jars of both strawberry and blueberry jam. Jars are numbered from \(1\) to \(2n\) from left to right, so Karlsson initially stands between jars \(n\) and \(n+1\).What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer \(t\) independent test cases.
The first line contains one integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^5\)).The second line of each test case contains \(2n\) integers \(a_1, a_2, \dots, a_{2n}\) (\(1 \le a_i \le 2\)) β€” \(a_i=1\) means that the \(i\)-th jar from the left is a strawberry jam jar and \(a_i=2\) means that it is a blueberry jam jar.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case print the answer to it β€” the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
The picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all \(6\) jars so that there remain \(0\) jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave \(1\) jar of both jams.
Input: 4 6 1 1 1 2 2 1 2 1 2 1 1 2 2 1 2 1 2 3 1 1 1 1 1 1 2 2 1 1 1 | Output: 6 0 6 2
Medium
4
1,239
502
175
12
1,415
C
1415C
C. Bouncing Ball
1,400
brute force; dp; implementation
You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from \(1\), and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell \(p\), then bounces off it, then bounces off a platform in the cell \((p + k)\), then a platform in the cell \((p + 2k)\), and so on every \(k\)-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these \(p\) and \(k\).You already have some level pattern \(a_1\), \(a_2\), \(a_3\), ..., \(a_n\), where \(a_i = 0\) means there is no platform in the cell \(i\), and \(a_i = 1\) means there is one. You want to modify it so that the level can be passed with given \(p\) and \(k\). In \(x\) seconds you can add a platform in some empty cell. In \(y\) seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than \(p\). Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given \(p\) and \(k\)?
The first line contains the number of test cases \(t\) (\(1 \le t \le 100\)). Description of test cases follows.The first line of each test case contains three integers \(n\), \(p\), and \(k\) (\(1 \le p \le n \le 10^5\), \(1 \le k \le n\)) β€” the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required.The second line of each test case contains a string \(a_1 a_2 a_3 \ldots a_n\) (\(a_i = 0\) or \(a_i = 1\)) β€” the initial pattern written without spaces.The last line of each test case contains two integers \(x\) and \(y\) (\(1 \le x, y \le 10^4\)) β€” the time required to add a platform and to remove the first cell correspondingly.The sum of \(n\) over test cases does not exceed \(10^5\).
For each test case output a single integer β€” the minimum number of seconds you need to modify the level accordingly.It can be shown that it is always possible to make the level passable.
In the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is \(y = 2\).In the second test case it's best to add a platform to both cells \(4\) and \(5\): 00000 \(\to\) 00011. The time required is \(x \cdot 2 = 4\).In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially \(10\)-th: 10110011000 \(\to\) 10110011010. The time required is \(y \cdot 2 + x = 10\).
Input: 3 10 3 2 0101010101 2 2 5 4 1 00000 2 10 11 2 3 10110011000 4 3 | Output: 2 4 10
Easy
3
1,436
751
186
14
178
F2
178F2
F2. Representative Sampling
2,200
dp; sortings; strings
The Smart Beaver from ABBYY has a long history of cooperating with the ""Institute of Cytology and Genetics"". Recently, the Institute staff challenged the Beaver with a new problem. The problem is as follows.There is a collection of n proteins (not necessarily distinct). Each protein is a string consisting of lowercase Latin letters. The problem that the scientists offered to the Beaver is to select a subcollection of size k from the initial collection of proteins so that the representativity of the selected subset of proteins is maximum possible.The Smart Beaver from ABBYY did some research and came to the conclusion that the representativity of a collection of proteins can be evaluated by a single number, which is simply calculated. Let's suppose we have a collection {a1, ..., ak} consisting of k strings describing proteins. The representativity of this collection is the following value: where f(x, y) is the length of the longest common prefix of strings x and y; for example, f(""abc"", ""abd"") = 2, and f(""ab"", ""bcd"") = 0.Thus, the representativity of collection of proteins {""abc"", ""abd"", ""abe""} equals 6, and the representativity of collection {""aaa"", ""ba"", ""ba""} equals 2.Having discovered that, the Smart Beaver from ABBYY asked the Cup contestants to write a program that selects, from the given collection of proteins, a subcollection of size k which has the largest possible value of representativity. Help him to solve this problem!
The first input line contains two integers n and k (1 ≀ k ≀ n), separated by a single space. The following n lines contain the descriptions of proteins, one per line. Each protein is a non-empty string of no more than 500 characters consisting of only lowercase Latin letters (a...z). Some of the strings may be equal.The input limitations for getting 20 points are: 1 ≀ n ≀ 20 The input limitations for getting 50 points are: 1 ≀ n ≀ 100 The input limitations for getting 100 points are: 1 ≀ n ≀ 2000
Print a single number denoting the largest possible value of representativity that a subcollection of size k of the given collection of proteins can have.
Input: 3 2ababzdabq | Output: 2
Hard
3
1,476
501
154
1
1,174
A
1174A
A. Ehab Fails to Be Thanos
1,000
constructive algorithms; greedy; sortings
You're given an array \(a\) of length \(2n\). Is it possible to reorder it in such way so that the sum of the first \(n\) elements isn't equal to the sum of the last \(n\) elements?
The first line contains an integer \(n\) (\(1 \le n \le 1000\)), where \(2n\) is the number of elements in the array \(a\).The second line contains \(2n\) space-separated integers \(a_1\), \(a_2\), \(\ldots\), \(a_{2n}\) (\(1 \le a_i \le 10^6\)) β€” the elements of the array \(a\).
If there's no solution, print ""-1"" (without quotes). Otherwise, print a single line containing \(2n\) space-separated integers. They must form a reordering of \(a\). You are allowed to not change the order.
In the first example, the first \(n\) elements have sum \(2+1+3=6\) while the last \(n\) elements have sum \(1+1+2=4\). The sums aren't equal.In the second example, there's no solution.
Input: 3 1 2 2 1 3 1 | Output: 2 1 3 1 1 2
Beginner
3
181
280
208
11
1,430
C
1430C
C. Numbers on Whiteboard
1,000
constructive algorithms; data structures; greedy; implementation; math
Numbers \(1, 2, 3, \dots n\) (each integer from \(1\) to \(n\) once) are written on a board. In one operation you can erase any two numbers \(a\) and \(b\) from the board and write one integer \(\frac{a + b}{2}\) rounded up instead.You should perform the given operation \(n - 1\) times and make the resulting number that will be left on the board as small as possible. For example, if \(n = 4\), the following course of action is optimal: choose \(a = 4\) and \(b = 2\), so the new number is \(3\), and the whiteboard contains \([1, 3, 3]\); choose \(a = 3\) and \(b = 3\), so the new number is \(3\), and the whiteboard contains \([1, 3]\); choose \(a = 1\) and \(b = 3\), so the new number is \(2\), and the whiteboard contains \([2]\). It's easy to see that after \(n - 1\) operations, there will be left only one number. Your goal is to minimize it.
The first line contains one integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases.The only line of each test case contains one integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) β€” the number of integers written on the board initially.It's guaranteed that the total sum of \(n\) over test cases doesn't exceed \(2 \cdot 10^5\).
For each test case, in the first line, print the minimum possible number left on the board after \(n - 1\) operations. Each of the next \(n - 1\) lines should contain two integers β€” numbers \(a\) and \(b\) chosen and erased in each operation.
Input: 1 4 | Output: 2 2 4 3 3 3 1
Beginner
5
854
330
242
14
2,120
B
2120B
B. Square Pool
1,000
geometry
Aryan and Harshith are playing pool in universe AX120 on a fixed square pool table of side \(s\) with pockets at its \(4\) corners. The corners are situated at \((0,0)\), \((0,s)\), \((s,0)\), and \((s,s)\). In this game variation, \(n\) identical balls are placed on the table with integral coordinates such that no ball lies on the edge or corner of the table. Then, they are all simultaneously shot at \(10^{100}\) units/sec speed (only at \(45\) degrees with the axes).In universe AX120, balls and pockets are almost point-sized, and the collisions are elastic, i.e., the ball, on hitting any surface, bounces off at the same angle and with the same speed. Harshith shot the balls, and he provided Aryan with the balls' positions and the angles at which he shot them. Help Aryan determine the number of balls potted into the pockets by Harshith.It is guaranteed that multiple collisions do not occur at the same moment and position.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 1000\)). The description of the test cases follows. The first line of each test case contains two integers \(n\) and \(s\) (\(1 \le n \le 10^3\), \(2 \le s\le 10^9\)) β€” the number of balls placed on the table and the side length of the square pool table.The \(i\)-th of the next \(n\) lines contains four integers \(d_x\), \(d_y\), \(x_i\), and \(y_i\) (\(d_x,d_y \in \{-1, 1\}\), \(0 \lt x_i, y_i \lt s\)) β€” the direction vectors of the launch on the \(X\)-axis and \(Y\)-axis respectively, and the coordinates of the location where the \(i\)-th ball was placed. It is guaranteed that no two balls coincide at the initial moment.It is also guaranteed that the sum of \(n\) over all test cases does not exceed \(10^3\).
For each test case, print a single integer β€” the number of balls potted in that game.
In the first test case, there is a single ball and it's shot directly towards the pocket at \((2, 2)\), thus potted.In the second test case, the state progresses as \(\rightarrow\) \(\rightarrow\) \(\rightarrow\) \(\rightarrow\)
Input: 21 21 1 1 15 41 -1 1 11 -1 2 2-1 1 2 31 -1 1 3-1 1 3 1 | Output: 1 3
Beginner
1
936
829
85
21
662
B
662B
B. Graph Coloring
2,200
dfs and similar; graphs
You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red.Find the minimum possible number of moves required to make the colors of all edges equal.
The first line of the input contains two integers n and m (1 ≀ n, m ≀ 100 000) β€” the number of vertices and edges, respectively.The following m lines provide the description of the edges, as the i-th of them contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the indices of the vertices connected by the i-th edge, and a character ci () providing the initial color of this edge. If ci equals 'R', then this edge is initially colored red. Otherwise, ci is equal to 'B' and this edge is initially colored blue. It's guaranteed that there are no self-loops and multiple edges.
If there is no way to make the colors of all edges equal output - 1 in the only line of the output. Otherwise first output k β€” the minimum number of moves required to achieve the goal, then output k integers a1, a2, ..., ak, where ai is equal to the index of the vertex that should be used at the i-th move.If there are multiple optimal sequences of moves, output any of them.
Input: 3 31 2 B3 1 R3 2 B | Output: 12
Hard
2
467
582
376
6
1,436
C
1436C
C. Binary Search
1,500
binary search; combinatorics
Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number \(x\) in an array. For an array \(a\) indexed from zero, and an integer \(x\) the pseudocode of the algorithm is as follows: Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down).Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find \(x\)!Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size \(n\) such that the algorithm finds \(x\) in them. A permutation of size \(n\) is an array consisting of \(n\) distinct integers between \(1\) and \(n\) in arbitrary order.Help Andrey and find the number of permutations of size \(n\) which contain \(x\) at position \(pos\) and for which the given implementation of the binary search algorithm finds \(x\) (returns true). As the result may be extremely large, print the remainder of its division by \(10^9+7\).
The only line of input contains integers \(n\), \(x\) and \(pos\) (\(1 \le x \le n \le 1000\), \(0 \le pos \le n - 1\)) β€” the required length of the permutation, the number to search, and the required position of that number, respectively.
Print a single number β€” the remainder of the division of the number of valid permutations by \(10^9+7\).
All possible permutations in the first test case: \((2, 3, 1, 4)\), \((2, 4, 1, 3)\), \((3, 2, 1, 4)\), \((3, 4, 1, 2)\), \((4, 2, 1, 3)\), \((4, 3, 1, 2)\).
Input: 4 1 2 | Output: 6
Medium
2
1,239
239
104
14
300
B
300B
B. Coach
1,500
brute force; dfs and similar; graphs
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
The first line of the input contains integers n and m (3 ≀ n ≀ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≀ ai < bi ≀ n) β€” the pair ai, bi means that students with numbers ai and bi want to be on the same team.It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≀ xi, yi, zi ≀ n) β€” the i-th team. If there are multiple answers, you are allowed to print any of them.
Input: 3 0 | Output: 3 2 1
Medium
3
812
352
243
3
280
E
280E
E. Sequence Transformation
3,000
brute force; data structures; dp; implementation; math
You've got a non-decreasing sequence x1, x2, ..., xn (1 ≀ x1 ≀ x2 ≀ ... ≀ xn ≀ q). You've also got two integers a and b (a ≀ b; aΒ·(n - 1) < q).Your task is to transform sequence x1, x2, ..., xn into some sequence y1, y2, ..., yn (1 ≀ yi ≀ q; a ≀ yi + 1 - yi ≀ b). The transformation price is the following sum: . Your task is to choose such sequence y that minimizes the described transformation price.
The first line contains four integers n, q, a, b (2 ≀ n ≀ 6000; 1 ≀ q, a, b ≀ 109; aΒ·(n - 1) < q; a ≀ b).The second line contains a non-decreasing integer sequence x1, x2, ..., xn (1 ≀ x1 ≀ x2 ≀ ... ≀ xn ≀ q).
In the first line print n real numbers β€” the sought sequence y1, y2, ..., yn (1 ≀ yi ≀ q; a ≀ yi + 1 - yi ≀ b). In the second line print the minimum transformation price, that is, .If there are multiple optimal answers you can print any of them.The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Input: 3 6 2 21 4 6 | Output: 1.666667 3.666667 5.666667 0.666667
Master
5
402
209
339
2
1,934
A
1934A
A. Too Min Too Max
800
greedy; math
Given an array \(a\) of \(n\) elements, find the maximum value of the expression:$$$\(|a_i - a_j| + |a_j - a_k| + |a_k - a_l| + |a_l - a_i|\)\(where \)i\(, \)j\(, \)k\(, and \)l\( are four distinct indices of the array \)a\(, with \)1 \le i, j, k, l \le n\(.Here \)|x|\( denotes the absolute value of \)x$$$.
The first line contains one integer \(t\) (\(1 \le t \le 500\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(4 \le n \le 100\)) β€” the length of the given array.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(-10^6 \le a_i \le 10^6\)).
For each test case, print a single integer β€” the maximum value.
In the first test case, for any selection of \(i\), \(j\), \(k\), \(l\), the answer will be \(0\). For example, \(|a_1 - a_2| + |a_2 - a_3| + |a_3 - a_4| + |a_4 - a_1| = |1 - 1| + |1 - 1| + |1 - 1| + |1 - 1| = 0 + 0 + 0 + 0 = 0\).In the second test case, for \(i = 1\), \(j = 3\), \(k = 2\), and \(l = 5\), the answer will be \(6\). \(|a_1 - a_3| + |a_3 - a_2| + |a_2 - a_5| + |a_5 - a_1| = |1 - 2| + |2 - 1| + |1 - 3| + |3 - 1| = 1 + 1 + 2 + 2 = 6\).
Input: 541 1 1 151 1 2 2 385 1 3 2 -3 -1 10 343 3 1 141 2 2 -1 | Output: 0 6 38 8 8
Beginner
2
308
366
63
19
886
A
886A
A. ACM ICPC
1,000
brute force
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams.After practice competition, participant number i got a score of ai. Team score is defined as sum of scores of its participants. High school management is interested if it's possible to build two teams with equal scores. Your task is to answer that question.
The single line contains six integers a1, ..., a6 (0 ≀ ai ≀ 1000) β€” scores of the participants
Print ""YES"" (quotes for clarity), if it is possible to build teams with equal score, and ""NO"" otherwise.You can print each character either upper- or lowercase (""YeS"" and ""yes"" are valid when the answer is ""YES"").
In the first sample, first team can be composed of 1st, 2nd and 6th participant, second β€” of 3rd, 4th and 5th: team scores are 1 + 3 + 1 = 2 + 1 + 2 = 5.In the second sample, score of participant number 6 is too high: his team score will be definitely greater.
Input: 1 3 2 1 2 1 | Output: YES
Beginner
1
501
94
223
8
1,477
A
1477A
A. Nezzar and Board
1,800
constructive algorithms; math; number theory
\(n\) distinct integers \(x_1,x_2,\ldots,x_n\) are written on the board. Nezzar can perform the following operation multiple times. Select two integers \(x,y\) (not necessarily distinct) on the board, and write down \(2x-y\). Note that you don't remove selected numbers. Now, Nezzar wonders if it is possible to have his favorite number \(k\) on the board after applying above operation multiple times.
The first line contains a single integer \(t\) (\(1 \le t \le 10^5\)) β€” the number of test cases. The first line of each test case contains two integers \(n,k\) (\(2 \le n \le 2 \cdot 10^5\), \(-10^{18} \le k \le 10^{18}\)).The second line of each test case contains \(n\) distinct integers \(x_1,x_2,\ldots,x_n\) (\(-10^{18} \le x_i \le 10^{18}\)).It is guaranteed that the sum of \(n\) for all test cases does not exceed \(2 \cdot 10^5\).
For each test case, print ""YES"" on a single line if it is possible to have \(k\) on the board. Otherwise, print ""NO"".You can print each letter in any case (upper or lower).
In the first test case, the number \(1\) is already on the board.In the second test case, Nezzar could perform the following operations to write down \(k=0\) on the board: Select \(x=3\) and \(y=2\) and write down \(4\) on the board. Select \(x=4\) and \(y=7\) and write down \(1\) on the board. Select \(x=1\) and \(y=2\) and write down \(0\) on the board. In the third test case, it is impossible to have the number \(k = -1\) on the board.
Input: 6 2 1 1 2 3 0 2 3 7 2 -1 31415926 27182818 2 1000000000000000000 1 1000000000000000000 2 -1000000000000000000 -1000000000000000000 123 6 80 -5 -20 13 -14 -2 -11 | Output: YES YES NO YES YES NO
Medium
3
402
440
176
14
1,505
B
1505B
B. DMCA
1,600
*special; implementation; number theory
Many people are aware of DMCA – Digital Millennium Copyright Act. But another recently proposed DMCA – Digital Millennium Calculation Act – is much less known.In this problem you need to find a root of a number according to this new DMCA law.
The input contains a single integer \(a\) (\(1 \le a \le 1000000\)).
Output the result – an integer number.
Input: 1 | Output: 1
Medium
3
242
68
38
15
2,075
B
2075B
B. Array Recoloring
1,300
constructive algorithms; greedy
You are given an integer array \(a\) of size \(n\). Initially, all elements of the array are colored red.You have to choose exactly \(k\) elements of the array and paint them blue. Then, while there is at least one red element, you have to select any red element with a blue neighbor and make it blue.The cost of painting the array is defined as the sum of the first \(k\) chosen elements and the last painted element. Your task is to calculate the maximum possible cost of painting for the given array.
The first line contains a single integer \(t\) (\(1 \le t \le 10^3\)) β€” the number of test cases.The first line of each test case contains two integers \(n\) and \(k\) (\(2 \le n \le 5000\); \(1 \le k < n\)).The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\)).Additional constraint on the input: the sum of \(n\) over all test cases doesn't exceed \(5000\).
For each test case, print a single integer β€” the maximum possible cost of painting for the given array.
In the first example, you can initially color the \(2\)-nd element, and then color the elements in the order \(1, 3\). Then the cost of painting is equal to \(2+3=5\).In the second example, you can initially color the elements \(1\) and \(5\), and then color the elements in the order \(2, 4, 3\). Then the cost of painting is equal to \(4+3+3=10\).In the third example, you can initially color the elements \(2, 3, 4\), and then color the \(1\)-st element. Then the cost of painting is equal to \(2+2+2+2=8\).
Input: 33 11 2 35 24 2 3 1 34 32 2 2 2 | Output: 5 10 8
Easy
2
503
395
103
20
859
B
859B
B. Lazy Security Guard
1,000
brute force; geometry; math
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.
Input will consist of a single integer N (1 ≀ N ≀ 106), the number of city blocks that must be enclosed by the route.
Print the minimum perimeter that can be achieved.
Here are some possible shapes for the examples:
Input: 4 | Output: 8
Beginner
3
541
117
49
8
952
G
952G
G. Puzzling Language
2,200
*special; *special; *special; constructive algorithms
In this problem you will write a simple code generator for a 2D programming language derived from Brainfuck.The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table: You are given a string. Output a program in the described language which prints this string.You can download the language interpreter used for judging here: https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp (use C++11 to compile the code). Note several implementation details: The first step of the language interpretation is conversion to a Brainfuck program, which is then executed. The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters. The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line. Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256. Console input (, command) is allowed in Brainfuck code but has no effect when executed.
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output a program in the described language which, when executed, will print the given message.
The example corresponds to the following Brainfuck program: - >+< >+++< >+++++< >+++++++< >+++++++++< >+++++++++++<< >...The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Input: $$$ | Output: .......X.............XXX...........XXXXX.........XXXXXXX.......XXXXXXXXX.....XXXXXXXXXXX...XXXXXXXXXXXXX................X.............XX..............X..............X..............
Hard
4
1,391
179
94
9
1,504
A
1504A
A. DΓ©jΓ  Vu
800
constructive algorithms; strings
A palindrome is a string that reads the same backward as forward. For example, the strings ""z"", ""aaa"", ""aba"", and ""abccba"" are palindromes, but ""codeforces"" and ""ab"" are not. You hate palindromes because they give you dΓ©jΓ  vu.There is a string \(s\). You must insert exactly one character 'a' somewhere in \(s\). If it is possible to create a string that is not a palindrome, you should find one example. Otherwise, you should report that it is impossible.For example, suppose \(s=\) ""cbabc"". By inserting an 'a', you can create ""acbabc"", ""cababc"", ""cbaabc"", ""cbabac"", or ""cbabca"". However ""cbaabc"" is a palindrome, so you must output one of the other options.
The first line contains a single integer \(t\) (\(1\le t\le 10^4\)) β€” the number of test cases.The only line of each test case contains a string \(s\) consisting of lowercase English letters.The total length of all strings does not exceed \(3\cdot 10^5\).
For each test case, if there is no solution, output ""NO"".Otherwise, output ""YES"" followed by your constructed string of length \(|s|+1\) on the next line. If there are multiple solutions, you may print any.You can print each letter of ""YES"" and ""NO"" in any case (upper or lower).
The first test case is described in the statement.In the second test case, we can make either ""aab"" or ""aba"". But ""aba"" is a palindrome, so ""aab"" is the only correct answer.In the third test case, ""zaza"" and ""zzaa"" are correct answers, but not ""azza"".In the fourth test case, ""baa"" is the only correct answer.In the fifth test case, we can only make ""aa"", which is a palindrome. So the answer is ""NO"".In the sixth test case, ""anutforajaroftuna"" is a palindrome, but inserting 'a' elsewhere is valid.
Input: 6 cbabc ab zza ba a nutforajaroftuna | Output: YES cbabac YES aab YES zaza YES baa NO YES nutforajarofatuna
Beginner
2
686
255
287
15
1,658
B
1658B
B. Marin and Anti-coprime Permutation
800
combinatorics; math; number theory
Marin wants you to count number of permutations that are beautiful. A beautiful permutation of length \(n\) is a permutation that has the following property: $$$\( \gcd (1 \cdot p_1, \, 2 \cdot p_2, \, \dots, \, n \cdot p_n) > 1, \)\( where \)\gcd\( is the greatest common divisor.A permutation is an array consisting of \)n\( distinct integers from \)1\( to \)n\( in arbitrary order. For example, \)[2,3,1,5,4]\( is a permutation, but \)[1,2,2]\( is not a permutation (\)2\( appears twice in the array) and \)[1,3, 4]\( is also not a permutation (\)n=3\( but there is \)4$$$ in the array).
The first line contains one integer \(t\) (\(1 \le t \le 10^3\)) β€” the number of test cases.Each test case consists of one line containing one integer \(n\) (\(1 \le n \le 10^3\)).
For each test case, print one integer β€” number of beautiful permutations. Because the answer can be very big, please print the answer modulo \(998\,244\,353\).
In first test case, we only have one permutation which is \([1]\) but it is not beautiful because \(\gcd(1 \cdot 1) = 1\).In second test case, we only have one beautiful permutation which is \([2, 1]\) because \(\gcd(1 \cdot 2, 2 \cdot 1) = 2\).
Input: 71234561000 | Output: 0 1 0 4 0 36 665702330
Beginner
3
590
180
159
16
1,002
B2
1002B2
B2. Distinguish GHZ state and W state
1,600
*special
You are given N qubits (2 ≀ N ≀ 8) which are guaranteed to be in one of the two states: state, or state. Your task is to perform necessary operations and measurements to figure out which state it was and to return 0 if it was GHZ state or 1 if it was W state. The state of the qubits after the operations does not matter.You have to implement an operation which takes an array of N qubits as an input and returns an integer. Your code should have the following signature:namespace Solution { open Microsoft.Quantum.Primitive; open Microsoft.Quantum.Canon; operation Solve (qs : Qubit[]) : Int { body { // your code here } }}
Medium
1
624
0
0
10
282
E
282E
E. Sausage Maximization
2,200
bitmasks; data structures; trees
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
The first line contains an integer n (1 ≀ n ≀ 105).The next line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 1012) β€” Mr. Bitkoch's sausage.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Print a single integer β€” the maximum pleasure BitHaval and BitAryo can get from the dinner.
Input: 21 2 | Output: 3
Hard
3
1,256
288
91
2
1,425
A
1425A
A. Arena of Greed
1,400
games; greedy
Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing \(N\) gold coins. The game ends if there are no more gold coins in the chest. In each turn, the players can make one of the following moves: Take one gold coin from the chest. Take half of the gold coins on the chest. This move is only available if the number of coins in the chest is even. Both players will try to maximize the number of coins they have. Mr. Chanek asks your help to find the maximum number of coins he can get at the end of the game if both he and the opponent plays optimally.
The first line contains a single integer \(T\) \((1 \le T \le 10^5)\) denotes the number of test cases.The next \(T\) lines each contain a single integer \(N\) \((1 \le N \le 10^{18})\).
\(T\) lines, each line is the answer requested by Mr. Chanek.
For the first case, the game is as follows: Mr. Chanek takes one coin. The opponent takes two coins. Mr. Chanek takes one coin. The opponent takes one coin. For the second case, the game is as follows: Mr. Chanek takes three coins. The opponent takes one coin. Mr. Chanek takes one coin. The opponent takes one coin.
Input: 2 5 6 | Output: 2 4
Easy
2
813
186
61
14
877
A
877A
A. Alex and broken contest
1,100
implementation; strings
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems.But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest by its name.It is known, that problem is from this contest if and only if its name contains one of Alex's friends' name exactly once. His friends' names are ""Danil"", ""Olya"", ""Slava"", ""Ann"" and ""Nikita"".Names are case sensitive.
The only line contains string from lowercase and uppercase letters and ""_"" symbols of length, not more than 100 β€” the name of the problem.
Print ""YES"", if problem is from this contest, and ""NO"" otherwise.
Input: Alex_and_broken_contest | Output: NO
Easy
2
555
140
69
8
367
A
367A
A. Sereja and Algorithm
1,500
data structures; implementation
Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string ""zyx"", ""xzy"", ""yxz"". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≀ li ≀ ri ≀ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not.
The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'.The second line contains integer m (1 ≀ m ≀ 105) β€” the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≀ li ≀ ri ≀ n).
For each test, print ""YES"" (without the quotes) if the algorithm works correctly on the corresponding test and ""NO"" (without the quotes) otherwise.
In the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string ""xzyx"" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly.
Input: zyxxxxxxyyz55 51 31 111 43 6 | Output: YESYESNOYESNO
Medium
2
1,227
321
151
3
492
E
492E
E. Vanya and Field
2,000
math
Vanya decided to walk in the field of size n Γ— n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
In the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Input: 5 5 2 30 01 21 32 43 1 | Output: 1 3
Hard
1
570
304
169
4
1,252
I
1252I
I. Mission Possible
3,000
Allen, a government secret service, has been assigned to infiltrate a mafia secret base to uncover crucial information regarding the mafia's operations.The secret base is a rectangular bounded by \((x_L,y_L)\), \((x_L,y_R)\), \((x_R,y_L)\), and \((x_R,y_R)\) in a Cartesian coordinate system where \(x_L < x_R\) and \(y_L < y_R\). There are \(N\) sensors placed inside the secret base. The \(i^{th}\) sensor is located at \((x_i, y_i)\) and has an effective sensing radius of \(r_i\) which can detect any person who is strictly within the radius of \(r_i\) from \((x_i, y_i)\). In other words, the \(i^{th}\) sensor can detect a person at location \((x_a, y_a)\) if and only if the Euclidean distance of \((x_i, y_i)\) and \((x_a, y_a)\) is strictly less than \(r_i\). It is also known that the Euclidean distance of any two sensors \(i\) and \(j\) is strictly larger than \(r_i + r_j\). Note that the Euclidean distance of two points, \((x_a, y_a)\) and \((x_b, y_b)\), is \(\sqrt{|x_a - x_b|^2 + |y_a - y_b|^2}\).Allen begins his infiltration mission at location \((x_s, y_s)\), and his target is located at \((x_t, y_t)\). Allen has the power to run extremely fast in a straight line while he needs to spend extra time to change his running trajectory (to adjust his footing). Although he is a fast runner, he still needs to make sure that none of the sensors detect him while he is running, i.e. there is no point in his running trajectory which is strictly within a sensor effective sensing radius.Let \(P = \{(x_{p_1}, y_{p_1}), \dots, (x_{p_{|P|}}, y_{p_{|P|}})\}\) be the set of locations where Allen changes his running trajectory, thus, Allen's running trajectory with \(P\) is \((x_s, y_s) \rightarrow (x_{p_1}, y_{p_1}) \rightarrow \dots \rightarrow (x_{p_{|P|}}, y_{p_{|P|}}) \rightarrow (x_t, y_t)\) where \((x_a,y_a) \rightarrow (x_b,y_b)\) implies that Allen is running from \((x_a,y_a)\) to \((x_b,y_b)\) in a straight line. The set \(P\) is feasible if and only if with \(P\), Allen is not detected by any sensor and is not running out of the secret base (although, Allen is allowed to run along the secret base perimeter). Note that \(x_p\) and \(y_p\), \((x_p,y_p) \in P\), are not necessarily integers; they can be real numbers.Your task in this problem is to find any one feasible \(P\) which contains no more than \(1000\) points.
Input begins with a line containing five integers: \(N\) \(x_L\) \(y_L\) \(x_R\) \(y_R\) (\(0 \le N \le 50\); \(0 \le x_L < x_R \le 1000\); \(0 \le y_L < y_R \le 1000\)) representing the number of sensors and the secret base (\(x_L\), \(y_L\), \(x_R\), \(y_R\)), respectively. The next line contains two integers: \(x_s\) \(y_s\) (\(x_L < x_s < x_R\); \(y_L < y_s < y_R\)) representing Allen's initial location. The next line contains two integers: \(x_t\) \(y_t\) (\(x_L < x_t < x_R\); \(y_L < y_t < y_R\)) representing Allen's target location. It is guaranteed that \(x_s \ne x_t\) or \(y_s \ne y_t\). The next \(N\) lines each contains three integers: \(x_i\) \(y_i\) \(r_i\) (\(x_L < x_i - r_i < x_i + r_i < x_R\); \(y_L < y_i - r_i < y_i + r_i < y_R\); \(1 \le r_i \le 1000\)) representing a sensor at location \((x_i, y_i)\) with an effective sensing radius of \(r_i\). It is guaranteed that the Euclidean distance of any two sensors \(i\) and \(j\) is larger than \(r_i + r_j\). It is also guaranteed that the Euclidean distance of \((x_s,y_s)\) and \((x_t,y_t)\) to any sensor \(i\) is larger than \(r_i\).
Output in a line an integer representing the size of a feasible \(P\). The next \(|P|\) lines each contains two real numbers (separated by a single space); the \(j^{th}\) line contains \(x_j\) \(y_j\) representing the \(j^{th}\) point in \(P\). You may output any feasible \(P\) with no more than \(1000\) points.Due to the nature of the output (floating point), let us define an epsilon \(\epsilon\) to be \(10^{-6}\) to verify the output. Consider \(Q_1 = (x_s, y_s)\), \(Q_{j+1} = P_j\) for all \(1 \le j \le |P|\), and \(Q_{|P|+2} = (x_t, y_t)\). Then, \(P\) is considered correct if and only if \(P\) contains no more than \(1000\) points and all of the following are satisfied: \(x_L - \epsilon \le x_{p_k} \le x_R + \epsilon\) and \(y_L - \epsilon \le y_{p_k} \le y_R + \epsilon\) for all \(1 \le k \le |P|\) (Allen is not running out of the secret base). For all \(1 \le k < |Q|\), let \(S_k\) be the line segment connecting \(Q_k\) and \(Q_{k+1}\) (Allen is running in straight line). For all \(1 \le i \le N\), let \((x_{k,i},y_{k,i})\) be the point along \(S_k\) that is the closest to the \(i^{th}\) sensor's location, \((x_i,y_i)\). Let \(d_{k,i}\) be the Euclidean distance between \((x_{k,i},y_{k,i})\) and \((x_i,y_i)\). Then, the constraint \(r_i \le d_{k,i} + \epsilon\) should be satisfied (Allen is not detected by any sensor). All points in \(Q\) are distinct. Two points, \((x_a,y_a)\) and \((x_b,y_b)\), are considered distinct if and only if \(|x_a - x_b| > \epsilon\) or \(|y_a - y_b| > \epsilon\).
Explanation for the sample input/output #1The figure above shows the \(P\) from the sample output. Note that there exists a feasible \(P\) with only one point in this sample, although you are not required to find such \(P\).
Input: 3 2 2 50 26 4 14 48 14 15 13 7 36 16 6 46 18 3 | Output: 2 13.25 23.1234567 36.591003 7.1
Master
0
2,353
1,114
1,523
12
2,045
H
2045H
H. Missing Separators
2,200
dp; sortings; string suffix structures; strings
You have a dictionary, which is a list of distinct words sorted in alphabetical order. Each word consists of uppercase English letters.You want to print this dictionary. However, there is a bug with the printing system, and all words in the list are printed next to each other without any separators between words. Now, you ended up with a string \(S\) that is a concatenation of all the words in the dictionary in the listed order.Your task is to reconstruct the dictionary by splitting \(S\) into one or more words. Note that the reconstructed dictionary must consist of distinct words sorted in alphabetical order. Furthermore, you want to maximize the number of words in the dictionary. If there are several possible dictionaries with the maximum number of words, you can choose any of them.
A single line consisting of a string \(S\) (\(1 \leq |S| \leq 5000)\). String \(S\) consists of only uppercase English letters.
First, output an integer in a single line representing the maximum number of the words in the reconstructed dictionary. Denote this number as \(n\).Then, output \(n\) lines, each containing a single string representing the word. The words must be distinct, and the list must be sorted alphabetically. The concatenation of the words in the listed order must equal \(S\).If there are several possible dictionaries with the maximum number of words, output any of them.
Input: ABACUS | Output: 4 A BA C US
Hard
4
795
127
465
20
2,041
A
2041A
A. The Bento Box Adventure
1,300
implementation; sortings
Image generated by ChatGPT 4o. Boxed meals in Taiwan are very common, offering convenient and affordable nutrition-balanced choices for students and office workers. These meals typically include a variety of vegetables, protein, and rice, providing a well-rounded diet. With numerous options available at local self-service restaurants, they are a popular choice for those looking for a quick, healthy lunch.There are five Taiwanese self-service restaurants numbered from 1 to 5. You plan to visit a different restaurant each day from Monday to Friday to pack a boxed meal for lunch. You've already visited one restaurant from Monday to Thursday, each time visiting a different one. Now, it's Friday, and you want to visit the last remaining restaurant that you haven't been to yet this week.Write a program that takes as input the four restaurants you've already visited (one for each day from Monday to Thursday) and outputs the restaurant you should visit on Friday.
A single line of input containing four integers \(a, b, c, d\), each between 1 and 5 (inclusive), representing the restaurant numbers you visited from Monday to Thursday, in order. \(1\le a, b, c, d\le 5\) All four numbers will be different.
Output the restaurant number you should visit on Friday.
Input: 1 3 2 5 | Output: 4
Easy
2
969
241
56
20
587
A
587A
A. Duff and Weight Lifting
1,500
greedy
Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps. Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2a1, ..., 2ak if and only if there exists a non-negative integer x such that 2a1 + 2a2 + ... + 2ak = 2x, i. e. the sum of those numbers is a power of two.Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps.
The first line of input contains integer n (1 ≀ n ≀ 106), the number of weights.The second line contains n integers w1, ..., wn separated by spaces (0 ≀ wi ≀ 106 for each 1 ≀ i ≀ n), the powers of two forming the weights values.
Print the minimum number of steps in a single line.
In the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two.In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two.
Input: 51 1 2 3 3 | Output: 2
Medium
1
752
228
51
5
1,016
F
1016F
F. Road Projects
2,600
dfs and similar; dp; trees
There are \(n\) cities in the country of Berland. Some of them are connected by bidirectional roads in such a way that there exists exactly one path, which visits each road no more than once, between every pair of cities. Each road has its own length. Cities are numbered from \(1\) to \(n\).The travelling time between some cities \(v\) and \(u\) is the total length of the roads on the shortest path from \(v\) to \(u\). The two most important cities in Berland are cities \(1\) and \(n\).The Berland Ministry of Transport decided to build a single new road to decrease the traffic between the most important cities. However, lots of people are used to the current travelling time between the most important cities, so the new road shouldn't change it too much. The new road can only be built between such cities \(v\) and \(u\) that \(v \neq u\) and \(v\) and \(u\) aren't already connected by some road.They came up with \(m\) possible projects. Each project is just the length \(x\) of the new road.Polycarp works as a head analyst at the Berland Ministry of Transport and it's his job to deal with all those \(m\) projects. For the \(i\)-th project he is required to choose some cities \(v\) and \(u\) to build the new road of length \(x_i\) between such that the travelling time between the most important cities is maximal possible. Unfortunately, Polycarp is not a programmer and no analyst in the world is capable to process all projects using only pen and paper. Thus, he asks you to help him to calculate the maximal possible travelling time between the most important cities for each project. Note that the choice of \(v\) and \(u\) can differ for different projects.
The first line contains two integers \(n\) and \(m\) (\(3 \le n \le 3 \cdot 10^5\), \(1 \le m \le 3 \cdot 10^5\)) β€” the number of cities and the number of projects, respectively.Each of the next \(n - 1\) lines contains three integers \(v_i\), \(u_i\) and \(w_i\) (\(1 \le v_i, u_i \le n\), \(1 \le w_i \le 10^9\)) β€” the description of the \(i\)-th road. It is guaranteed that there exists exactly one path, which visits each road no more than once, between every pair of cities.Each of the next \(m\) lines contains a single integer \(x_j\) (\(1 \le x_j \le 10^9\)) β€” the length of the road for the \(j\)-th project.
Print \(m\) lines, the \(j\)-th line should contain a single integer β€” the maximal possible travelling time between the most important cities for the \(j\)-th project.
The road network from the first example:You can build the road with length \(1\) between cities \(5\) and \(6\) to get \(83\) as the travelling time between \(1\) and \(7\) (\(1 \rightarrow 2 \rightarrow 6 \rightarrow 5 \rightarrow 3 \rightarrow 4 \rightarrow 7\) \(=\) \(18 + 4 + 1 + 12 + 24 + 24 = 83\)). Other possible pairs of cities will give answers less or equal to \(83\).
Input: 7 21 2 182 3 223 4 244 7 242 6 43 5 121100 | Output: 8388
Expert
3
1,680
617
167
10
2,121
A
2121A
A. Letter Home
800
brute force; math
You are given an array of distinct integers \(x_1, x_2, \ldots, x_n\) and an integer \(s\). Initially, you are at position \(pos = s\) on the \(X\) axis. In one step, you can perform exactly one of the following two actions: Move from position \(pos\) to position \(pos + 1\). Move from position \(pos\) to position \(pos - 1\). A sequence of steps will be considered successful if, during the entire journey, you visit each position \(x_i\) on the \(X\) axis at least once. Note that the initial position \(pos = s\) is also considered visited. Your task is to determine the minimum number of steps in any successful sequence of steps.
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 1000\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains two integers \(n\) and \(s\) (\(1 \leq n \leq 10\), \(1 \leq s \leq 100\)) β€” the number of positions to visit and the starting position. The second line of each test case contains \(n\) integers \(x_1, x_2, \ldots, x_n\) (\(1 \leq x_i \leq 100\)). It is guaranteed that for all \(1 \leq i < n\), it holds that \(x_i < x_{i + 1}\).
For each test case, output the minimum number of steps in any successful sequence of steps.
In the first test case, no steps need to be taken, so the only visited position will be \(1\). In the second test case, the following path can be taken: \(2 \rightarrow 1\). The number of steps is \(1\). In the third test case, the following path can be taken: \(1 \rightarrow 2\). The number of steps is \(1\).In the fifth test case, the following path can be taken: \(2 \rightarrow 1 \rightarrow 2 \rightarrow 3\). The number of steps is \(3\).
Input: 121 111 211 122 12 32 21 32 31 23 11 2 33 21 3 43 31 2 34 31 2 3 105 51 2 3 6 76 61 2 3 9 10 11 | Output: 0 1 1 2 3 2 2 4 2 11 8 15
Beginner
2
636
557
91
21
1,036
E
1036E
E. Covered Points
2,400
fft; geometry; number theory
You are given \(n\) segments on a Cartesian plane. Each segment's endpoints have integer coordinates. Segments can intersect with each other. No two segments lie on the same line.Count the number of distinct points with integer coordinates, which are covered by at least one segment.
The first line contains a single integer \(n\) (\(1 \le n \le 1000\)) β€” the number of segments.Each of the next \(n\) lines contains four integers \(Ax_i, Ay_i, Bx_i, By_i\) (\(-10^6 \le Ax_i, Ay_i, Bx_i, By_i \le 10^6\)) β€” the coordinates of the endpoints \(A\), \(B\) (\(A \ne B\)) of the \(i\)-th segment.It is guaranteed that no two segments lie on the same line.
Print a single integer β€” the number of distinct points with integer coordinates, which are covered by at least one segment.
The image for the first example: Several key points are marked blue, the answer contains some non-marked points as well.The image for the second example:
Input: 90 0 4 4-1 5 4 04 0 4 45 2 11 26 1 6 75 6 11 610 1 10 77 0 9 810 -1 11 -1 | Output: 42
Expert
3
283
367
123
10
245
H
245H
H. Queries for Number of Palindromes
1,800
dp; hashing; strings
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≀ li ≀ ri ≀ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≀ l ≀ r ≀ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.
The first line contains string s (1 ≀ |s| ≀ 5000). The second line contains a single integer q (1 ≀ q ≀ 106) β€” the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≀ li ≀ ri ≀ |s|) β€” the description of the i-th query.It is guaranteed that the given string consists only of lowercase English letters.
Print q integers β€” the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.
Consider the fourth query in the first test case. String s[4... 6] = Β«abaΒ». Its palindrome substrings are: Β«aΒ», Β«bΒ», Β«aΒ», Β«abaΒ».
Input: caaaba51 11 42 34 64 5 | Output: 17342
Medium
3
526
375
168
2
1,682
B
1682B
B. AND Sorting
1,100
bitmasks; constructive algorithms; sortings
You are given a permutation \(p\) of integers from \(0\) to \(n-1\) (each of them occurs exactly once). Initially, the permutation is not sorted (that is, \(p_i>p_{i+1}\) for at least one \(1 \le i \le n - 1\)). The permutation is called \(X\)-sortable for some non-negative integer \(X\) if it is possible to sort the permutation by performing the operation below some finite number of times: Choose two indices \(i\) and \(j\) \((1 \le i \lt j \le n)\) such that \(p_i \& p_j = X\). Swap \(p_i\) and \(p_j\). Here \(\&\) denotes the bitwise AND operation.Find the maximum value of \(X\) such that \(p\) is \(X\)-sortable. It can be shown that there always exists some value of \(X\) such that \(p\) is \(X\)-sortable.
The input consists of multiple test cases. The first line contains a single integer \(t\) \((1 \le t \le 10^4)\) β€” the number of test cases. Description of test cases follows.The first line of each test case contains a single integer \(n\) \((2 \le n \le 2 \cdot 10^5)\) β€” the length of the permutation.The second line of each test case contains \(n\) integers \(p_1, p_2, ..., p_n\) (\(0 \le p_i \le n-1\), all \(p_i\) are distinct) β€” the elements of \(p\). It is guaranteed that \(p\) is not sorted.It is guaranteed that the sum of \(n\) over all cases does not exceed \(2 \cdot 10^5\).
For each test case output a single integer β€” the maximum value of \(X\) such that \(p\) is \(X\)-sortable.
In the first test case, the only \(X\) for which the permutation is \(X\)-sortable are \(X = 0\) and \(X = 2\), maximum of which is \(2\).Sorting using \(X = 0\): Swap \(p_1\) and \(p_4\), \(p = [2, 1, 3, 0]\). Swap \(p_3\) and \(p_4\), \(p = [2, 1, 0, 3]\). Swap \(p_1\) and \(p_3\), \(p = [0, 1, 2, 3]\). Sorting using \(X = 2\): Swap \(p_3\) and \(p_4\), \(p = [0, 1, 2, 3]\). In the second test case, we must swap \(p_1\) and \(p_2\) which is possible only with \(X = 0\).
Input: 440 1 3 221 070 1 2 3 5 6 450 3 2 1 4 | Output: 2 0 4 1
Easy
3
719
588
106
16
194
A
194A
A. Exams
900
implementation; math
One day the Codeforces round author sat exams. He had n exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2. The author would need to spend too much time and effort to make the sum of his marks strictly more than k. That could have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than k, the author's mum won't be pleased at all. The Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams. Help the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all n exams equal exactly k.
The single input line contains space-separated integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 250) β€” the number of exams and the required sum of marks.It is guaranteed that there exists a way to pass n exams in the way that makes the sum of marks equal exactly k.
Print the single number β€” the minimum number of exams that the author will get a 2 for, considering that the sum of marks for all exams must equal k.
In the first sample the author has to get a 2 for all his exams.In the second sample he should get a 3 for two exams and a 2 for two more.In the third sample he should get a 3 for one exam.
Input: 4 8 | Output: 4
Beginner
2
774
254
149
1
209
C
209C
C. Trails and Glades
2,400
constructive algorithms; dsu; graphs; greedy
Vasya went for a walk in the park. The park has n glades, numbered from 1 to n. There are m trails between the glades. The trails are numbered from 1 to m, where the i-th trail connects glades xi and yi. The numbers of the connected glades may be the same (xi = yi), which means that a trail connects a glade to itself. Also, two glades may have several non-intersecting trails between them.Vasya is on glade 1, he wants to walk on all trails of the park exactly once, so that he can eventually return to glade 1. Unfortunately, Vasya does not know whether this walk is possible or not. Help Vasya, determine whether the walk is possible or not. If such walk is impossible, find the minimum number of trails the authorities need to add to the park in order to make the described walk possible.Vasya can shift from one trail to another one only on glades. He can move on the trails in both directions. If Vasya started going on the trail that connects glades a and b, from glade a, then he must finish this trail on glade b.
The first line contains two integers n and m (1 ≀ n ≀ 106; 0 ≀ m ≀ 106) β€” the number of glades in the park and the number of trails in the park, respectively. Next m lines specify the trails. The i-th line specifies the i-th trail as two space-separated numbers, xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of the glades connected by this trail.
Print the single integer β€” the answer to the problem. If Vasya's walk is possible without adding extra trails, print 0, otherwise print the minimum number of trails the authorities need to add to the park in order to make Vasya's walk possible.
In the first test case the described walk is possible without building extra trails. For example, let's first go on the first trail, then on the second one, and finally on the third one.In the second test case the described walk is impossible without adding extra trails. To make the walk possible, it is enough to add one trail, for example, between glades number one and two.
Input: 3 31 22 33 1 | Output: 0
Expert
4
1,023
339
244
2
883
J
883J
J. Renovation
2,400
constructive algorithms; greedy; sortings
The mayor of the Berland city S sees the beauty differently than other city-dwellers. In particular, he does not understand at all, how antique houses can be nice-looking. So the mayor wants to demolish all ancient buildings in the city.The city S is going to host the football championship very soon. In order to make the city beautiful, every month the Berland government provides mayor a money tranche. The money has to be spent on ancient buildings renovation.There are n months before the championship and the i-th month tranche equals to ai burles. The city S has m antique buildings and the renovation cost of the j-th building is bj burles.The mayor has his own plans for spending the money. As he doesn't like antique buildings he wants to demolish as much of them as possible. For the j-th building he calculated its demolishing cost pj.The mayor decided to act according to the following plan.Each month he chooses several (possibly zero) of m buildings to demolish in such a way that renovation cost of each of them separately is not greater than the money tranche ai of this month (bj ≀ ai) β€” it will allow to deceive city-dwellers that exactly this building will be renovated.Then the mayor has to demolish all selected buildings during the current month as otherwise the dwellers will realize the deception and the plan will fail. Definitely the total demolishing cost can not exceed amount of money the mayor currently has. The mayor is not obliged to spend all the money on demolishing. If some money is left, the mayor puts it to the bank account and can use it in any subsequent month. Moreover, at any month he may choose not to demolish any buildings at all (in this case all the tranche will remain untouched and will be saved in the bank).Your task is to calculate the maximal number of buildings the mayor can demolish.
The first line of the input contains two integers n and m (1 ≀ n, m ≀ 100 000) β€” the number of months before the championship and the number of ancient buildings in the city S.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109), where ai is the tranche of the i-th month.The third line contains m integers b1, b2, ..., bm (1 ≀ bj ≀ 109), where bj is renovation cost of the j-th building.The fourth line contains m integers p1, p2, ..., pm (1 ≀ pj ≀ 109), where pj is the demolishing cost of the j-th building.
Output single integer β€” the maximal number of buildings the mayor can demolish.
In the third example the mayor acts as follows.In the first month he obtains 6 burles tranche and demolishes buildings #2 (renovation cost 6, demolishing cost 4) and #4 (renovation cost 5, demolishing cost 2). He spends all the money on it.After getting the second month tranche of 3 burles, the mayor selects only building #1 (renovation cost 3, demolishing cost 1) for demolishing. As a result, he saves 2 burles for the next months.In the third month he gets 2 burle tranche, but decides not to demolish any buildings at all. As a result, he has 2 + 2 = 4 burles in the bank.This reserve will be spent on the fourth month together with the 4-th tranche for demolishing of houses #3 and #5 (renovation cost is 4 for each, demolishing costs are 3 and 5 correspondingly). After this month his budget is empty.Finally, after getting the last tranche of 3 burles, the mayor demolishes building #6 (renovation cost 2, demolishing cost 3).As it can be seen, he demolished all 6 buildings.
Input: 2 32 46 2 31 3 2 | Output: 2
Expert
3
1,843
524
79
8
1,517
E
1517E
E. Group Photo
2,500
binary search; data structures; implementation; two pointers
In the 2050 Conference, some people from the competitive programming community meet together and are going to take a photo. The \(n\) people form a line. They are numbered from \(1\) to \(n\) from left to right. Each of them either holds a cardboard with the letter 'C' or a cardboard with the letter 'P'.Let \(C=\{c_1,c_2,\dots,c_m\}\) \((c_1<c_2<\ldots <c_m)\) be the set of people who hold cardboards of 'C'. Let \(P=\{p_1,p_2,\dots,p_k\}\) \((p_1<p_2<\ldots <p_k)\) be the set of people who hold cardboards of 'P'. The photo is good if and only if it satisfies the following constraints: \(C\cup P=\{1,2,\dots,n\}\) \(C\cap P =\emptyset \). \(c_i-c_{i-1}\leq c_{i+1}-c_i(1< i <m)\). \(p_i-p_{i-1}\geq p_{i+1}-p_i(1< i <k)\). Given an array \(a_1,\ldots, a_n\), please find the number of good photos satisfying the following condition: $$$\(\sum\limits_{x\in C} a_x < \sum\limits_{y\in P} a_y.\)\(The answer can be large, so output it modulo \)998\,244\,353$$$. Two photos are different if and only if there exists at least one person who holds a cardboard of 'C' in one photo but holds a cardboard of 'P' in the other.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 200\,000\)). Description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1\leq n\leq 200\,000\)).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^9\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(200\,000\).
For each test case, output the answer modulo \(998\,244\,353\) in a separate line.
For the first test case, there are \(10\) possible good photos satisfying the condition: PPPPP, CPPPP, PCPPP, CCPPP, PCCPP, PCPCP, PPPPC, CPPPC, PCPPC, PPPCC.For the second test case, there are \(7\) possible good photos satisfying the condition: PPPP, PCPP, PCCP, PPPC, PCPC, PPCC, PCCC.
Input: 3 5 2 1 2 1 1 4 9 2 2 2 1 998244353 | Output: 10 7 1
Expert
4
1,122
432
82
15
1,989
E
1989E
E. Distance to Different
2,300
combinatorics; dp; math
Consider an array \(a\) of \(n\) integers, where every element is from \(1\) to \(k\), and every integer from \(1\) to \(k\) appears at least once.Let the array \(b\) be constructed as follows: for the \(i\)-th element of \(a\), \(b_i\) is the distance to the closest element in \(a\) which is not equal to \(a_i\). In other words, \(b_i = \min \limits_{j \in [1, n], a_j \ne a_i} |i - j|\).For example, if \(a = [1, 1, 2, 3, 3, 3, 3, 1]\), then \(b = [2, 1, 1, 1, 2, 2, 1, 1]\).Calculate the number of different arrays \(b\) you can obtain if you consider all possible arrays \(a\), and print it modulo \(998244353\).
The only line of the input contains two integers \(n\) and \(k\) (\(2 \le n \le 2 \cdot 10^5\); \(2 \le k \le \min(n, 10)\)).
Print one integer β€” the number of different arrays \(b\) you can obtain, taken modulo \(998244353\).
Input: 2 2 | Output: 1
Expert
3
618
125
100
19
2,127
D
2127D
D. Root was Built by Love, Broken by Destiny
1,800
combinatorics; dfs and similar; graphs; trees
Heartfall River runs horizontally through Destinyland and divides it into the northern and southern sides.Engineer Root wants to build \(n\) houses along the river, numbered from \(1\) to \(n\). All houses on the northern side and all houses on the southern side must lie along straight lines parallel to Heartfall River.There will be \(m\) bridges, with the \(i\)-th bridge connecting house \(u_i\) and house \(v_i\) (\(u_i \ne v_i\)). It is guaranteed that all \(n\) houses are connected by these bridges, that is, you can travel from any house to any other by crossing bridges. Also, there are no two bridges connecting the same pair of houses.Root wants to know how many ways there are to arrange the \(n\) houses along the river, modulo \(10^9+7\), such that the following conditions hold for the planned \(m\) bridges: For every bridge, the two houses it connects lie on opposite sides of the river; The bridges do not cross when drawn as straight lines between the houses. A possible arrangement of the houses when \(n=5\). Two arrangements are considered different if at least one of the following conditions holds: There exists a house that lies on a different side in each arrangement; There exist two houses \(a\) and \(b\) that are on the same side in both arrangements, but \(a\) comes before \(b\) in one arrangement and \(b\) comes before \(a\) in the other. Since Root is distracted by his ex, whom destiny separated from him, he asks you to calculate the number of ways to arrange the houses along the river, modulo \(10^9+7\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The first line of each test case contains two integers \(n\) and \(m\) (\(2 \leq n \leq 2 \cdot 10^5\), \(n-1 \leq m \leq \min\left(\frac{n(n-1)}{2}, 2 \cdot 10^5\right)\)) β€” the number of houses and the number of bridges.Then \(m\) lines follow, the \(i\)-th line containing two integers \(u_i\) and \(v_i\) (\(1 \leq u_i,v_i \leq n\), \(u_i\ne v_i\)) β€” the two houses that the \(i\)-th bridge connects.It is guaranteed that all the \(n\) houses are connected by the bridges, and there are no two bridges connecting the same pair of houses.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\), and the sum of \(m\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output a single integer β€” the number of ways to arrange the \(n\) houses along the river, modulo \(10^9+7\).
In the first test case, either house \(1\) should be built on the northern side and house \(2\) on the southern side, or vice versa.In the second test case, at least two houses must be built on the same side of the river. But every pair of houses is connected by a bridge. So in every arrangement, at least one bridge will not cross the river. Thus, the answer is \(0\).In the third test case, one of the possible arrangements of the houses is provided in the problem statement.
Input: 42 11 23 31 21 32 35 41 21 33 43 54 31 21 31 4 | Output: 2 0 8 12
Medium
4
1,544
870
128
21
1,271
F
1271F
F. Divide The Students
2,700
brute force
Recently a lot of students were enrolled in Berland State University. All students were divided into groups according to their education program. Some groups turned out to be too large to attend lessons in the same auditorium, so these groups should be divided into two subgroups. Your task is to help divide the first-year students of the computer science faculty.There are \(t\) new groups belonging to this faculty. Students have to attend classes on three different subjects β€” maths, programming and P. E. All classes are held in different places according to the subject β€” maths classes are held in auditoriums, programming classes are held in computer labs, and P. E. classes are held in gyms.Each group should be divided into two subgroups so that there is enough space in every auditorium, lab or gym for all students of the subgroup. For the first subgroup of the \(i\)-th group, maths classes are held in an auditorium with capacity of \(a_{i, 1}\) students; programming classes are held in a lab that accomodates up to \(b_{i, 1}\) students; and P. E. classes are held in a gym having enough place for \(c_{i, 1}\) students. Analogically, the auditorium, lab and gym for the second subgroup can accept no more than \(a_{i, 2}\), \(b_{i, 2}\) and \(c_{i, 2}\) students, respectively.As usual, some students skip some classes. Each student considers some number of subjects (from \(0\) to \(3\)) to be useless β€” that means, he skips all classes on these subjects (and attends all other classes). This data is given to you as follows β€” the \(i\)-th group consists of: \(d_{i, 1}\) students which attend all classes; \(d_{i, 2}\) students which attend all classes, except for P. E.; \(d_{i, 3}\) students which attend all classes, except for programming; \(d_{i, 4}\) students which attend only maths classes; \(d_{i, 5}\) students which attend all classes, except for maths; \(d_{i, 6}\) students which attend only programming classes; \(d_{i, 7}\) students which attend only P. E. There is one more type of students β€” those who don't attend any classes at all (but they, obviously, don't need any place in auditoriums, labs or gyms, so the number of those students is insignificant in this problem).Your task is to divide each group into two subgroups so that every auditorium (or lab, or gym) assigned to each subgroup has enough place for all students from this subgroup attending the corresponding classes (if it is possible). Each student of the \(i\)-th group should belong to exactly one subgroup of the \(i\)-th group; it is forbidden to move students between groups.
The first line contains one integer \(t\) (\(1 \le t \le 300\)) β€” the number of groups.Then the descriptions of groups follow. The description of the \(i\)-th group consists of three lines: the first line contains three integers \(a_{i, 1}\), \(b_{i, 1}\) and \(c_{i, 1}\) (\(1 \le a_{i, 1}, b_{i, 1}, c_{i, 1} \le 3000\)) β€” the capacity of the auditorium, lab and gym assigned to the first subgroup of the \(i\)-th group, respectively; the second line contains three integers \(a_{i, 2}\), \(b_{i, 2}\) and \(c_{i, 2}\) (\(1 \le a_{i, 2}, b_{i, 2}, c_{i, 2} \le 3000\)) β€” the capacity of the auditorium, lab and gym assigned to the second subgroup of the \(i\)-th group, respectively; the third line contains integers \(d_{i, 1}\), \(d_{i, 2}\), ..., \(d_{i, 7}\) (\(0 \le d_{i, j} \le 3000\)) β€” the number of students belonging to each of the seven aforementioned types in the \(i\)-th group. It is not guaranteed that the sum of these values is positive β€” a group can consist entirely of students that don't attend classes at all. It is guaranteed that the total number of students in all groups is not greater than \(3000\).
For each group, print the result of its division as follows: if it is impossible to divide the group, print one integer \(-1\); otherwise print seven integers \(f_{i, 1}\), \(f_{i, 2}\), ..., \(f_{i, 7}\) (\(0 \le f_{i, j} \le d_{i, j}\)) β€” the number of students the first, second, ..., seventh type in the first subgroup of the \(i\)-th group (all other students will be assigned to the second subgroup). If there are multiple answers, print any of them.
Input: 3 9 4 13 1 10 3 1 2 3 4 5 6 7 9 4 13 1 10 3 2 1 3 4 5 6 7 1 2 3 4 5 6 0 0 0 0 0 0 0 | Output: 1 1 3 4 2 0 7 -1 0 0 0 0 0 0 0
Master
1
2,583
1,128
456
12
873
E
873E
E. Awards For Contestants
2,300
brute force; data structures; dp
Alexey recently held a programming contest for students from Berland. n students participated in a contest, i-th of them solved ai problems. Now he wants to award some contestants. Alexey can award the students with diplomas of three different degrees. Each student either will receive one diploma of some degree, or won't receive any diplomas at all. Let cntx be the number of students that are awarded with diplomas of degree x (1 ≀ x ≀ 3). The following conditions must hold: For each x (1 ≀ x ≀ 3) cntx > 0; For any two degrees x and y cntx ≀ 2Β·cnty. Of course, there are a lot of ways to distribute the diplomas. Let bi be the degree of diploma i-th student will receive (or - 1 if i-th student won't receive any diplomas). Also for any x such that 1 ≀ x ≀ 3 let cx be the maximum number of problems solved by a student that receives a diploma of degree x, and dx be the minimum number of problems solved by a student that receives a diploma of degree x. Alexey wants to distribute the diplomas in such a way that: If student i solved more problems than student j, then he has to be awarded not worse than student j (it's impossible that student j receives a diploma and i doesn't receive any, and also it's impossible that both of them receive a diploma, but bj < bi); d1 - c2 is maximum possible; Among all ways that maximize the previous expression, d2 - c3 is maximum possible; Among all ways that correspond to the two previous conditions, d3 - c - 1 is maximum possible, where c - 1 is the maximum number of problems solved by a student that doesn't receive any diploma (or 0 if each student is awarded with some diploma). Help Alexey to find a way to award the contestants!
The first line contains one integer number n (3 ≀ n ≀ 3000).The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 5000).
Output n numbers. i-th number must be equal to the degree of diploma i-th contestant will receive (or - 1 if he doesn't receive any diploma).If there are multiple optimal solutions, print any of them. It is guaranteed that the answer always exists.
Input: 41 2 3 4 | Output: 3 3 2 1
Expert
3
1,685
135
248
8
1,707
E
1707E
E. Replace
3,500
binary search; data structures
You are given an integer array \(a_1,\ldots, a_n\), where \(1\le a_i \le n\) for all \(i\).There's a ""replace"" function \(f\) which takes a pair of integers \((l, r)\), where \(l \le r\), as input and outputs the pair $$$\(f\big( (l, r) \big)=\left(\min\{a_l,a_{l+1},\ldots,a_r\},\, \max\{a_l,a_{l+1},\ldots,a_r\}\right).\)\(Consider repeated calls of this function. That is, from a starting pair \)(l, r)\( we get \)f\big((l, r)\big)\(, then \)f\big(f\big((l, r)\big)\big)\(, then \)f\big(f\big(f\big((l, r)\big)\big)\big)\(, and so on.Now you need to answer \)q\( queries. For the \)i\(-th query you have two integers \)l_i\( and \)r_i\( (\)1\le l_i\le r_i\le n\(). You must answer the minimum number of times you must apply the ""replace"" function to the pair \)(l_i,r_i)\( to get \)(1, n)$$$, or report that it is impossible.
The first line contains two positive integers \(n\), \(q\) (\(1\le n,q\le 10^5\)) β€” the length of the sequence \(a\) and the number of the queries.The second line contains \(n\) positive integers \(a_1,a_2,\ldots,a_n\) (\(1\le a_i\le n\)) β€” the sequence \(a\).Each line of the following \(q\) lines contains two integers \(l_i\), \(r_i\) (\(1\le l_i\le r_i\le n\)) β€” the queries.
For each query, output the required number of times, or \(-1\) if it is impossible.
In the first example, \(n=5\) and \(a=[2,5,4,1,3]\).For the first query: \((4,4)\to(1,1)\to(2,2)\to(5,5)\to(3,3)\to(4,4)\to\ldots\), so it's impossible to get \((1,5)\).For the second query, you already have \((1,5)\).For the third query: \((1,4)\to(1,5)\).For the fourth query: \((3,5)\to(1,4)\to(1,5)\).For the fifth query: \((4,5)\to(1,3)\to(2,5)\to(1,5)\).For the sixth query: \((2,3)\to(4,5)\to(1,3)\to(2,5)\to(1,5)\).
Input: 5 6 2 5 4 1 3 4 4 1 5 1 4 3 5 4 5 2 3 | Output: -1 0 1 2 3 4
Master
2
832
379
83
17
858
B
858B
B. Which floor?
1,500
brute force; implementation
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.Given this information, is it possible to restore the exact floor for flat n?
The first line contains two integers n and m (1 ≀ n ≀ 100, 0 ≀ m ≀ 100), where n is the number of the flat you need to restore floor for, and m is the number of flats in Polycarp's memory.m lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers ki, fi (1 ≀ ki ≀ 100, 1 ≀ fi ≀ 100), which means that the flat ki is on the fi-th floor. All values ki are distinct.It is guaranteed that the given information is not self-contradictory.
Print the number of the floor in which the n-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor.
In the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor.In the second example there can be 3 or 4 flats on each floor, so we can't restore the floor for the 8-th flat.
Input: 10 36 22 17 3 | Output: 4
Medium
2
908
472
178
8
1,368
H1
1368H1
H1. Breadboard Capacity (easy version)
3,300
dp; flows; greedy
This is an easier version of the problem H without modification queries.Lester and Delbert work at an electronics company. They are currently working on a microchip component serving to connect two independent parts of a large supercomputer.The component is built on top of a breadboard β€” a grid-like base for a microchip. The breadboard has \(n\) rows and \(m\) columns, and each row-column intersection contains a node. Also, on each side of the breadboard there are ports that can be attached to adjacent nodes. Left and right side have \(n\) ports each, and top and bottom side have \(m\) ports each. Each of the ports is connected on the outside to one of the parts bridged by the breadboard, and is colored red or blue respectively. Ports can be connected by wires going inside the breadboard. However, there are a few rules to follow: Each wire should connect a red port with a blue port, and each port should be connected to at most one wire. Each part of the wire should be horizontal or vertical, and turns are only possible at one of the nodes. To avoid interference, wires can not have common parts of non-zero length (but may have common nodes). Also, a wire can not cover the same segment of non-zero length twice.The capacity of the breadboard is the largest number of red-blue wire connections that can be made subject to the rules above. For example, the breadboard above has capacity \(7\), and one way to make seven connections is pictured below. Up to this point statements of both versions are identical. Differences follow below.Given the current breadboard configuration, help Lester and Delbert find its capacity efficiently.
The first line contains three integers \(n, m, q\) (\(1 \leq n, m \leq 10^5\), \(\pmb{q = 0}\)). \(n\) and \(m\) are the number of rows and columns of the breadboard respectively. In this version \(q\) is always zero, and is only present for consistency with the harder version.The next four lines describe initial coloring of the ports. Each character in these lines is either R or B, depending on the coloring of the respective port. The first two of these lines contain \(n\) characters each, and describe ports on the left and right sides respectively from top to bottom. The last two lines contain \(m\) characters each, and describe ports on the top and bottom sides respectively from left to right.
Print a single integer β€” the given breadboard capacity.
Input: 4 5 0 BBRR RBBR BBBBB RRRRR | Output: 7
Master
3
1,649
705
55
13
493
D
493D
D. Vasya and Chess
1,700
constructive algorithms; games; math
Vasya decided to learn to play chess. Classic chess doesn't seem interesting to him, so he plays his own sort of chess.The queen is the piece that captures all squares on its vertical, horizontal and diagonal lines. If the cell is located on the same vertical, horizontal or diagonal line with queen, and the cell contains a piece of the enemy color, the queen is able to move to this square. After that the enemy's piece is removed from the board. The queen cannot move to a cell containing an enemy piece if there is some other piece between it and the queen. There is an n Γ— n chessboard. We'll denote a cell on the intersection of the r-th row and c-th column as (r, c). The square (1, 1) contains the white queen and the square (1, n) contains the black queen. All other squares contain green pawns that don't belong to anyone.The players move in turns. The player that moves first plays for the white queen, his opponent plays for the black queen.On each move the player has to capture some piece with his queen (that is, move to a square that contains either a green pawn or the enemy queen). The player loses if either he cannot capture any piece during his move or the opponent took his queen during the previous move. Help Vasya determine who wins if both players play with an optimal strategy on the board n Γ— n.
The input contains a single number n (2 ≀ n ≀ 109) β€” the size of the board.
On the first line print the answer to problem β€” string ""white"" or string ""black"", depending on who wins if the both players play optimally. If the answer is ""white"", then you should also print two integers r and c representing the cell (r, c), where the first player should make his first move to win. If there are multiple such cells, print the one with the minimum r. If there are still multiple squares, print the one with the minimum c.
In the first sample test the white queen can capture the black queen at the first move, so the white player wins.In the second test from the statement if the white queen captures the green pawn located on the central vertical line, then it will be captured by the black queen during the next move. So the only move for the white player is to capture the green pawn located at (2, 1). Similarly, the black queen doesn't have any other options but to capture the green pawn located at (2, 3), otherwise if it goes to the middle vertical line, it will be captured by the white queen.During the next move the same thing happens β€” neither the white, nor the black queen has other options rather than to capture green pawns situated above them. Thus, the white queen ends up on square (3, 1), and the black queen ends up on square (3, 3). In this situation the white queen has to capture any of the green pawns located on the middle vertical line, after that it will be captured by the black queen. Thus, the player who plays for the black queen wins.
Input: 2 | Output: white1 2
Medium
3
1,323
75
446
4
146
A
146A
A. Lucky Ticket
800
implementation
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals n (n is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first n / 2 digits) equals the sum of digits in the second half (the sum of the last n / 2 digits). Check if the given ticket is lucky.
The first line contains an even integer n (2 ≀ n ≀ 50) β€” the length of the ticket number that needs to be checked. The second line contains an integer whose length equals exactly n β€” the ticket number. The number may contain leading zeros.
On the first line print ""YES"" if the given ticket number is lucky. Otherwise, print ""NO"" (without the quotes).
In the first sample the sum of digits in the first half does not equal the sum of digits in the second half (4 β‰  7).In the second sample the ticket number is not the lucky number.
Input: 247 | Output: NO
Beginner
1
615
239
114
1
964
B
964B
B. Messages
1,300
math
There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.Also, each minute Vasya's bank account receives CΒ·k, where k is the amount of received but unread messages.Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.Determine the maximum amount of money Vasya's bank account can hold after T minutes.
The first line contains five integers n, A, B, C and T (1 ≀ n, A, B, C, T ≀ 1000).The second string contains n integers ti (1 ≀ ti ≀ T).
Output one integer β€” the answer to the problem.
In the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, nΒ·A = 20 in total.In the second sample the messages can be read at any integer moment.In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4Β·3) + (5 - 3Β·3) + (5 - 2Β·3) + (5 - 1Β·3) + 5 = - 5 points. This is 35 in total.
Input: 4 5 5 3 51 5 5 4 | Output: 20
Easy
1
757
136
47
9
2,008
B
2008B
B. Square or Not
800
brute force; math; strings
A beautiful binary matrix is a matrix that has ones on its edges and zeros inside. Examples of four beautiful binary matrices. Today, Sakurako was playing with a beautiful binary matrix of size \(r \times c\) and created a binary string \(s\) by writing down all the rows of the matrix, starting from the first and ending with the \(r\)-th. More formally, the element from the matrix in the \(i\)-th row and \(j\)-th column corresponds to the \(((i-1)*c+j)\)-th element of the string.You need to check whether the beautiful matrix from which the string \(s\) was obtained could be squared. In other words, you need to check whether the string \(s\) could have been build from a square beautiful binary matrix (i.e., one where \(r=c\)).
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The first line of each test case contains a single integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) β€” the length of the string.The second line of each test case contains the string \(s\) of length \(n\). The string is always the result of writing out the strings of a beautiful matrix.It is guaranteed that the sum of \(n\) across all test cases does not exceed \(2 \cdot 10^5\).
Print ""Yes"", if the original matrix could have been square, and ""No"" otherwise.
For the second test case, string 1111 can be obtained from the matrix: \(1\)\(1\)\(1\)\(1\) For the third test case, string 111101111 can be obtained from the matrix: \(1\)\(1\)\(1\)\(1\)\(0\)\(1\)\(1\)\(1\)\(1\) There is no square matrix in the fourth case, such that the string can be obtained from it.
Input: 5211411119111101111911111111112111110011111 | Output: No Yes Yes No No
Beginner
3
735
472
83
20
1,743
F
1743F
F. Intersection and Union
2,300
data structures; dp; matrices; probabilities
You are given \(n\) segments on the coordinate axis. The \(i\)-th segment is \([l_i, r_i]\). Let's denote the set of all integer points belonging to the \(i\)-th segment as \(S_i\).Let \(A \cup B\) be the union of two sets \(A\) and \(B\), \(A \cap B\) be the intersection of two sets \(A\) and \(B\), and \(A \oplus B\) be the symmetric difference of \(A\) and \(B\) (a set which contains all elements of \(A\) and all elements of \(B\), except for the ones that belong to both sets).Let \([\mathbin{op}_1, \mathbin{op}_2, \dots, \mathbin{op}_{n-1}]\) be an array where each element is either \(\cup\), \(\oplus\), or \(\cap\). Over all \(3^{n-1}\) ways to choose this array, calculate the sum of the following values:$$$\(|(((S_1\ \mathbin{op}_1\ S_2)\ \mathbin{op}_2\ S_3)\ \mathbin{op}_3\ S_4)\ \dots\ \mathbin{op}_{n-1}\ S_n|\)\(In this expression, \)|S|\( denotes the size of the set \)S$$$.
The first line contains one integer \(n\) (\(2 \le n \le 3 \cdot 10^5\)).Then, \(n\) lines follow. The \(i\)-th of them contains two integers \(l_i\) and \(r_i\) (\(0 \le l_i \le r_i \le 3 \cdot 10^5\)).
Print one integer β€” the sum of \(|(((S_1\ \mathbin{op}_1\ S_2)\ \mathbin{op}_2\ S_3)\ \mathbin{op}_3\ S_4)\ \dots\ \mathbin{op}_{n-1}\ S_n|\) over all possible ways to choose \([\mathbin{op}_1, \mathbin{op}_2, \dots, \mathbin{op}_{n-1}]\). Since the answer can be huge, print it modulo \(998244353\).
Input: 4 3 5 4 8 2 2 1 9 | Output: 162
Expert
4
897
203
300
17
1,533
C
1533C
C. Sweets
0
*special; data structures; implementation
Anya came to her friend's birthday party. There are \(n\) delicious sweets on a circle table (for convenience, we will number them from \(1\) to \(n\) in clockwise direction). For each of the sweets, it is known whether Anya likes it or not. Anya decided that she should eat all the sweets that are on the table, and she likes them.However, eating all the sweets in some random order is too boring. Therefore, Anya came up with a game that will make the process of eating sweets more interesting.The game is played according to the following rules: if there are no sweets that Anya likes left on the table, then the game ends; at the very beginning of the game, if there is at least one sweet on the table that Anya wants to eat, she eats the sweet number \(1\); after Anya has eaten some sweet, she counts \(k\) sweets clockwise, starting from the next sweet in the circle, and eats the \(k\)-th sweet in the count (if there are less than \(k\) sweets in the circle, some sweets can participate in the count more than once, and the last sweet in the count is picked). Obviously, the sweets that have already been eaten do not participate in the count. For example, let \(6\) sweets be arranged in a circle, Anya likes sweets \(4\), \(5\) and \(6\), \(k = 4\). Then the game goes as follows: initially there are sweets \([1, 2, 3, 4, 5, 6]\) on the table, Anya chooses the sweet number \(1\). Anya eats the sweet number \(1\), after that, there are sweets \([2, 3, 4, 5, 6]\) on the table. Anya counts \(4\) sweets, starting with the \(2\)-nd sweet, and stops at the \(5\)-th sweet. Anya eats the \(5\)-th sweet, after that, there are sweets \([2, 3, 4, 6]\) on the table. Anya counts \(4\) sweets, starting with the \(6\)-th sweet, and stops at the \(4\)-th sweet. Anya eats the sweet number \(4\), after that, there are sweets \([2, 3, 6]\) on the table. Anya counts \(4\) sweets, starting with the \(6\)-th sweet, and stops at the \(6\)-th sweet. Anya eats the sweet number \(6\), after that, there are sweets \([2, 3]\) on the table. There are no sweets that Anya likes on the table, so the game ends. Your task is to calculate the number of sweets that Anya will eat.
The first line contains a single integer \(t\) (\(1 \le t \le 5000\)) β€” the number of test cases.The first line of each test case contains two integers \(n\) and \(k\) (\(1 \le k \le n \le 5000\)) β€” the number of sweets and the parameter \(k\).The next line contains the string \(s\), where \(s_i = 1\) if Anya likes \(i\)-th sweet, and \(s_i = 0\) otherwise.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5000\).
For each test case, print one integer β€” the number of sweets that Anya will eat.
The first test case of the example is described in the statement.
Input: 4 6 4 000111 7 3 0000100 3 2 000 5 1 10011 | Output: 4 4 0 5
Beginner
3
2,172
443
80
15
302
B
302B
B. Eugeny and Play List
1,200
binary search; implementation; two pointers
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.
The first line contains two integers n, m (1 ≀ n, m ≀ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≀ ci, ti ≀ 109) β€” the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 .The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m).The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.
Print m integers β€” the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.
Input: 1 22 81 16 | Output: 11
Easy
3
737
666
158
3
1,884
C
1884C
C. Medium Design
1,700
brute force; data structures; dp; greedy; sortings
The array \(a_1, a_2, \ldots, a_m\) is initially filled with zeroes. You are given \(n\) pairwise distinct segments \(1 \le l_i \le r_i \le m\). You have to select an arbitrary subset of these segments (in particular, you may select an empty set). Next, you do the following: For each \(i = 1, 2, \ldots, n\), if the segment \((l_i, r_i)\) has been selected to the subset, then for each index \(l_i \le j \le r_i\) you increase \(a_j\) by \(1\) (i. e. \(a_j\) is replaced by \(a_j + 1\)). If the segment \((l_i, r_i)\) has not been selected, the array does not change. Next (after processing all values of \(i = 1, 2, \ldots, n\)), you compute \(\max(a)\) as the maximum value among all elements of \(a\). Analogously, compute \(\min(a)\) as the minimum value. Finally, the cost of the selected subset of segments is declared as \(\max(a) - \min(a)\).Please, find the maximum cost among all subsets of segments.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows.The first line of each test case contains two integers \(n\) and \(m\) (\(1 \le n \le 10^5\), \(1 \le m \le 10^9\)) β€” the number of segments and the length of the array.The following \(n\) lines of each test case describe the segments. The \(i\)-th of these lines contains two integers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le m\)). It is guaranteed that the segments are pairwise distinct.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output the maximum cost among all subsets of the given set of segments.
In the first test case, there is only one segment available. If we do not select it, then the array will be \(a = [0, 0, 0]\), and the cost of such (empty) subset of segments will be \(0\). If, however, we select the only segment, the array will be \(a = [0, 1, 0]\), and the cost will be \(1 - 0 = 1\).In the second test case, we can select all the segments: the array will be \(a = [0, 1, 2, 3, 2, 1, 0, 0]\) in this case. The cost will be \(3 - 0 = 3\).
Input: 61 32 23 82 43 54 66 31 11 21 32 22 33 37 62 21 61 25 61 54 43 66 276 265 172 320 211 2212 244 10000000002 9999999993 1000000000123456789 9876543219274 123456789 | Output: 1 3 2 3 4 4
Medium
5
911
647
91
18
1,338
D
1338D
D. Nested Rubber Bands
2,700
constructive algorithms; dfs and similar; dp; math; trees
You have a tree of \(n\) vertices. You are going to convert this tree into \(n\) rubber bands on infinitely large plane. Conversion rule follows: For every pair of vertices \(a\) and \(b\), rubber bands \(a\) and \(b\) should intersect if and only if there is an edge exists between \(a\) and \(b\) in the tree. Shape of rubber bands must be a simple loop. In other words, rubber band is a loop which doesn't self-intersect. Now let's define following things: Rubber band \(a\) includes rubber band \(b\), if and only if rubber band \(b\) is in rubber band \(a\)'s area, and they don't intersect each other. Sequence of rubber bands \(a_{1}, a_{2}, \ldots, a_{k}\) (\(k \ge 2\)) are nested, if and only if for all \(i\) (\(2 \le i \le k\)), \(a_{i-1}\) includes \(a_{i}\). This is an example of conversion. Note that rubber bands \(5\) and \(6\) are nested. It can be proved that is it possible to make a conversion and sequence of nested rubber bands under given constraints.What is the maximum length of sequence of nested rubber bands can be obtained from given tree? Find and print it.
The first line contains integer \(n\) (\(3 \le n \le 10^{5}\)) β€” the number of vertices in tree.The \(i\)-th of the next \(n-1\) lines contains two integers \(a_{i}\) and \(b_{i}\) (\(1 \le a_{i} \lt b_{i} \le n\)) β€” it means there is an edge between \(a_{i}\) and \(b_{i}\). It is guaranteed that given graph forms tree of \(n\) vertices.
Print the answer.
In the first sample, you can obtain a nested sequence of \(4\) rubber bands(\(1\), \(2\), \(5\), and \(6\)) by the conversion shown below. Of course, there are other conversions exist to make a nested sequence of \(4\) rubber bands. However, you cannot make sequence of \(5\) or more nested rubber bands with given tree. You can see one of the possible conversions for the second sample below.
Input: 6 1 3 2 3 3 4 4 5 4 6 | Output: 4
Master
5
1,089
339
17
13
2,033
F
2033F
F. Kosuke's Sloth
1,800
brute force; math; number theory
Kosuke is too lazy. He will not give you any legend, just the task:Fibonacci numbers are defined as follows: \(f(1)=f(2)=1\). \(f(n)=f(n-1)+f(n-2)\) \((3\le n)\) We denote \(G(n,k)\) as an index of the \(n\)-th Fibonacci number that is divisible by \(k\). For given \(n\) and \(k\), compute \(G(n,k)\).As this number can be too big, output it by modulo \(10^9+7\).For example: \(G(3,2)=9\) because the \(3\)-rd Fibonacci number that is divisible by \(2\) is \(34\). \([1,1,\textbf{2},3,5,\textbf{8},13,21,\textbf{34}]\).
The first line of the input data contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The first and only line contains two integers \(n\) and \(k\) (\(1 \le n \le 10^{18}\), \(1 \le k \le 10^5\)).It is guaranteed that the sum of \(k\) across all test cases does not exceed \(10^6\).
For each test case, output the only number: the value \(G(n,k)\) taken by modulo \(10^9+7\).
Input: 33 2100 11000000000000 1377 | Output: 9 100 999244007
Medium
3
520
311
92
20
39
J
39J
J. Spelling Check
1,500
hashing; implementation; strings
Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he decided to invent the function that will correct the words itself. Petya started from analyzing the case that happens to him most of the time, when all one needs is to delete one letter for the word to match a word from the dictionary. Thus, Petya faces one mini-task: he has a printed word and a word from the dictionary, and he should delete one letter from the first word to get the second one. And now the very non-trivial question that Petya faces is: which letter should he delete?
The input data contains two strings, consisting of lower-case Latin letters. The length of each string is from 1 to 106 symbols inclusive, the first string contains exactly 1 symbol more than the second one.
In the first line output the number of positions of the symbols in the first string, after the deleting of which the first string becomes identical to the second one. In the second line output space-separated positions of these symbols in increasing order. The positions are numbered starting from 1. If it is impossible to make the first string identical to the second string by deleting one symbol, output one number 0.
Input: abdrakadabraabrakadabra | Output: 13
Medium
3
806
207
421
0
1,898
E
1898E
E. Sofia and Strings
2,200
data structures; greedy; sortings; strings; two pointers
Sofia has a string \(s\) of length \(n\), consisting only of lowercase English letters. She can perform operations of the following types with this string. Select an index \(1 \le i \le |s|\) and remove the character \(s_i\) from the string. Select a pair of indices \((l, r)\) (\(1 \le l \le r \le |s|\)) and sort the substring \(s_{l} s_{l+1} \ldots s_r\) in alphabetical order. Here, \(|s|\) denotes the current length of \(s\). In particular, \(|s| = n\) before the first operation. For example, if \(s = \mathtt{sofia}\), then performing the operation of the first type with \(i=4\) results in \(s\) becoming \(\mathtt{sofa}\), and performing the operation of the second type with \((l, r) = (2, 4)\) after that results in \(s\) becoming \(\mathtt{safo}\).Sofia wants to obtain the string \(t\) of length \(m\) after performing zero or more operations on string \(s\) as described above. Please determine whether it is possible or not.
The first line contains one integer \(t\) (\(1 \leq t \leq 10\,000\)) β€” the number of test cases.The first line of each test case contains two integers \(n\), \(m\) (\(1\leq m \leq n \leq 2\cdot 10^5\)) β€” the lengths of string \(s\) and \(t\), respectively.The second line of each test case contains the string \(s\) of length \(n\), consisting only of lowercase English letters.The third line of each test case contains the string \(t\) of length \(m\), consisting only of lowercase English 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 ""YES"" if Sofia can obtain the string \(t\) from \(s\) using the operations above. Otherwise, output ""NO"".You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
In the first test case, Sofia can perform the following operation: operation of the second type with \(l=1\) and \(r=5\): string \(s\) becomes \(\mathtt{afios}\) after it. In the second test case, Sofia can perform the following operations: operation of the second type with \(l=1\) and \(r=2\): string \(s\) becomes \(\mathtt{bca}\) after it; operation of the first type with \(i=3\): string \(s\) becomes \(\mathtt{bc}\) after it. In the third test case, it can be shown that it is impossible to obtain \(t\) from \(s\) using the provided operations.
Input: 85 5sofiaafios3 2cbabc5 1sofiae15 7anavolimilovanaaamanan26 4abcdefghijklmnopqrstuvwxyznope26 4zyxwvutsrqponmlkjihgfedcbanope7 3apricotcat3 3cbaacb | Output: YES YES NO YES NO YES NO YES
Hard
5
940
591
297
18
617
D
617D
D. Polyline
1,700
constructive algorithms; implementation
There are three points marked on the coordinate plane. The goal is to make a simple polyline, without self-intersections and self-touches, such that it passes through all these points. Also, the polyline must consist of only segments parallel to the coordinate axes. You are to find the minimum number of segments this polyline may consist of.
Each of the three lines of the input contains two integers. The i-th line contains integers xi and yi ( - 109 ≀ xi, yi ≀ 109) β€” the coordinates of the i-th point. It is guaranteed that all points are distinct.
Print a single number β€” the minimum possible number of segments of the polyline.
The variant of the polyline in the first sample: The variant of the polyline in the second sample: The variant of the polyline in the third sample:
Input: 1 -11 11 2 | Output: 1
Medium
2
343
209
80
6
1,296
B
1296B
B. Food Buying
900
math
Mishka wants to buy some food in the nearby shop. Initially, he has \(s\) burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number \(1 \le x \le s\), buy food that costs exactly \(x\) burles and obtain \(\lfloor\frac{x}{10}\rfloor\) burles as a cashback (in other words, Mishka spends \(x\) burles and obtains \(\lfloor\frac{x}{10}\rfloor\) back). The operation \(\lfloor\frac{a}{b}\rfloor\) means \(a\) divided by \(b\) rounded down.It is guaranteed that you can always buy some food that costs \(x\) for any possible value of \(x\).Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has \(s=19\) burles then the maximum number of burles he can spend is \(21\). Firstly, he can spend \(x=10\) burles, obtain \(1\) burle as a cashback. Now he has \(s=10\) burles, so can spend \(x=10\) burles, obtain \(1\) burle as a cashback and spend it too.You have to answer \(t\) independent test cases.
The first line of the input contains one integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The next \(t\) lines describe test cases. Each test case is given on a separate line and consists of one integer \(s\) (\(1 \le s \le 10^9\)) β€” the number of burles Mishka initially has.
For each test case print the answer on it β€” the maximum number of burles Mishka can spend if he buys food optimally.
Input: 6 1 10 19 9876 12345 1000000000 | Output: 1 11 21 10973 13716 1111111111
Beginner
1
1,036
291
116
12
1,202
C
1202C
C. You Are Given a WASD-string...
2,100
brute force; data structures; dp; greedy; implementation; math; strings
You have a string \(s\) β€” a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β€” move one cell up; 'S' β€” move one cell down; 'A' β€” move one cell left; 'D' β€” move one cell right. Let \(Grid(s)\) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands \(s\). For example, if \(s = \text{DSAWWAW}\) then \(Grid(s)\) is the \(4 \times 3\) grid: you can place the robot in the cell \((3, 2)\); the robot performs the command 'D' and moves to \((3, 3)\); the robot performs the command 'S' and moves to \((4, 3)\); the robot performs the command 'A' and moves to \((4, 2)\); the robot performs the command 'W' and moves to \((3, 2)\); the robot performs the command 'W' and moves to \((2, 2)\); the robot performs the command 'A' and moves to \((2, 1)\); the robot performs the command 'W' and moves to \((1, 1)\). You have \(4\) extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence \(s\) to minimize the area of \(Grid(s)\).What is the minimum area of \(Grid(s)\) you can achieve?
The first line contains one integer \(T\) (\(1 \le T \le 1000\)) β€” the number of queries.Next \(T\) lines contain queries: one per line. This line contains single string \(s\) (\(1 \le |s| \le 2 \cdot 10^5\), \(s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}\)) β€” the sequence of commands.It's guaranteed that the total length of \(s\) over all queries doesn't exceed \(2 \cdot 10^5\).
Print \(T\) integers: one per query. For each query print the minimum area of \(Grid(s)\) you can achieve.
In the first query you have to get string \(\text{DSAWW}\underline{D}\text{AW}\).In second and third queries you can not decrease the area of \(Grid(s)\).
Input: 3 DSAWWAW D WA | Output: 8 2 4
Hard
7
1,273
388
106
12
254
D
254D
D. Rats
2,300
brute force; dfs and similar; graphs; implementation; shortest paths
Rats have bred to hundreds and hundreds in the basement of the store, owned by Vasily Petrovich. Vasily Petrovich may have not noticed their presence, but they got into the habit of sneaking into the warehouse and stealing food from there. Vasily Petrovich cannot put up with it anymore, he has to destroy the rats in the basement. Since mousetraps are outdated and do not help, and rat poison can poison inattentive people as well as rats, he chose a radical way: to blow up two grenades in the basement (he does not have more).In this problem, we will present the shop basement as a rectangular table of n Γ— m cells. Some of the cells are occupied by walls, and the rest of them are empty. Vasily has been watching the rats and he found out that at a certain time they go to sleep, and all the time they sleep in the same places. He wants to blow up a grenade when this convenient time comes. On the plan of his basement, he marked cells with sleeping rats in them. Naturally, these cells are not occupied by walls.Grenades can only blow up in a cell that is not occupied by a wall. The blast wave from a grenade distributes as follows. We assume that the grenade blast occurs at time 0. During this initial time only the cell where the grenade blew up gets 'clear'. If at time t some cell is clear, then at time t + 1 those side-neighbouring cells which are not occupied by the walls get clear too (some of them could have been cleared before). The blast wave distributes for exactly d seconds, then it dies immediately. An example of a distributing blast wave: Picture 1 shows the situation before the blast, and the following pictures show ""clear"" cells by time 0,1,2,3 and 4. Thus, the blast wave on the picture distributes for d = 4 seconds. Vasily Petrovich wonders, whether he can choose two cells to blast the grenades so as to clear all cells with sleeping rats. Write the program that finds it out.
The first line contains three integers n, m and d, separated by single spaces (4 ≀ n, m ≀ 1000, 1 ≀ d ≀ 8). Next n lines contain the table that represents the basement plan. Each row of the table consists of m characters. Character ""X"" means that the corresponding cell is occupied by the wall, character ""."" represents a empty cell, character ""R"" represents a empty cell with sleeping rats. It is guaranteed that the first and the last row, as well as the first and the last column consist of characters ""X"". The plan has at least two empty cells. There is at least one cell with sleeping rats.
If it is impossible to blow up all cells with sleeping rats, print a single integer -1. Otherwise, print four space-separated integers r1, c1, r2, c2, that mean that one grenade should go off in cell (r1, c1), and the other one β€” in cell (r2, c2). Consider the table rows numbered from top to bottom from 1 to n and the table columns β€” from left to right from 1 to m. As r1 and r2 represent the row numbers, and c1 and c2 represent the column numbers in the table, they should fit the limits: 1 ≀ r1, r2 ≀ n, 1 ≀ c1, c2 ≀ m. It is forbidden to blow a grenade twice in the same cell. The blast waves of the grenades can intersect. It is possible that one grenade blast destroys no rats, and the other one destroys all of them.
Input: 4 4 1XXXXXR.XX.RXXXXX | Output: 2 2 2 3
Expert
5
1,912
603
725
2
414
C
414C
C. Mashmokh and Reverse Operation
2,100
combinatorics; divide and conquer
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≀ j ≀ 2n - qi) should contain the elements a[(j - 1)Β·2qi + 1], a[(j - 1)Β·2qi + 2], ..., a[(j - 1)Β·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
The first line of input contains a single integer n (0 ≀ n ≀ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≀ a[i] ≀ 109), the initial array.The third line of input contains a single integer m (1 ≀ m ≀ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≀ qi ≀ n), the queries.Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
If we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i < j and x[i] > x[j].
Input: 22 1 4 341 2 0 2 | Output: 0660
Hard
2
1,161
542
96
4
248
E
248E
E. Piglet's Birthday
2,600
dp; math; probabilities
Piglet has got a birthday today. His friend Winnie the Pooh wants to make the best present for him β€” a honey pot. Of course Winnie realizes that he won't manage to get the full pot to Piglet. In fact, he is likely to eat all the honey from the pot. And as soon as Winnie planned a snack on is way, the pot should initially have as much honey as possible. The day before Winnie the Pooh replenished his honey stocks. Winnie-the-Pooh has n shelves at home, each shelf contains some, perhaps zero number of honey pots. During the day Winnie came to the honey shelves q times; on the i-th time he came to some shelf ui, took from it some pots ki, tasted the honey from each pot and put all those pots on some shelf vi. As Winnie chose the pots, he followed his intuition. And that means that among all sets of ki pots on shelf ui, he equiprobably chooses one.Now Winnie remembers all actions he performed with the honey pots. He wants to take to the party the pot he didn't try the day before. For that he must know the mathematical expectation of the number m of shelves that don't have a single untasted pot. To evaluate his chances better, Winnie-the-Pooh wants to know the value m after each action he performs.Your task is to write a program that will find those values for him.
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of shelves at Winnie's place. The second line contains n integers ai (1 ≀ i ≀ n, 0 ≀ ai ≀ 100) β€” the number of honey pots on a shelf number i. The next line contains integer q (1 ≀ q ≀ 105) β€” the number of actions Winnie did the day before. Then follow q lines, the i-th of them describes an event that follows chronologically; the line contains three integers ui, vi and ki (1 ≀ ui, vi ≀ n, 1 ≀ ki ≀ 5) β€” the number of the shelf from which Winnie took pots, the number of the shelf on which Winnie put the pots after he tasted each of them, and the number of the pots Winnie tasted, correspondingly.Consider the shelves with pots numbered with integers from 1 to n. It is guaranteed that Winnie-the-Pooh Never tried taking more pots from the shelf than it has.
For each Winnie's action print the value of the mathematical expectation m by the moment when this action is performed. The relative or absolute error of each value mustn't exceed 10 - 9.
Input: 32 2 351 2 12 1 21 2 23 1 13 2 2 | Output: 0.0000000000000.3333333333331.0000000000001.0000000000002.000000000000
Expert
3
1,279
843
187
2
627
E
627E
E. Orchestra
3,000
two pointers
Paul is at the orchestra. The string section is arranged in an r Γ— c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take.Two pictures are considered to be different if the coordinates of corresponding rectangles are different.
The first line of input contains four space-separated integers r, c, n, k (1 ≀ r, c, n ≀ 3000, 1 ≀ k ≀ min(n, 10)) β€” the number of rows and columns of the string section, the total number of violas, and the minimum number of violas Paul would like in his photograph, respectively.The next n lines each contain two integers xi and yi (1 ≀ xi ≀ r, 1 ≀ yi ≀ c): the position of the i-th viola. It is guaranteed that no location appears more than once in the input.
Print a single integer β€” the number of photographs Paul can take which include at least k violas.
We will use '*' to denote violinists and '#' to denote violists.In the first sample, the orchestra looks as follows: *#** Paul can take a photograph of just the viola, the 1 Γ— 2 column containing the viola, the 2 Γ— 1 row containing the viola, or the entire string section, for 4 pictures total.In the second sample, the orchestra looks as follows: #**##* Paul must take a photograph of the entire section.In the third sample, the orchestra looks the same as in the second sample.
Input: 2 2 1 11 2 | Output: 4
Master
1
476
461
97
6
714
A
714A
A. Meeting of Old Friends
1,100
implementation; math
Today an outstanding event is going to happen in the forest β€” hedgehog Filya will come to his old fried Sonya!Sonya is an owl and she sleeps during the day and stay awake from minute l1 to minute r1 inclusive. Also, during the minute k she prinks and is unavailable for Filya.Filya works a lot and he plans to visit Sonya from minute l2 to minute r2 inclusive.Calculate the number of minutes they will be able to spend together.
The only line of the input contains integers l1, r1, l2, r2 and k (1 ≀ l1, r1, l2, r2, k ≀ 1018, l1 ≀ r1, l2 ≀ r2), providing the segments of time for Sonya and Filya and the moment of time when Sonya prinks.
Print one integer β€” the number of minutes Sonya and Filya will be able to spend together.
In the first sample, they will be together during minutes 9 and 10.In the second sample, they will be together from minute 50 to minute 74 and from minute 76 to minute 100.
Input: 1 10 9 20 1 | Output: 2
Easy
2
428
208
89
7
963
B
963B
B. Destruction of a Tree
2,000
constructive algorithms; dfs and similar; dp; greedy; trees
You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges).A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted.Destroy all vertices in the given tree or determine that it is impossible.
The first line contains integer n (1 ≀ n ≀ 2Β·105) β€” number of vertices in a tree.The second line contains n integers p1, p2, ..., pn (0 ≀ pi ≀ n). If pi β‰  0 there is an edge between vertices i and pi. It is guaranteed that the given graph is a tree.
If it's possible to destroy all vertices, print ""YES"" (without quotes), otherwise print ""NO"" (without quotes).If it's possible to destroy all vertices, in the next n lines print the indices of the vertices in order you destroy them. If there are multiple correct answers, print any.
In the first example at first you have to remove the vertex with index 1 (after that, the edges (1, 2) and (1, 4) are removed), then the vertex with index 2 (and edges (2, 3) and (2, 5) are removed). After that there are no edges in the tree, so you can remove remaining vertices in any order.
Input: 50 1 2 1 2 | Output: YES12354
Hard
5
349
249
286
9
1,425
I
1425I
I. Impressive Harvesting of The Orchard
2,800
data structures
Mr. Chanek has an orchard structured as a rooted ternary tree with \(N\) vertices numbered from \(1\) to \(N\). The root of the tree is vertex \(1\). \(P_i\) denotes the parent of vertex \(i\), for \((2 \le i \le N)\). Interestingly, the height of the tree is not greater than \(10\). Height of a tree is defined to be the largest distance from the root to a vertex in the tree.There exist a bush on each vertex of the tree. Initially, all bushes have fruits. Fruits will not grow on bushes that currently already have fruits. The bush at vertex \(i\) will grow fruits after \(A_i\) days since its last harvest.Mr. Chanek will visit his orchard for \(Q\) days. In day \(i\), he will harvest all bushes that have fruits on the subtree of vertex \(X_i\). For each day, determine the sum of distances from every harvested bush to \(X_i\), and the number of harvested bush that day. Harvesting a bush means collecting all fruits on the bush.For example, if Mr. Chanek harvests all fruits on subtree of vertex \(X\), and harvested bushes \([Y_1, Y_2, \dots, Y_M]\), the sum of distances is \(\sum_{i = 1}^M \text{distance}(X, Y_i)\)\(\text{distance}(U, V)\) in a tree is defined to be the number of edges on the simple path from \(U\) to \(V\).
The first line contains two integers \(N\) and \(Q\) \((1 \le N,\ Q,\le 5 \cdot 10^4)\), which denotes the number of vertices and the number of days Mr. Chanek visits the orchard.The second line contains \(N\) integers \(A_i\) \((1 \le A_i \le 5 \cdot 10^4)\), which denotes the fruits growth speed on the bush at vertex \(i\), for \((1 \le i \le N)\).The third line contains \(N-1\) integers \(P_i\) \((1 \le P_i \le N, P_i \ne i)\), which denotes the parent of vertex \(i\) in the tree, for \((2 \le i \le N)\). It is guaranteed that each vertex can be the parent of at most \(3\) other vertices. It is also guaranteed that the height of the tree is not greater than \(10\).The next \(Q\) lines contain a single integer \(X_i\) \((1 \le X_i \le N)\), which denotes the start of Mr. Chanek's visit on day \(i\), for \((1 \le i \le Q)\).
Output \(Q\) lines, line \(i\) gives the sum of distances from the harvested bushes to \(X_i\), and the number of harvested bushes.
For the first example: On day 1, Mr. Chanek starts at vertex \(2\) and can harvest the bush at vertex 2. On day 2, Mr. Chanek starts at vertex \(1\) and only harvest from bush \(1\) (bush 2's fruit still has not grown yet). On day 3, Mr. Chanek starts at vertex \(1\) and harvests the fruits on bush \(1\) and \(2\). The sum of distances from every harvested bush to \(1\) is \(1\). For the second example, Mr. Chanek always starts at vertex \(1\). The bushes which Mr. Chanek harvests on day one, two, and three are \([1, 2, 3, 4, 5], [2, 3], [1, 2, 3, 5]\), respectively.
Input: 2 3 1 2 1 2 1 1 | Output: 0 1 0 1 1 2
Master
1
1,239
837
131
14
337
C
337C
C. Quiz
1,600
binary search; greedy; math; matrices; number theory
Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero.Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9).
The single line contains three space-separated integers n, m and k (2 ≀ k ≀ n ≀ 109; 0 ≀ m ≀ n).
Print a single integer β€” the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9).
Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points.Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4.Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number.
Input: 5 3 2 | Output: 3
Medium
5
1,004
96
123
3
923
E
923E
E. Perpetual Subtraction
3,100
fft; math; matrices
There is a number x initially written on a blackboard. You repeat the following action a fixed amount of times: take the number x currently written on a blackboard and erase it select an integer uniformly at random from the range [0, x] inclusive, and write it on the blackboard Determine the distribution of final number given the distribution of initial number and the number of steps.
The first line contains two integers, N (1 ≀ N ≀ 105) β€” the maximum number written on the blackboard β€” and M (0 ≀ M ≀ 1018) β€” the number of steps to perform.The second line contains N + 1 integers P0, P1, ..., PN (0 ≀ Pi < 998244353), where Pi describes the probability that the starting number is i. We can express this probability as irreducible fraction P / Q, then . It is guaranteed that the sum of all Pis equals 1 (modulo 998244353).
Output a single line of N + 1 integers, where Ri is the probability that the final number after M steps is i. It can be proven that the probability may always be expressed as an irreducible fraction P / Q. You are asked to output .
In the first case, we start with number 2. After one step, it will be 0, 1 or 2 with probability 1/3 each.In the second case, the number will remain 2 with probability 1/9. With probability 1/9 it stays 2 in the first round and changes to 1 in the next, and with probability 1/6 changes to 1 in the first round and stays in the second. In all other cases the final integer is 0.
Input: 2 10 0 1 | Output: 332748118 332748118 332748118
Master
3
387
440
231
9
429
E
429E
E. Points and Segments
3,000
graphs
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.Iahub wants to draw n distinct segments [li, ri] on the OX axis. He can draw each segment with either red or blue. The drawing is good if and only if the following requirement is met: for each point x of the OX axis consider all the segments that contains point x; suppose, that rx red segments and bx blue segments contain point x; for each point x inequality |rx - bx| ≀ 1 must be satisfied.A segment [l, r] contains a point x if and only if l ≀ x ≀ r.Iahub gives you the starting and ending points of all the segments. You have to find any good drawing for him.
The first line of input contains integer n (1 ≀ n ≀ 105) β€” the number of segments. The i-th of the next n lines contains two integers li and ri (0 ≀ li ≀ ri ≀ 109) β€” the borders of the i-th segment.It's guaranteed that all the segments are distinct.
If there is no good drawing for a given test, output a single integer -1. Otherwise output n integers; each integer must be 0 or 1. The i-th number denotes the color of the i-th segment (0 is red and 1 is blue).If there are multiple good drawings you can output any of them.
Input: 20 22 3 | Output: 0 1
Master
1
833
249
274
4
1,939
D
1939D
0
*special; dp; games
Beginner
3
0
0
0
19
1,558
D
1558D
D. Top-Notch Insertions
2,600
combinatorics; data structures
Consider the insertion sort algorithm used to sort an integer sequence \([a_1, a_2, \ldots, a_n]\) of length \(n\) in non-decreasing order.For each \(i\) in order from \(2\) to \(n\), do the following. If \(a_i \ge a_{i-1}\), do nothing and move on to the next value of \(i\). Otherwise, find the smallest \(j\) such that \(a_i < a_j\), shift the elements on positions from \(j\) to \(i-1\) by one position to the right, and write down the initial value of \(a_i\) to position \(j\). In this case we'll say that we performed an insertion of an element from position \(i\) to position \(j\).It can be noticed that after processing any \(i\), the prefix of the sequence \([a_1, a_2, \ldots, a_i]\) is sorted in non-decreasing order, therefore, the algorithm indeed sorts any sequence.For example, sorting \([4, 5, 3, 1, 3]\) proceeds as follows: \(i = 2\): \(a_2 \ge a_1\), do nothing; \(i = 3\): \(j = 1\), insert from position \(3\) to position \(1\): \([3, 4, 5, 1, 3]\); \(i = 4\): \(j = 1\), insert from position \(4\) to position \(1\): \([1, 3, 4, 5, 3]\); \(i = 5\): \(j = 3\), insert from position \(5\) to position \(3\): \([1, 3, 3, 4, 5]\). You are given an integer \(n\) and a list of \(m\) integer pairs \((x_i, y_i)\). We are interested in sequences such that if you sort them using the above algorithm, exactly \(m\) insertions will be performed: first from position \(x_1\) to position \(y_1\), then from position \(x_2\) to position \(y_2\), ..., finally, from position \(x_m\) to position \(y_m\).How many sequences of length \(n\) consisting of (not necessarily distinct) integers between \(1\) and \(n\), inclusive, satisfy the above condition? Print this number modulo \(998\,244\,353\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^5\)). Description of the test cases follows.The first line of each test case contains two integers \(n\) and \(m\) (\(2 \le n \le 2 \cdot 10^5\); \(0 \le m < n\)) β€” the length of the sequence and the number of insertions.The \(i\)-th of the following \(m\) lines contains two integers \(x_i\) and \(y_i\) (\(2 \le x_1 < x_2 < \ldots < x_m \le n\); \(1 \le y_i < x_i\)). These lines describe the sequence of insertions in chronological order.It is guaranteed that the sum of \(m\) over all test cases does not exceed \(2 \cdot 10^5\). Note that there is no constraint on the sum of \(n\) of the same kind.
For each test case, print the number of sequences of length \(n\) consisting of integers from \(1\) to \(n\) such that sorting them with the described algorithm produces the given sequence of insertions, modulo \(998\,244\,353\).
In the first test case, the algorithm performs no insertions β€” therefore, the initial sequence is already sorted in non-decreasing order. There are \(10\) such sequences: \([1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3], [1, 3, 3], [2, 2, 2], [2, 2, 3], [2, 3, 3], [3, 3, 3]\).In the second test case, the only sequence satisfying the conditions is \([3, 2, 1]\).In the third test case, \([4, 5, 3, 1, 3]\) is one of the sought sequences.
Input: 3 3 0 3 2 2 1 3 1 5 3 3 1 4 1 5 3 | Output: 10 1 21
Expert
2
1,707
717
229
15
765
C
765C
C. Table Tennis Game 2
1,200
math
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins.Across all the sets Misha scored a points in total, and Vanya scored b points. Given this information, determine the maximum number of sets they could have played, or that the situation is impossible.Note that the game consisted of several complete sets.
The first line contains three space-separated integers k, a and b (1 ≀ k ≀ 109, 0 ≀ a, b ≀ 109, a + b > 0).
If the situation is impossible, print a single number -1. Otherwise, print the maximum possible number of sets.
Note that the rules of the game in this problem differ from the real table tennis game, for example, the rule of ""balance"" (the winning player has to be at least two points ahead to win a set) has no power within the present problem.
Input: 11 11 5 | Output: 1
Easy
1
530
107
111
7
746
D
746D
D. Green and Black Tea
1,500
constructive algorithms; greedy; math
Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black.Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink n cups of tea, without drinking the same tea more than k times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once.
The first line contains four integers n, k, a and b (1 ≀ k ≀ n ≀ 105, 0 ≀ a, b ≀ n) β€” the number of cups of tea Innokentiy wants to drink, the maximum number of cups of same tea he can drink in a row, the number of tea bags of green and black tea. It is guaranteed that a + b = n.
If it is impossible to drink n cups of tea, print ""NO"" (without quotes).Otherwise, print the string of the length n, which consists of characters 'G' and 'B'. If some character equals 'G', then the corresponding cup of tea should be green. If some character equals 'B', then the corresponding cup of tea should be black.If there are multiple answers, print any of them.
Input: 5 1 3 2 | Output: GBGBG
Medium
3
519
280
371
7
1,375
D
1375D
D. Replace by MEX
1,900
brute force; constructive algorithms; sortings
You're given an array of \(n\) integers between \(0\) and \(n\) inclusive.In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation).For example, if the current array is \([0, 2, 2, 1, 4]\), you can choose the second element and replace it by the MEX of the present elements β€” \(3\). Array will become \([0, 3, 2, 1, 4]\).You must make the array non-decreasing, using at most \(2n\) operations.It can be proven that it is always possible. Please note that you do not have to minimize the number of operations. If there are many solutions, you can print any of them. –An array \(b[1 \ldots n]\) is non-decreasing if and only if \(b_1 \le b_2 \le \ldots \le b_n\).The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance: The MEX of \([2, 2, 1]\) is \(0\), because \(0\) does not belong to the array. The MEX of \([3, 1, 0, 1]\) is \(2\), because \(0\) and \(1\) belong to the array, but \(2\) does not. The MEX of \([0, 3, 1, 2]\) is \(4\) because \(0\), \(1\), \(2\) and \(3\) belong to the array, but \(4\) does not. It's worth mentioning that the MEX of an array of length \(n\) is always between \(0\) and \(n\) inclusive.
The first line contains a single integer \(t\) (\(1 \le t \le 200\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(3 \le n \le 1000\)) β€” length of the array.The second line of each test case contains \(n\) integers \(a_1, \ldots, a_n\) (\(0 \le a_i \le n\)) β€” elements of the array. Note that they don't have to be distinct.It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(1000\).
For each test case, you must output two lines:The first line must contain a single integer \(k\) (\(0 \le k \le 2n\)) β€” the number of operations you perform.The second line must contain \(k\) integers \(x_1, \ldots, x_k\) (\(1 \le x_i \le n\)), where \(x_i\) is the index chosen for the \(i\)-th operation.If there are many solutions, you can find any of them. Please remember that it is not required to minimize \(k\).
In the first test case, the array is already non-decreasing (\(2 \le 2 \le 3\)).Explanation of the second test case (the element modified by each operation is colored in red): \(a = [2, 1, 0]\) ; the initial MEX is \(3\). \(a = [2, 1, \color{red}{3}]\) ; the new MEX is \(0\). \(a = [\color{red}{0}, 1, 3]\) ; the new MEX is \(2\). The final array is non-decreasing: \(0 \le 1 \le 3\). Explanation of the third test case: \(a = [0, 7, 3, 1, 3, 7, 7]\) ; the initial MEX is \(2\). \(a = [0, \color{red}{2}, 3, 1, 3, 7, 7]\) ; the new MEX is \(4\). \(a = [0, 2, 3, 1, \color{red}{4}, 7, 7]\) ; the new MEX is \(5\). \(a = [0, 2, 3, 1, \color{red}{5}, 7, 7]\) ; the new MEX is \(4\). \(a = [0, 2, 3, \color{red}{4}, 5, 7, 7]\) ; the new MEX is \(1\). The final array is non-decreasing: \(0 \le 2 \le 3 \le 4 \le 5 \le 7 \le 7\).
Input: 5 3 2 2 3 3 2 1 0 7 0 7 3 1 3 7 7 9 2 0 1 1 2 4 4 2 0 9 8 4 7 6 1 2 3 0 5 | Output: 0 2 3 1 4 2 5 5 4 11 3 8 9 7 8 5 9 6 4 1 2 10 1 8 1 9 5 2 4 6 3 7
Hard
3
1,285
499
419
13
461
B
461B
B. Appleman and Tree
2,000
dfs and similar; dp; trees
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
The first line contains an integer n (2 ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1.The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
Input: 30 00 1 1 | Output: 2
Hard
3
529
537
91
4
471
E
471E
E. MUH and Lots and Lots of Segments
2,700
data structures; dsu
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to do some painting. As they were trying to create their first masterpiece, they made a draft on a piece of paper. The draft consists of n segments. Each segment was either horizontal or vertical. Now the friends want to simplify the draft by deleting some segments or parts of segments so that the final masterpiece meets three conditions: Horace wants to be able to paint the whole picture in one stroke: by putting the brush on the paper and never taking it off until the picture is ready. The brush can paint the same place multiple times. That's why all the remaining segments must form a single connected shape. Menshykov wants the resulting shape to be simple. He defines a simple shape as a shape that doesn't contain any cycles. Initially all the segment on the draft have integer startpoint and endpoint coordinates. Uslada doesn't like real coordinates and she wants this condition to be fulfilled after all the changes. As in other parts the draft is already beautiful, the friends decided to delete such parts of the draft that the sum of lengths of the remaining segments is as large as possible. Your task is to count this maximum sum of the lengths that remain after all the extra segments are removed.
The first line of the input contains integer n (1 ≀ n ≀ 2Β·105) β€” the number of segments on the draft. The next n lines contain four integers each: x1, y1, x2, y2 ( - 109 ≀ x1 ≀ x2 ≀ 109; - 109 ≀ y1 ≀ y2 ≀ 109) β€” the two startpoint and the two endpoint coordinates of a segment. All segments are non-degenerative and either are strictly horizontal or strictly vertical.No two horizontal segments share common points. No two vertical segments share common points.
Print a single integer β€” the maximum sum of lengths for the remaining segments.
The shapes that you can get in the two given samples are: In the first sample you need to delete any segment as the two segments together do not form a single connected shape.In the second sample the initial segments form a cycle, there are four ways to break the cycle: delete the first, second or fourth segment altogether or delete the middle of the third segment. The last way is shown on the picture.
Input: 20 0 0 11 0 1 1 | Output: 1
Master
2
1,331
461
79
4
1,180
A
1180A
A. Alex and a Rhombus
800
dp; implementation; math
While playing with geometric figures Alex has accidentally invented a concept of a \(n\)-th order rhombus in a cell grid.A \(1\)-st order rhombus is just a square \(1 \times 1\) (i.e just a cell).A \(n\)-th order rhombus for all \(n \geq 2\) one obtains from a \(n-1\)-th order rhombus adding all cells which have a common side with it to it (look at the picture to understand it better). Alex asks you to compute the number of cells in a \(n\)-th order rhombus.
The first and only input line contains integer \(n\) (\(1 \leq n \leq 100\)) β€” order of a rhombus whose numbers of cells should be computed.
Print exactly one integer β€” the number of cells in a \(n\)-th order rhombus.
Images of rhombus corresponding to the examples are given in the statement.
Input: 1 | Output: 1
Beginner
3
462
140
76
11
1,826
E
1826E
E. Walk the Runway
2,400
bitmasks; brute force; data structures; dp; graphs; implementation; sortings
A fashion tour consists of \(m\) identical runway shows in different cities. There are \(n\) models willing to participate in the tour, numbered from \(1\) to \(n\). People in different cities have different views on the fashion industry, so they rate each model differently. In particular, people in city \(i\) rate model \(j\) with rating \(r_{i, j}\).You are to choose some number of \(k\) models, and their order, let the chosen models have indices \(j_1, j_2, \dots, j_k\) in the chosen order. In each city, these \(k\) models will walk the runway one after another in this order. To make the show exciting, in each city, the ratings of models should be strictly increasing in the order of their performance. More formally, for any city \(i\) and index \(t\) (\(2 \leq t \leq k\)), the ratings must satisfy \(r_{i,j_{t - 1}} < r_{i,j_t}\). After all, the fashion industry is all about money, so choosing model \(j\) to participate in the tour profits you \(p_j\) money. Compute the maximum total profit you can make by choosing the models and their order while satisfying all the requirements.
The first line contains two integers \(m\) and \(n\) (\(1 \leq m \leq 500\), \(1 \leq n \leq 5000\)) β€” the number of shows and the number of models willing to participate respectively.The second line contains \(n\) integers \(p_j\) (\(1 \leq p_j \leq 10^9\)) β€” the profit you get inviting the \(j\)-th model to the tour.The next \(m\) lines each contain \(n\) integers. Line number \(i\) contains \(n\) integers \(r_{i, j}\) (\(1 \leq r_{i, j} \leq n\)) β€” the ratings of models in city \(i\).
Output a single integer β€” the largest total amount of money you can get.
In the first example, there are \(3\) invited models. The show consists of models in the order \([1, 3, 4]\).Then, the corresponding ratings in the cities are as follows: City \(1\) β€” \([ 1, 3, 4 ]\). City \(2\) β€” \([ 1, 2, 3 ]\). City \(3\) β€” \([ 2, 4, 5 ]\). You can see that the ratings are increasing. So the total profit is \(10 + 10 + 10 = 30\). It can be proven that we can't achieve a bigger profit.In the second example, we can invite the fifth model to the tour, which would result in a total profit of \(50\). It can be proven that we can't achieve a bigger profit.In the third example, we invite the single model to the tour, which results in a total profit of \(1\,000\,000\,000\).In the fourth test case, we can invite all the models and make the show in the order \([ 5, 4, 3, 2, 1 ]\). The total profit is \(5 \cdot 1\,000\,000\,000 = 5\,000\,000\,000\).
Input: 3 5 10 10 10 10 10 1 2 3 4 5 1 5 2 3 4 2 3 4 5 1 | Output: 30
Expert
7
1,098
492
72
18
83
E
83E
E. Two Subsequences
2,800
bitmasks; dp
On an IT lesson Valera studied data compression. The teacher told about a new method, which we shall now describe to you.Let {a1, a2, ..., an} be the given sequence of lines needed to be compressed. Here and below we shall assume that all lines are of the same length and consist only of the digits 0 and 1. Let's define the compression function: f(empty sequence) = empty string f(s) = s. f(s1, s2) = the smallest in length string, which has one of the prefixes equal to s1 and one of the suffixes equal to s2. For example, f(001, 011) = 0011, f(111, 011) = 111011. f(a1, a2, ..., an) = f(f(a1, a2, an - 1), an). For example, f(000, 000, 111) = f(f(000, 000), 111) = f(000, 111) = 000111. Valera faces a real challenge: he should divide the given sequence {a1, a2, ..., an} into two subsequences {b1, b2, ..., bk} and {c1, c2, ..., cm}, m + k = n, so that the value of S = |f(b1, b2, ..., bk)| + |f(c1, c2, ..., cm)| took the minimum possible value. Here |p| denotes the length of the string p.Note that it is not allowed to change the relative order of lines in the subsequences. It is allowed to make one of the subsequences empty. Each string from the initial sequence should belong to exactly one subsequence. Elements of subsequences b and c don't have to be consecutive in the original sequence a, i. e. elements of b and c can alternate in a (see samples 2 and 3).Help Valera to find the minimum possible value of S.
The first line of input data contains an integer n β€” the number of strings (1 ≀ n ≀ 2Β·105). Then on n lines follow elements of the sequence β€” strings whose lengths are from 1 to 20 characters, consisting only of digits 0 and 1. The i + 1-th input line contains the i-th element of the sequence. Elements of the sequence are separated only by a newline. It is guaranteed that all lines have the same length.
Print a single number β€” the minimum possible value of S.
Detailed answers to the tests: The best option is to make one of the subsequences empty, and the second one equal to the whole given sequence. |f(01, 10, 01)| = |f(f(01, 10), 01)| = |f(010, 01)| = |0101| = 4. The best option is: b = {000, 001}, c = {111, 110}. S = |f(000, 001)| + |f(111, 110)| = |0001| + |1110| = 8. The best option is: b = {10101, 01010, 01000}, c = {11111, 10010}. S = |10101000| + |111110010| = 17.
Input: 3011001 | Output: 4
Master
2
1,424
406
56
0
1,020
B
1020B
B. Badge
1,000
brute force; dfs and similar; graphs
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of \(n\) students doing yet another trick. Let's assume that all these students are numbered from \(1\) to \(n\). The teacher came to student \(a\) and put a hole in his badge. The student, however, claimed that the main culprit is some other student \(p_a\).After that, the teacher came to student \(p_a\) and made a hole in his badge as well. The student in reply said that the main culprit was student \(p_{p_a}\).This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers \(p_i\). Your task is to find out for every student \(a\), who would be the student with two holes in the badge if the first caught student was \(a\).
The first line of the input contains the only integer \(n\) (\(1 \le n \le 1000\)) β€” the number of the naughty students.The second line contains \(n\) integers \(p_1\), ..., \(p_n\) (\(1 \le p_i \le n\)), where \(p_i\) indicates the student who was reported to the teacher by student \(i\).
For every student \(a\) from \(1\) to \(n\) print which student would receive two holes in the badge, if \(a\) was the first student caught by the teacher.
The picture corresponds to the first example test case. When \(a = 1\), the teacher comes to students \(1\), \(2\), \(3\), \(2\), in this order, and the student \(2\) is the one who receives a second hole in his badge.When \(a = 2\), the teacher comes to students \(2\), \(3\), \(2\), and the student \(2\) gets a second hole in his badge. When \(a = 3\), the teacher will visit students \(3\), \(2\), \(3\) with student \(3\) getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Input: 32 3 2 | Output: 2 2 3
Beginner
3
1,103
290
155
10
44
J
44J
J. Triminoes
2,000
constructive algorithms; greedy
There are many interesting tasks on domino tilings. For example, an interesting fact is known. Let us take a standard chessboard (8 Γ— 8) and cut exactly two squares out of it. It turns out that the resulting board can always be tiled using dominoes 1 Γ— 2, if the two cut out squares are of the same color, otherwise it is impossible. Petya grew bored with dominoes, that's why he took a chessboard (not necessarily 8 Γ— 8), cut some squares out of it and tries to tile it using triminoes. Triminoes are reactangles 1 Γ— 3 (or 3 Γ— 1, because triminoes can be rotated freely), also the two extreme squares of a trimino are necessarily white and the square in the middle is black. The triminoes are allowed to put on the chessboard so that their squares matched the colors of the uncut squares of the chessboard, and also the colors must match: the black squares must be matched with the black ones only and the white ones β€” with the white squares. The triminoes must not protrude above the chessboard or overlap each other. All the uncut squares of the board must be covered with triminoes. Help Petya find out if it is possible to tile his board using triminos in the described way and print one of the variants of tiling.
The first line contains two integers n and m (1 ≀ n, m ≀ 1000) β€” the board size. Next n lines contain m symbols each and represent the board description. If some position contains ""."", then the square in this position has been cut out. Symbol ""w"" stands for a white square, ""b"" stands for a black square. It is guaranteed that through adding the cut squares can result in a correct chessboard (i.e. with alternating black and white squares), thought, perhaps, of a non-standard size.
If at least one correct tiling exists, in the first line print ""YES"" (without quotes), and then β€” the tiling description. The description must contain n lines, m symbols in each. The cut out squares, as well as in the input data, are marked by ""."". To denote triminoes symbols ""a"", ""b"", ""c"", ""d"" can be used, and all the three squares of each trimino must be denoted by the same symbol. If two triminoes share a side, than they must be denoted by different symbols. Two triminoes not sharing a common side can be denoted by one and the same symbol (c.f. sample).If there are multiple correct ways of tiling, it is allowed to print any. If it is impossible to tile the board using triminoes or the correct tiling, for which four symbols ""a"", ""b"", ""c"", ""d"" would be enough, doesn't exist, print ""NO"" (without quotes) in the first line.
Input: 6 10.w.wbw.wbwwbwbw.w.w.bw.wbwbwbww.wbw.wbwb...wbw.w.w..wbw.wbw. | Output: YES.a.aaa.cccbaccc.c.a.ba.dddcbabb.aaa.cbab...bbb.b.b..ccc.ddd.
Hard
2
1,219
489
855
0
188
C
188C
C. LCM
1,400
*special; implementation; math
Least common multiple (LCM) of two numbers is the smallest positive integer which is divisible by both of them. You are given integers a and b. Calculate their LCM.
The input contains two integers a and b (1 ≀ a, b ≀ 103), separated by a single space.
Output LCM(a, b).
Input: 10 42 | Output: 210
Easy
3
164
86
17
1
331
E1
331E1
E1. Deja Vu
2,900
constructive algorithms; graphs; implementation
Everybody knows that we have been living in the Matrix for a long time. And in the new seventh Matrix the world is ruled by beavers.So let's take beaver Neo. Neo has so-called ""deja vu"" outbursts when he gets visions of events in some places he's been at or is going to be at. Let's examine the phenomenon in more detail.We can say that Neo's city is represented by a directed graph, consisting of n shops and m streets that connect the shops. No two streets connect the same pair of shops (besides, there can't be one street from A to B and one street from B to A). No street connects a shop with itself. As Neo passes some streets, he gets visions. No matter how many times he passes street k, every time he will get the same visions in the same order. A vision is a sequence of shops.We know that Neo is going to get really shocked if he passes the way from some shop a to some shop b, possible coinciding with a, such that the list of visited shops in the real life and in the visions coincide.Suggest beaver Neo such path of non-zero length. Or maybe you can even count the number of such paths modulo 1000000007 (109 + 7)?..
The first line contains integers n and m β€” the number of shops and the number of streets, correspondingly, 1 ≀ n ≀ 50, . Next m lines contain the descriptions of the streets in the following format: xi yi ki v1 v2 ... vk, where xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi) are indices of shops connected by a street, ki (0 ≀ ki ≀ n) is the number of visions on the way from xi to yi; v1, v2, ..., vk (1 ≀ vi ≀ n) describe the visions: the numbers of the shops Neo saw. Note that the order of the visions matters.It is guaranteed that the total number of visions on all streets doesn't exceed 105. to get 50 points, you need to find any (not necessarily simple) path of length at most 2Β·n, that meets the attributes described above (subproblem E1); to get 50 more points, you need to count for each length from 1 to 2Β·n the number of paths that have the attribute described above (subproblem E2).
Subproblem E1. In the first line print an integer k (1 ≀ k ≀ 2Β·n) β€” the numbers of shops on Neo's path. In the next line print k integers β€” the number of shops in the order Neo passes them. If the graph doesn't have such paths or the length of the shortest path includes more than 2Β·n shops, print on a single line 0.Subproblem E2. Print 2Β·n lines. The i-th line must contain a single integer β€” the number of required paths of length i modulo 1000000007 (109 + 7).
The input in both samples are the same. The first sample contains the answer to the first subproblem, the second sample contains the answer to the second subproblem.
Input: 6 61 2 2 1 22 3 1 33 4 2 4 54 5 05 3 1 36 1 1 6 | Output: 46 1 2 3
Master
3
1,132
886
464
3
1,970
D3
1970D3
D3. Arithmancy (Hard)
3,100
interactive
The only difference between the versions of this problem is the maximum value of \(n\).Professor Vector is preparing to teach her Arithmancy class. She needs to prepare \(n\) distinct magic words for the class. Each magic word is a string consisting of characters X and O. A spell is a string created by concatenating two magic words together. The power of a spell is equal to the number of its different non-empty substrings. For example, the power of the spell XOXO is equal to 7, because it has 7 different substrings: X, O, XO, OX, XOX, OXO and XOXO.Each student will create their own spell by concatenating two magic words. Since the students are not very good at magic yet, they will choose each of the two words independently and uniformly at random from the \(n\) words provided by Professor Vector. It is therefore also possible that the two words a student chooses are the same. Each student will then compute the power of their spell, and tell it to Professor Vector. In order to check their work, and of course to impress the students, Professor Vector needs to find out which two magic words and in which order were concatenated by each student.Your program needs to perform the role of Professor Vector: first, create \(n\) distinct magic words, and then handle multiple requests where it is given the spell power and needs to determine the indices of the two magic words, in the correct order, that were used to create the corresponding spell.
Input: 2 2 15 11 | Output: XOXO X 1 1 2 1
Master
1
1,458
0
0
19
1,516
B
1516B
B. AGAGA XOOORRR
1,500
bitmasks; brute force; dp; greedy
Baby Ehab is known for his love for a certain operation. He has an array \(a\) of length \(n\), and he decided to keep doing the following operation on it: he picks \(2\) adjacent elements; he then removes them and places a single integer in their place: their bitwise XOR. Note that the length of the array decreases by one. Now he asks you if he can make all elements of the array equal. Since babies like to make your life harder, he requires that you leave at least \(2\) elements remaining.
The first line contains an integer \(t\) (\(1 \le t \le 15\)) β€” the number of test cases you need to solve.The first line of each test case contains an integers \(n\) (\(2 \le n \le 2000\)) β€” the number of elements in the array \(a\).The second line contains \(n\) space-separated integers \(a_1\), \(a_2\), \(\ldots\), \(a_{n}\) (\(0 \le a_i < 2^{30}\)) β€” the elements of the array \(a\).
If Baby Ehab can make all elements equal while leaving at least \(2\) elements standing, print ""YES"". Otherwise, print ""NO"".
In the first sample, he can remove the first \(2\) elements, \(0\) and \(2\), and replace them by \(0 \oplus 2=2\). The array will be \([2,2]\), so all the elements are equal.In the second sample, there's no way to make all the elements equal.
Input: 2 3 0 2 2 4 2 3 1 10 | Output: YES NO
Medium
4
495
389
128
15
1,707
B
1707B
B. Difference Array
1,900
brute force; data structures; implementation; sortings
You are given an array \(a\) consisting of \(n\) non-negative integers. It is guaranteed that \(a\) is sorted from small to large.For each operation, we generate a new array \(b_i=a_{i+1}-a_{i}\) for \(1 \le i < n\). Then we sort \(b\) from small to large, replace \(a\) with \(b\), and decrease \(n\) by \(1\).After performing \(n-1\) operations, \(n\) becomes \(1\). You need to output the only integer in array \(a\) (that is to say, you need to output \(a_1\)).
The input consists of multiple test cases. The first line contains a single integer \(t\) (\(1\le t\le 10^4\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains one integer \(n\) (\(2\le n\le 10^5\)) β€” the length of the array \(a\).The second line contains \(n\) integers \(a_1,a_2,\dots,a_n\) (\(0\le a_1\le \ldots\le a_n \le 5\cdot 10^5\)) β€” the array \(a\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2.5\cdot 10^5\), and the sum of \(a_n\) over all test cases does not exceed \(5\cdot 10^5\).
For each test case, output the answer on a new line.
To simplify the notes, let \(\operatorname{sort}(a)\) denote the array you get by sorting \(a\) from small to large.In the first test case, \(a=[1,10,100]\) at first. After the first operation, \(a=\operatorname{sort}([10-1,100-10])=[9,90]\). After the second operation, \(a=\operatorname{sort}([90-9])=[81]\).In the second test case, \(a=[4,8,9,13]\) at first. After the first operation, \(a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]\). After the second operation, \(a=\operatorname{sort}([4-1,4-4])=[0,3]\). After the last operation, \(a=\operatorname{sort}([3-0])=[3]\).
Input: 531 10 10044 8 9 1350 0 0 8 1362 4 8 16 32 6470 0 0 0 0 0 0 | Output: 81 3 1 2 0
Hard
4
465
591
52
17
1,332
D
1332D
D. Walk on Matrix
1,700
bitmasks; constructive algorithms; math
Bob is playing a game named ""Walk on Matrix"".In this game, player is given an \(n \times m\) matrix \(A=(a_{i,j})\), i.e. the element in the \(i\)-th row in the \(j\)-th column is \(a_{i,j}\). Initially, player is located at position \((1,1)\) with score \(a_{1,1}\). To reach the goal, position \((n,m)\), player can move right or down, i.e. move from \((x,y)\) to \((x,y+1)\) or \((x+1,y)\), as long as player is still on the matrix.However, each move changes player's score to the bitwise AND of the current score and the value at the position he moves to.Bob can't wait to find out the maximum score he can get using the tool he recently learnt β€” dynamic programming. Here is his algorithm for this problem. However, he suddenly realize that the algorithm above fails to output the maximum score for some matrix \(A\). Thus, for any given non-negative integer \(k\), he wants to find out an \(n \times m\) matrix \(A=(a_{i,j})\) such that \(1 \le n,m \le 500\) (as Bob hates large matrix); \(0 \le a_{i,j} \le 3 \cdot 10^5\) for all \(1 \le i\le n,1 \le j\le m\) (as Bob hates large numbers); the difference between the maximum score he can get and the output of his algorithm is exactly \(k\). It can be shown that for any given integer \(k\) such that \(0 \le k \le 10^5\), there exists a matrix satisfying the above constraints.Please help him with it!
The only line of the input contains one single integer \(k\) (\(0 \le k \le 10^5\)).
Output two integers \(n\), \(m\) (\(1 \le n,m \le 500\)) in the first line, representing the size of the matrix. Then output \(n\) lines with \(m\) integers in each line, \(a_{i,j}\) in the \((i+1)\)-th row, \(j\)-th column.
In the first example, the maximum score Bob can achieve is \(300000\), while the output of his algorithm is \(300000\).In the second example, the maximum score Bob can achieve is \(7\&3\&3\&3\&7\&3=3\), while the output of his algorithm is \(2\).
Input: 0 | Output: 1 1 300000
Medium
3
1,361
84
224
13
1,539
F
1539F
F. Strange Array
2,600
data structures; greedy; sortings
Vasya has an array of \(n\) integers \(a_1, a_2, \ldots, a_n\). Vasya thinks that all numbers in his array are strange for some reason. To calculate how strange the \(i\)-th number is, Vasya created the following algorithm.He chooses a subsegment \(a_l, a_{l+1}, \ldots, a_r\), such that \(1 \le l \le i \le r \le n\), sort its elements in increasing order in his head (he can arrange equal elements arbitrary). After that he finds the center of the segment. The center of a segment is the element at position \((l + r) / 2\), if the length of the segment is odd, and at position \((l + r + 1) / 2\) otherwise. Now Vasya finds the element that was at position \(i\) before the sorting, and calculates the distance between its current position and the center of the subsegment (the distance between the elements with indices \(j\) and \(k\) is \(|j - k|\)).The strangeness of the number at position \(i\) is the maximum distance among all suitable choices of \(l\) and \(r\). Vasya wants to calculate the strangeness of each number in his array. Help him to do it.
The first line contains a single integer \(n\) (\(1 \le n \le 200\,000\)) β€” the size of the array.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le n\)) β€” Vasya's array.
Print a single line with \(n\) numbers. The \(i\)-th of them must be equal to the strangeness of the \(i\)-th element of the array.
In the first example: For the first position we choose the segment from \(1\) to \(5\). After sorting, it looks like \([1, 2, 3, 4, 5]\), the center is \(3\). The distance from the center to \(5\) is \(2\). For the second position we choose the segment from \(2\) to \(4\). For the third position we choose the segment from \(3\) to \(5\). For the fourth position we choose the segment from \(1\) to \(4\). After sorting, it looks like \([2, 3, 4, 5]\), the center is \(4\). The distance from the center to \(2\) is \(2\). For the fifth position we choose the segment from \(1\) to \(5\).
Input: 5 5 4 3 2 1 | Output: 2 1 1 2 2
Expert
3
1,063
202
131
15
1,594
F
1594F
F. Ideal Farm
2,400
constructive algorithms; math
Theofanis decided to visit his uncle's farm. There are \(s\) animals and \(n\) animal pens on the farm. For utility purpose, animal pens are constructed in one row.Uncle told Theofanis that a farm is lucky if you can distribute all animals in all pens in such a way that there are no empty pens and there is at least one continuous segment of pens that has exactly \(k\) animals in total.Moreover, a farm is ideal if it's lucky for any distribution without empty pens.Neither Theofanis nor his uncle knows if their farm is ideal or not. Can you help them to figure it out?
The first line contains a single integer \(t\) (\(1 \le t \le 10^5\)) β€” the number of test cases.The first and only line of each test case contains three integers \(s\), \(n\), and \(k\) (\(1 \le s, n, k \le 10^{18}\); \(n \le s\)).
For each test case, print YES (case-insensitive), if the farm is ideal, or NO (case-insensitive) otherwise.
For the first and the second test case, the only possible combination is \([1]\) so there always will be a subsegment with \(1\) animal but not with \(2\) animals.
Input: 4 1 1 1 1 1 2 100 50 200 56220 47258 14497 | Output: YES NO NO YES
Expert
2
572
232
107
15
827
A
827A
A. String Reconstruction
1,700
data structures; greedy; sortings; strings
Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more, he also remembers exactly ki positions where the string ti occurs in string s: these positions are xi, 1, xi, 2, ..., xi, ki. He remembers n such strings ti.You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings ti and string s consist of small English letters only.
The first line contains single integer n (1 ≀ n ≀ 105) β€” the number of strings Ivan remembers.The next n lines contain information about the strings. The i-th of these lines contains non-empty string ti, then positive integer ki, which equal to the number of times the string ti occurs in string s, and then ki distinct positive integers xi, 1, xi, 2, ..., xi, ki in increasing order β€” positions, in which occurrences of the string ti in the string s start. It is guaranteed that the sum of lengths of strings ti doesn't exceed 106, 1 ≀ xi, j ≀ 106, 1 ≀ ki ≀ 106, and the sum of all ki doesn't exceed 106. The strings ti can coincide.It is guaranteed that the input data is not self-contradictory, and thus at least one answer always exists.
Print lexicographically minimal string that fits all the information Ivan remembers.
Input: 3a 4 1 3 5 7ab 2 1 5ca 1 4 | Output: abacaba
Medium
4
651
741
84
8
2,038
B
2038B
B. Make It Equal
2,100
binary search; brute force; greedy; math
You are given an integer array \(a\) of size \(n\). The elements of the array are numbered from \(1\) to \(n\).You can perform the following operation any number of times (possibly, zero): choose an index \(i\) from \(1\) to \(n\); decrease \(a_i\) by \(2\) and increase \(a_{(i \bmod n) + 1}\) by \(1\).After you perform the operations, all elements of the array should be non-negative equal integers.Your task is to calculate the minimum number of operations you have to perform.
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The first line of each test case contains a single integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)).The second line of each test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\)).Additional constraint on the input: the sum of \(n\) over all test cases doesn't exceed \(2 \cdot 10^5\).
For each test case, print a single integer β€” the minimum number of operations you have to perform. If it is impossible to make all elements of the array equal, print -1.
Input: 321 131 3 242 1 2 6 | Output: 0 -1 3
Hard
4
481
406
169
20
1,368
A
1368A
A. C+=
800
brute force; greedy; implementation; math
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a ""+="" operation that adds the right-hand side value to the left-hand side variable. For example, performing ""a += b"" when a = \(2\), b = \(3\) changes the value of a to \(5\) (the value of b does not change).In a prototype program Leo has two integer variables a and b, initialized with some positive values. He can perform any number of operations ""a += b"" or ""b += a"". Leo wants to test handling large integers, so he wants to make the value of either a or b strictly greater than a given value \(n\). What is the smallest number of operations he has to perform?
The first line contains a single integer \(T\) (\(1 \leq T \leq 100\)) β€” the number of test cases.Each of the following \(T\) lines describes a single test case, and contains three integers \(a, b, n\) (\(1 \leq a, b \leq n \leq 10^9\)) β€” initial values of a and b, and the value one of the variables has to exceed, respectively.
For each test case print a single integer β€” the smallest number of operations needed. Separate answers with line breaks.
In the first case we cannot make a variable exceed \(3\) in one operation. One way of achieving this in two operations is to perform ""b += a"" twice.
Input: 2 1 2 3 5 4 100 | Output: 2 7
Beginner
4
674
329
120
13
1,509
B
1509B
B. TMT Document
1,100
greedy
The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it.However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to figure out whether the document has malfunctioned. Specifically, he is given a string of length \(n\) whose characters are all either T or M, and he wants to figure out if it is possible to partition it into some number of disjoint subsequences, all of which are equal to TMT. That is, each character of the string should belong to exactly one of the subsequences.A string \(a\) is a subsequence of a string \(b\) if \(a\) can be obtained from \(b\) by deletion of several (possibly, zero) characters.
The first line contains an integer \(t\) (\(1 \le t \le 5000\)) β€” the number of test cases.The first line of each test case contains an integer \(n\) (\(3 \le n < 10^5\)), the number of characters in the string entered in the document. It is guaranteed that \(n\) is divisible by \(3\).The second line of each test case contains a string of length \(n\) consisting of only the characters T and M.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case, print a single line containing YES if the described partition exists, and a single line containing NO otherwise.
In the first test case, the string itself is already a sequence equal to TMT.In the third test case, we may partition the string into the subsequences TMTMTT. Both the bolded and the non-bolded subsequences are equal to TMT.
Input: 5 3 TMT 3 MTT 6 TMTMTT 6 TMTTTT 6 TTMMTT | Output: YES NO YES NO YES
Easy
1
816
480
132
15
1,398
G
1398G
G. Running Competition
2,600
bitmasks; fft; math; number theory
A running competition is going to be held soon. The stadium where the competition will be held can be represented by several segments on the coordinate plane: two horizontal segments: one connecting the points \((0, 0)\) and \((x, 0)\), the other connecting the points \((0, y)\) and \((x, y)\); \(n + 1\) vertical segments, numbered from \(0\) to \(n\). The \(i\)-th segment connects the points \((a_i, 0)\) and \((a_i, y)\); \(0 = a_0 < a_1 < a_2 < \dots < a_{n - 1} < a_n = x\). For example, here is a picture of the stadium with \(x = 10\), \(y = 5\), \(n = 3\) and \(a = [0, 3, 5, 10]\): A lap is a route that goes along the segments, starts and finishes at the same point, and never intersects itself (the only two points of a lap that coincide are its starting point and ending point). The length of a lap is a total distance travelled around it. For example, the red route in the picture representing the stadium is a lap of length \(24\).The competition will be held in \(q\) stages. The \(i\)-th stage has length \(l_i\), and the organizers want to choose a lap for each stage such that the length of the lap is a divisor of \(l_i\). The organizers don't want to choose short laps for the stages, so for each stage, they want to find the maximum possible length of a suitable lap.Help the organizers to calculate the maximum possible lengths of the laps for the stages! In other words, for every \(l_i\), find the maximum possible integer \(L\) such that \(l_i \bmod L = 0\), and there exists a lap of length exactly \(L\).If it is impossible to choose such a lap then print \(-1\).
The first line contains three integers \(n\), \(x\) and \(y\) (\(1 \le n, x, y \le 2 \cdot 10^5\), \(n \le x\)).The second line contains \(n + 1\) integers \(a_0\), \(a_1\), ..., \(a_n\) (\(0 = a_0 < a_1 < a_2 < \dots < a_{n - 1} < a_n = x\)).The third line contains one integer \(q\) (\(1 \le q \le 2 \cdot 10^5\)) β€” the number of stages.The fourth line contains \(q\) even integers \(l_1\), \(l_2\), ..., \(l_q\) (\(4 \le l_i \le 10^6\)) β€” the lengths of the stages.
Print \(q\) numbers. The \(i\)-th number should be equal to the maximum possible length of a suitable lap for the \(i\)-th stage, or \(-1\) if it is impossible to choose a lap for that stage.
Input: 3 10 5 0 3 5 10 6 24 30 14 16 18 10 | Output: 24 30 14 16 -1 -1
Expert
4
1,592
468
191
13
528
D
528D
D. Fuzzy Search
2,500
bitmasks; brute force; fft
Leonid works for a small and promising start-up that works on decoding the human genome. His duties include solving complex problems of finding certain patterns in long strings consisting of letters 'A', 'T', 'G' and 'C'.Let's consider the following scenario. There is a fragment of a human DNA chain, recorded as a string S. To analyze the fragment, you need to find all occurrences of string T in a string S. However, the matter is complicated by the fact that the original chain fragment could contain minor mutations, which, however, complicate the task of finding a fragment. Leonid proposed the following approach to solve this problem.Let's write down integer k β‰₯ 0 β€” the error threshold. We will say that string T occurs in string S on position i (1 ≀ i ≀ |S| - |T| + 1), if after putting string T along with this position, each character of string T corresponds to the some character of the same value in string S at the distance of at most k. More formally, for any j (1 ≀ j ≀ |T|) there must exist such p (1 ≀ p ≀ |S|), that |(i + j - 1) - p| ≀ k and S[p] = T[j].For example, corresponding to the given definition, string ""ACAT"" occurs in string ""AGCAATTCAT"" in positions 2, 3 and 6. Note that at k = 0 the given definition transforms to a simple definition of the occurrence of a string in a string.Help Leonid by calculating in how many positions the given string T occurs in the given string S with the given error threshold.
The first line contains three integers |S|, |T|, k (1 ≀ |T| ≀ |S| ≀ 200 000, 0 ≀ k ≀ 200 000) β€” the lengths of strings S and T and the error threshold.The second line contains string S.The third line contains string T.Both strings consist only of uppercase letters 'A', 'T', 'G' and 'C'.
Print a single number β€” the number of occurrences of T in S with the error threshold k by the given definition.
If you happen to know about the structure of the human genome a little more than the author of the problem, and you are not impressed with Leonid's original approach, do not take everything described above seriously.
Input: 10 4 1AGCAATTCATACAT | Output: 3
Expert
3
1,443
287
111
5
21
A
21A
A. Jabber ID
1,900
implementation; strings
Jabber ID on the national Berland service Β«BabberΒ» has a form <username>@<hostname>[/resource], where <username> β€” is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters Β«_Β», the length of <username> is between 1 and 16, inclusive. <hostname> β€” is a sequence of word separated by periods (characters Β«.Β»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive. <resource> β€” is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters Β«_Β», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional β€” it can be present or can be absent.There are the samples of correct Jabber IDs: [email protected], [email protected]/contest.Your task is to write program which checks if given string is a correct Jabber ID.
The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive.
Print YES or NO.
Input: [email protected] | Output: YES
Hard
2
942
163
16
0
903
F
903F
F. Clear The Matrix
2,200
bitmasks; dp
You are given a matrix f with 4 rows and n columns. Each element of the matrix is either an asterisk (*) or a dot (.).You may perform the following operation arbitrary number of times: choose a square submatrix of f with size k Γ— k (where 1 ≀ k ≀ 4) and replace each element of the chosen submatrix with a dot. Choosing a submatrix of size k Γ— k costs ak coins.What is the minimum number of coins you have to pay to replace all asterisks with dots?
The first line contains one integer n (4 ≀ n ≀ 1000) β€” the number of columns in f.The second line contains 4 integers a1, a2, a3, a4 (1 ≀ ai ≀ 1000) β€” the cost to replace the square submatrix of size 1 Γ— 1, 2 Γ— 2, 3 Γ— 3 or 4 Γ— 4, respectively.Then four lines follow, each containing n characters and denoting a row of matrix f. Each character is either a dot or an asterisk.
Print one integer β€” the minimum number of coins to replace all asterisks with dots.
In the first example you can spend 8 coins to replace the submatrix 3 Γ— 3 in the top-left corner, and 1 coin to replace the 1 Γ— 1 submatrix in the bottom-right corner.In the second example the best option is to replace the 4 Γ— 4 submatrix containing columns 2 – 5, and the 2 Γ— 2 submatrix consisting of rows 2 – 3 and columns 6 – 7.In the third example you can select submatrix 3 Γ— 3 in the top-left corner and then submatrix 3 Γ— 3 consisting of rows 2 – 4 and columns 2 – 4.
Input: 41 10 8 20***.***.***....* | Output: 9
Hard
2
448
374
83
9