contest_id
int32
1
2.13k
index
stringclasses
62 values
problem_id
stringlengths
2
6
title
stringlengths
0
67
rating
int32
0
3.5k
tags
stringlengths
0
139
statement
stringlengths
0
6.96k
input_spec
stringlengths
0
2.32k
output_spec
stringlengths
0
1.52k
note
stringlengths
0
5.06k
sample_tests
stringlengths
0
1.02k
difficulty_category
stringclasses
6 values
tag_count
int8
0
11
statement_length
int32
0
6.96k
input_spec_length
int16
0
2.32k
output_spec_length
int16
0
1.52k
contest_year
int16
0
21
1,029
D
1029D
D. Concatenated Multiples
1,900
implementation; math
You are given an array \(a\), consisting of \(n\) positive integers.Let's call a concatenation of numbers \(x\) and \(y\) the number that is obtained by writing down numbers \(x\) and \(y\) one right after another without changing the order. For example, a concatenation of numbers \(12\) and \(3456\) is a number \(123456\).Count the number of ordered pairs of positions \((i, j)\) (\(i \neq j\)) in array \(a\) such that the concatenation of \(a_i\) and \(a_j\) is divisible by \(k\).
The first line contains two integers \(n\) and \(k\) (\(1 \le n \le 2 \cdot 10^5\), \(2 \le k \le 10^9\)).The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\)).
Print a single integer — the number of ordered pairs of positions \((i, j)\) (\(i \neq j\)) in array \(a\) such that the concatenation of \(a_i\) and \(a_j\) is divisible by \(k\).
In the first example pairs \((1, 2)\), \((1, 3)\), \((2, 3)\), \((3, 1)\), \((3, 4)\), \((4, 2)\), \((4, 3)\) suffice. They produce numbers \(451\), \(4510\), \(110\), \(1045\), \(1012\), \(121\), \(1210\), respectively, each of them is divisible by \(11\).In the second example all \(n(n - 1)\) pairs suffice.In the third example no pair is sufficient.
Input: 6 1145 1 10 12 11 7 | Output: 7
Hard
2
486
196
180
10
133
A
133A
A. HQ9+
900
implementation
HQ9+ is a joke programming language which has only four one-character instructions: ""H"" prints ""Hello, World!"", ""Q"" prints the source code of the program itself, ""9"" prints the lyrics of ""99 Bottles of Beer"" song, ""+"" increments the value stored in the internal accumulator.Instructions ""H"" and ""Q"" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.
The input will consist of a single line p which will give a program in HQ9+. String p will contain between 1 and 100 characters, inclusive. ASCII-code of each character of p will be between 33 (exclamation mark) and 126 (tilde), inclusive.
Output ""YES"", if executing the program will produce any output, and ""NO"" otherwise.
In the first case the program contains only one instruction — ""H"", which prints ""Hello, World!"".In the second case none of the program characters are language instructions.
Input: Hi! | Output: YES
Beginner
1
545
239
87
1
580
B
580B
B. Kefa and Company
1,500
binary search; sortings; two pointers
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, ) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Print the maximum total friendship factir that can be reached.
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.In the second sample test we can take all the friends.
Input: 4 575 50 100150 2075 1 | Output: 100
Medium
3
626
430
62
5
1,404
D
1404D
D. Game of Pairs
2,800
constructive algorithms; dfs and similar; interactive; math; number theory
This is an interactive problem.Consider a fixed positive integer \(n\). Two players, First and Second play a game as follows: First considers the \(2n\) numbers \(1, 2, \dots, 2n\), and partitions them as he wants into \(n\) disjoint pairs. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants). To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of \(2n\), then Second wins. Otherwise, First wins.You are given the integer \(n\). Your task is to decide which player you wish to play as and win the game.
In the first sample, \(n = 2\), and you decide to play as Second. The judge chooses the pairs \((1, 2)\) and \((3, 4)\), and you reply with the numbers \(1\) and \(3\). This is a valid choice since it contains exactly one number from each pair, and the sum \(1 + 3 = 4\) is divisible by \(4\).In the second sample, \(n = 2\) again, and you play as First. You choose the pairs \((2, 4)\) and \((1, 3)\). The judge fails to choose a number from each pair such that their sum is divisible by \(4\), so the answer is correct.Note that the sample tests are just for illustration of the interaction protocol, and don't necessarily correspond to the behavior of the real interactor.
Input: 2 1 1 2 2 0 | Output: Second 1 3
Master
5
648
0
0
14
1,256
C
1256C
C. Platforms Jumping
1,700
greedy
There is a river of width \(n\). The left bank of the river is cell \(0\) and the right bank is cell \(n + 1\) (more formally, the river can be represented as a sequence of \(n + 2\) cells numbered from \(0\) to \(n + 1\)). There are also \(m\) wooden platforms on a river, the \(i\)-th platform has length \(c_i\) (so the \(i\)-th platform takes \(c_i\) consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed \(n\).You are standing at \(0\) and want to reach \(n+1\) somehow. If you are standing at the position \(x\), you can jump to any position in the range \([x + 1; x + d]\). However you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if \(d=1\), you can jump only to the next position (if it belongs to the wooden platform). You can assume that cells \(0\) and \(n+1\) belong to wooden platforms.You want to know if it is possible to reach \(n+1\) from \(0\) if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms.Note that you should move platforms until you start jumping (in other words, you first move the platforms and then start jumping).For example, if \(n=7\), \(m=3\), \(d=2\) and \(c = [1, 2, 1]\), then one of the ways to reach \(8\) from \(0\) is follow: The first example: \(n=7\).
The first line of the input contains three integers \(n\), \(m\) and \(d\) (\(1 \le n, m, d \le 1000, m \le n\)) — the width of the river, the number of platforms and the maximum distance of your jump, correspondingly.The second line of the input contains \(m\) integers \(c_1, c_2, \dots, c_m\) (\(1 \le c_i \le n, \sum\limits_{i=1}^{m} c_i \le n\)), where \(c_i\) is the length of the \(i\)-th platform.
If it is impossible to reach \(n+1\) from \(0\), print NO in the first line. Otherwise, print YES in the first line and the array \(a\) of length \(n\) in the second line — the sequence of river cells (excluding cell \(0\) and cell \(n + 1\)).If the cell \(i\) does not belong to any platform, \(a_i\) should be \(0\). Otherwise, it should be equal to the index of the platform (\(1\)-indexed, platforms are numbered from \(1\) to \(m\) in order of input) to which the cell \(i\) belongs.Note that all \(a_i\) equal to \(1\) should form a contiguous subsegment of the array \(a\) of length \(c_1\), all \(a_i\) equal to \(2\) should form a contiguous subsegment of the array \(a\) of length \(c_2\), ..., all \(a_i\) equal to \(m\) should form a contiguous subsegment of the array \(a\) of length \(c_m\). The leftmost position of \(2\) in \(a\) should be greater than the rightmost position of \(1\), the leftmost position of \(3\) in \(a\) should be greater than the rightmost position of \(2\), ..., the leftmost position of \(m\) in \(a\) should be greater than the rightmost position of \(m-1\).See example outputs for better understanding.
Consider the first example: the answer is \([0, 1, 0, 2, 2, 0, 3]\). The sequence of jumps you perform is \(0 \rightarrow 2 \rightarrow 4 \rightarrow 5 \rightarrow 7 \rightarrow 8\).Consider the second example: it does not matter how to place the platform because you always can jump from \(0\) to \(11\).Consider the third example: the answer is \([0, 0, 0, 0, 1, 1, 0, 0, 0, 0]\). The sequence of jumps you perform is \(0 \rightarrow 5 \rightarrow 6 \rightarrow 11\).
Input: 7 3 2 1 2 1 | Output: YES 0 1 0 2 2 0 3
Medium
1
1,515
405
1,145
12
1,579
B
1579B
B. Shifting Sort
1,100
implementation; sortings
The new generation external memory contains an array of integers \(a[1 \ldots n] = [a_1, a_2, \ldots, a_n]\).This type of memory does not support changing the value of an arbitrary element. Instead, it allows you to cut out any segment of the given array, cyclically shift (rotate) it by any offset and insert it back into the same place.Technically, each cyclic shift consists of two consecutive actions: You may select arbitrary indices \(l\) and \(r\) (\(1 \le l < r \le n\)) as the boundaries of the segment. Then you replace the segment \(a[l \ldots r]\) with it's cyclic shift to the left by an arbitrary offset \(d\). The concept of a cyclic shift can be also explained by following relations: the sequence \([1, 4, 1, 3]\) is a cyclic shift of the sequence \([3, 1, 4, 1]\) to the left by the offset \(1\) and the sequence \([4, 1, 3, 1]\) is a cyclic shift of the sequence \([3, 1, 4, 1]\) to the left by the offset \(2\). For example, if \(a = [1, \color{blue}{3, 2, 8}, 5]\), then choosing \(l = 2\), \(r = 4\) and \(d = 2\) yields a segment \(a[2 \ldots 4] = [3, 2, 8]\). This segment is then shifted by the offset \(d = 2\) to the left, and you get a segment \([8, 3, 2]\) which then takes the place of of the original elements of the segment. In the end you get \(a = [1, \color{blue}{8, 3, 2}, 5]\).Sort the given array \(a\) using no more than \(n\) cyclic shifts of any of its segments. Note that you don't need to minimize the number of cyclic shifts. Any method that requires \(n\) or less cyclic shifts will be accepted.
The first line contains an integer \(t\) (\(1 \leq t \leq 1000\)) — the number of test cases.The next \(2t\) lines contain the descriptions of the test cases. The first line of each test case description contains an integer \(n\) (\(2 \leq n \leq 50\)) — the length of the array. The second line consists of space-separated elements of the array \(a_i\) (\(-10^9 \leq a_i \leq 10^9\)). Elements of array \(a\) may repeat and don't have to be unique.
Print \(t\) answers to all input test cases. The first line of the answer of each test case should contain an integer \(k\) (\(0 \le k \le n\)) — the number of actions to sort the array. The next \(k\) lines should contain descriptions of the actions formatted as ""\(l\) \(r\) \(d\)"" (without quotes) where \(l\) and \(r\) (\(1 \le l < r \le n\)) are the boundaries of the segment being shifted, while \(d\) (\(1 \le d \le r - l\)) is the offset value. Please remember that only the cyclic shifts to the left are considered so the chosen segment will be shifted by the offset \(d\) to the to the left.Note that you are not required to find the minimum number of cyclic shifts needed for sorting. Any sorting method where the number of shifts does not exceed \(n\) will be accepted.If the given array \(a\) is already sorted, one of the possible answers is \(k = 0\) and an empty sequence of cyclic shifts.If there are several possible answers, you may print any of them.
Explanation of the fourth data set in the example: The segment \(a[2 \ldots 4]\) is selected and is shifted to the left by \(2\): \([2, \color{blue}{5, 1, 4}, 3] \longrightarrow [2, \color{blue}{4, 5, 1}, 3]\) The segment \(a[1 \ldots 5]\) is then selected and is shifted to the left by \(3\): \([\color{blue}{2, 4, 5, 1, 3}] \longrightarrow [\color{blue}{1, 3, 2, 4, 5}]\) After that the segment \(a[1 \ldots 2]\) is selected and is shifted to the left by \(1\): \([\color{blue}{1, 3}, 2, 4, 5] \longrightarrow [\color{blue}{3, 1}, 2, 4, 5]\) And in the end the segment \(a[1 \ldots 3]\) is selected and is shifted to the left by \(1\): \([\color{blue}{3, 1, 2}, 4, 5] \longrightarrow [\color{blue}{1, 2, 3}, 4, 5]\)
Input: 4 2 2 1 3 1 2 1 4 2 4 1 3 5 2 5 1 4 3 | Output: 1 1 2 1 1 1 3 2 3 2 4 1 2 3 1 1 3 2 4 2 4 2 1 5 3 1 2 1 1 3 1
Easy
2
1,540
449
972
15
10
C
10C
C. Digital Root
2,000
number theory
Not long ago Billy came across such a problem, where there were given three natural numbers A, B and C from the range [1, N], and it was asked to check whether the equation AB = C is correct. Recently Billy studied the concept of a digital root of a number. We should remind you that a digital root d(x) of the number x is the sum s(x) of all the digits of this number, if s(x) ≤ 9, otherwise it is d(s(x)). For example, a digital root of the number 6543 is calculated as follows: d(6543) = d(6 + 5 + 4 + 3) = d(18) = 9. Billy has counted that the digital root of a product of numbers is equal to the digital root of the product of the factors' digital roots, i.e. d(xy) = d(d(x)d(y)). And the following solution to the problem came to his mind: to calculate the digital roots and check if this condition is met. However, Billy has doubts that this condition is sufficient. That's why he asks you to find out the amount of test examples for the given problem such that the algorithm proposed by Billy makes mistakes.
The first line contains the only number N (1 ≤ N ≤ 106).
Output one number — the amount of required A, B and C from the range [1, N].
For the first sample the required triples are (3, 4, 3) and (4, 3, 3).
Input: 4 | Output: 2
Hard
1
1,016
56
76
0
3
D
3D
D. Least Cost Bracket Sequence
2,600
greedy
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting ""+"" and ""1"" into it we get a correct mathematical expression. For example, sequences ""(())()"", ""()"" and ""(()(()))"" are regular, while "")("", ""(()"" and ""(()))("" are not. You have a pattern of a bracket sequence that consists of characters ""("", "")"" and ""?"". You have to replace each character ""?"" with a bracket so, that you get a regular bracket sequence.For each character ""?"" the cost of its replacement with ""("" and "")"" is given. Among all the possible variants your should choose the cheapest.
The first line contains a non-empty pattern of even length, consisting of characters ""("", "")"" and ""?"". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters ""?"" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character ""?"" with an opening bracket, and bi — with a closing one.
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second.Print -1, if there is no answer. If the answer is not unique, print any of them.
Input: (??)1 22 8 | Output: 4()()
Expert
1
636
408
194
0
983
B
983B
B. XOR-pyramid
1,800
dp
For an array \(b\) of length \(m\) we define the function \(f\) as \( f(b) = \begin{cases} b[1] & \quad \text{if } m = 1 \\ f(b[1] \oplus b[2],b[2] \oplus b[3],\dots,b[m-1] \oplus b[m]) & \quad \text{otherwise,} \end{cases} \) where \(\oplus\) is bitwise exclusive OR.For example, \(f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15\)You are given an array \(a\) and a few queries. Each query is represented as two integers \(l\) and \(r\). The answer is the maximum value of \(f\) on all continuous subsegments of the array \(a_l, a_{l+1}, \ldots, a_r\).
The first line contains a single integer \(n\) (\(1 \le n \le 5000\)) — the length of \(a\).The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(0 \le a_i \le 2^{30}-1\)) — the elements of the array.The third line contains a single integer \(q\) (\(1 \le q \le 100\,000\)) — the number of queries.Each of the next \(q\) lines contains a query represented as two integers \(l\), \(r\) (\(1 \le l \le r \le n\)).
Print \(q\) lines — the answers for the queries.
In first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment.In second sample, optimal segment for first query are \([3,6]\), for second query — \([2,5]\), for third — \([3,4]\), for fourth — \([1,2]\).
Input: 38 4 122 31 2 | Output: 512
Medium
1
608
425
48
9
628
F
628F
F. Bear and Fair Set
2,500
flows; graphs
Limak is a grizzly bear. He is big and dreadful. You were chilling in the forest when you suddenly met him. It's very unfortunate for you. He will eat all your cookies unless you can demonstrate your mathematical skills. To test you, Limak is going to give you a puzzle to solve.It's a well-known fact that Limak, as every bear, owns a set of numbers. You know some information about the set: The elements of the set are distinct positive integers. The number of elements in the set is n. The number n is divisible by 5. All elements are between 1 and b, inclusive: bears don't know numbers greater than b. For each r in {0, 1, 2, 3, 4}, the set contains exactly elements that give remainder r when divided by 5. (That is, there are elements divisible by 5, elements of the form 5k + 1, elements of the form 5k + 2, and so on.) Limak smiles mysteriously and gives you q hints about his set. The i-th hint is the following sentence: ""If you only look at elements that are between 1 and upToi, inclusive, you will find exactly quantityi such elements in my set.""In a moment Limak will tell you the actual puzzle, but something doesn't seem right... That smile was very strange. You start to think about a possible reason. Maybe Limak cheated you? Or is he a fair grizzly bear?Given n, b, q and hints, check whether Limak can be fair, i.e. there exists at least one set satisfying the given conditions. If it's possible then print ''fair"". Otherwise, print ''unfair"".
The first line contains three integers n, b and q (5 ≤ n ≤ b ≤ 104, 1 ≤ q ≤ 104, n divisible by 5) — the size of the set, the upper limit for numbers in the set and the number of hints.The next q lines describe the hints. The i-th of them contains two integers upToi and quantityi (1 ≤ upToi ≤ b, 0 ≤ quantityi ≤ n).
Print ''fair"" if there exists at least one set that has all the required properties and matches all the given hints. Otherwise, print ''unfair"".
In the first example there is only one set satisfying all conditions: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.In the second example also there is only one set satisfying all conditions: {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}.Easy to see that there is no set satisfying all conditions from the third example. So Limak lied to you :-(
Input: 10 20 110 10 | Output: fair
Expert
2
1,468
316
146
6
741
E
741E
E. Arpa’s abnormal DNA and Mehrdad’s deep interest
3,400
data structures; string suffix structures
All of us know that girls in Arpa’s land are... ok, you’ve got the idea :DAnyone knows that Arpa isn't a normal man, he is ... well, sorry, I can't explain it more. Mehrdad is interested about the reason, so he asked Sipa, one of the best biology scientists in Arpa's land, for help. Sipa has a DNA editor. Sipa put Arpa under the DNA editor. DNA editor showed Arpa's DNA as a string S consisting of n lowercase English letters. Also Sipa has another DNA T consisting of lowercase English letters that belongs to a normal man.Now there are (n + 1) options to change Arpa's DNA, numbered from 0 to n. i-th of them is to put T between i-th and (i + 1)-th characters of S (0 ≤ i ≤ n). If i = 0, T will be put before S, and if i = n, it will be put after S.Mehrdad wants to choose the most interesting option for Arpa's DNA among these n + 1 options. DNA A is more interesting than B if A is lexicographically smaller than B. Mehrdad asked Sipa q questions: Given integers l, r, k, x, y, what is the most interesting option if we only consider such options i that l ≤ i ≤ r and ? If there are several most interesting options, Mehrdad wants to know one with the smallest number i.Since Sipa is a biology scientist but not a programmer, you should help him.
The first line contains strings S, T and integer q (1 ≤ |S|, |T|, q ≤ 105) — Arpa's DNA, the DNA of a normal man, and the number of Mehrdad's questions. The strings S and T consist only of small English letters.Next q lines describe the Mehrdad's questions. Each of these lines contain five integers l, r, k, x, y (0 ≤ l ≤ r ≤ n, 1 ≤ k ≤ n, 0 ≤ x ≤ y < k).
Print q integers. The j-th of them should be the number i of the most interesting option among those that satisfy the conditions of the j-th question. If there is no option i satisfying the conditions in some question, print -1.
Explanation of first sample case:In the first question Sipa has two options: dabc (i = 0) and abdc (i = 2). The latter (abcd) is better than abdc, so answer is 2.In the last question there is no i such that 0 ≤ i ≤ 1 and .
Input: abc d 40 3 2 0 00 3 1 0 01 2 1 0 00 1 3 2 2 | Output: 2 3 2 -1
Master
2
1,252
356
228
7
1,815
F
1815F
F. OH NO1 (-2-3-4)
3,500
constructive algorithms; graphs; math
You are given an undirected graph with \(n\) vertices and \(3m\) edges. The graph may contain multi-edges, but does not contain self-loops. The graph satisfies the following property: the given edges can be divided into \(m\) groups of \(3\), such that each group is a triangle.A triangle is defined as three edges \((a,b)\), \((b,c)\) and \((c,a)\) for some three distinct vertices \(a,b,c\) (\(1 \leq a,b,c \leq n\)).Initially, each vertex \(v\) has a non-negative integer weight \(a_v\). For every edge \((u,v)\) in the graph, you should perform the following operation exactly once: Choose an integer \(x\) between \(1\) and \(4\). Then increase both \(a_u\) and \(a_v\) by \(x\). After performing all operations, the following requirement should be satisfied: if \(u\) and \(v\) are connected by an edge, then \(a_u \ne a_v\).It can be proven this is always possible under the constraints of the task. Output a way to do so, by outputting the choice of \(x\) for each edge. It is easy to see that the order of operations does not matter. If there are multiple valid answers, output any.
The first line contains a single integer \(t\) (\(1 \leq t \leq 10^5\)) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers \(n\) and \(m\) (\(3 \le n \le 10^6\), \(1 \le m \le 4 \cdot 10^5\)) — denoting the graph have \(n\) vertices and \(3m\) edges.The second line of each test case contains \(n\) integers \(a_1,a_2,\ldots,a_n\) (\(0 \leq a_i \leq 10^6\)) — the initial weights of each vertex. Then \(m\) lines follow. The \(i\)-th line contains three integers \(a_i\), \(b_i\), \(c_i\) (\(1 \leq a_i < b_i < c_i \leq n\)) — denotes that three edges \((a_i,b_i)\), \((b_i,c_i)\) and \((c_i,a_i)\). Note that the graph may contain multi-edges: a pair \((x,y)\) may appear in multiple triangles.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^6\) and the sum of \(m\) over all test cases does not exceed \(4 \cdot 10^5\).
For each test case, output \(m\) lines of \(3\) integers each.The \(i\)-th line should contains three integers \(e_{ab},e_{bc},e_{ca}\) (\(1 \leq e_{ab}, e_{bc} , e_{ca} \leq 4\)), denoting the choice of value \(x\) for edges \((a_i, b_i)\), \((b_i,c_i)\) and \((c_i, a_i)\) respectively.
In the first test case, the initial weights are \([0,0,0,0]\). We have added values as follows: Added \(2\) to vertices \(1\) and \(2\) Added \(1\) to vertices \(2\) and \(3\) Added \(3\) to vertices \(3\) and \(1\) The final weights are \([5,3,4,0]\). The output is valid because \(a_1 \neq a_2\), \(a_1 \neq a_3\), \(a_2 \neq a_3\), and that all chosen values are between \(1\) and \(4\).In the second test case, the initial weights are \([0,0,0,0,0]\). The weights after the operations are \([12,5,6,7,6]\). The output is valid because \(a_1 \neq a_2\), \(a_1 \neq a_3\), \(a_2 \neq a_3\), and that \(a_1 \neq a_4\), \(a_1 \neq a_5\), \(a_4 \neq a_5\), and that all chosen values are between \(1\) and \(4\).In the third test case, the initial weights are \([3,4,5,6]\). The weights after the operations are \([19,16,17,20]\), and all final weights are distinct, which means no two adjacent vertices have the same weight.
Input: 44 10 0 0 01 2 35 20 0 0 0 01 2 31 4 54 43 4 5 61 2 31 2 41 3 42 3 45 40 1000000 412 412 4121 2 31 4 52 4 53 4 5 | Output: 2 1 3 2 3 3 4 3 3 3 1 2 2 2 3 2 3 4 3 1 1 2 3 4 1 2 4 4 4 3 4 1 1
Master
3
1,091
923
288
18
1,545
A
1545A
A. AquaMoon and Strange Sort
1,500
sortings
AquaMoon has \(n\) friends. They stand in a row from left to right, and the \(i\)-th friend from the left wears a T-shirt with a number \(a_i\) written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.AquaMoon hopes that after some operations, the numbers written on the T-shirt of \(n\) friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
The input consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 50\)) — the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \leq n \leq 10^5\)) — the number of Aquamoon's friends.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \leq a_i \leq 10^5\)) — the numbers, written on the T-shirts.It is guaranteed that the sum of \(n\) for all test cases does not exceed \(10^5\).
For each test case, if there exists a possible sequence of operations, print ""YES"" (without quotes); otherwise, print ""NO"" (without quotes).You can print each letter in any case (upper or lower).
The possible list of operations in the first test case: Swap \(a_1\) and \(a_2\). The resulting sequence is \(3, 4, 2, 5\). The directions are: left, left, right, right. Swap \(a_2\) and \(a_3\). The resulting sequence is \(3, 2, 4, 5\). The directions are: left, left, right, right. Swap \(a_1\) and \(a_2\). The resulting sequence is \(2, 3, 4, 5\). The directions are: right, right, right, right.
Input: 3 4 4 3 2 5 4 3 3 2 2 5 1 2 3 5 4 | Output: YES YES NO
Medium
1
763
479
199
15
1,619
H
1619H
H. Permutation and Queries
2,400
brute force; data structures; divide and conquer; two pointers
You are given a permutation \(p\) of \(n\) elements. A permutation of \(n\) elements is an array of length \(n\) containing each integer from \(1\) to \(n\) exactly once. For example, \([1, 2, 3]\) and \([4, 3, 5, 1, 2]\) are permutations, but \([1, 2, 4]\) and \([4, 3, 2, 1, 2]\) are not permutations. You should perform \(q\) queries.There are two types of queries: \(1\) \(x\) \(y\) — swap \(p_x\) and \(p_y\). \(2\) \(i\) \(k\) — print the number that \(i\) will become if we assign \(i = p_i\) \(k\) times.
The first line contains two integers \(n\) and \(q\) (\(1 \le n, q \le 10^5\)).The second line contains \(n\) integers \(p_1, p_2, \dots, p_n\).Each of the next \(q\) lines contains three integers. The first integer is \(t\) (\(1 \le t \le 2\)) — type of query. If \(t = 1\), then the next two integers are \(x\) and \(y\) (\(1 \le x, y \le n\); \(x \ne y\)) — first-type query. If \(t = 2\), then the next two integers are \(i\) and \(k\) (\(1 \le i, k \le n\)) — second-type query.It is guaranteed that there is at least one second-type query.
For every second-type query, print one integer in a new line — answer to this query.
In the first example \(p = \{5, 3, 4, 2, 1\}\). The first query is to print \(p_3\). The answer is \(4\).The second query is to print \(p_{p_1}\). The answer is \(1\).The third query is to swap \(p_1\) and \(p_3\). Now \(p = \{4, 3, 5, 2, 1\}\).The fourth query is to print \(p_{p_1}\). The answer is \(2\).
Input: 5 4 5 3 4 2 1 2 3 1 2 1 2 1 1 3 2 1 2 | Output: 4 1 2
Expert
4
512
545
84
16
1,909
C
1909C
C. Heavy Intervals
1,400
constructive algorithms; data structures; dsu; greedy; math; sortings
Shiki - Pure Ruby⠀You have \(n\) intervals \([l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]\), such that \(l_i < r_i\) for each \(i\), and all the endpoints of the intervals are distinct.The \(i\)-th interval has weight \(c_i\) per unit length. Therefore, the weight of the \(i\)-th interval is \(c_i \cdot (r_i - l_i)\).You don't like large weights, so you want to make the sum of weights of the intervals as small as possible. It turns out you can perform all the following three operations: rearrange the elements in the array \(l\) in any order; rearrange the elements in the array \(r\) in any order; rearrange the elements in the array \(c\) in any order. However, after performing all of the operations, the intervals must still be valid (i.e., for each \(i\), \(l_i < r_i\) must hold).What's the minimum possible sum of weights of the intervals after performing the operations?
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^5\)) — the number of intervals.The second line of each test case contains \(n\) integers \(l_1, l_2, \ldots, l_n\) (\(1 \le l_i \le 2 \cdot 10^5\)) — the left endpoints of the initial intervals.The third line of each test case contains \(n\) integers \(r_1, r_2, \ldots, r_n\) (\(l_i < r_i \le 2 \cdot 10^5\)) — the right endpoints of the initial intervals.It is guaranteed that \(\{l_1, l_2, \dots, l_n, r_1, r_2, \dots, r_n\}\) are all distinct.The fourth line of each test case contains \(n\) integers \(c_1, c_2, \ldots, c_n\) (\(1 \le c_i \le 10^7\)) — the initial weights of the intervals per unit length.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case, output a single integer: the minimum possible sum of weights of the intervals after your operations.
In the first test case, you can make \(l = [8, 3]\); \(r = [23, 12]\); \(c = [100, 100]\). In that case, there are two intervals: interval \([8, 23]\) with weight \(100\) per unit length, and \(100 \cdot (23-8) = 1500\) in total; interval \([3, 12]\) with weight \(100\) per unit length, and \(100 \cdot (12-3) = 900\) in total. The sum of the weights is \(2400\). It can be shown that there is no configuration of final intervals whose sum of weights is less than \(2400\).In the second test case, you can make \(l = [1, 2, 5, 20]\); \(r = [3, 4, 10, 30]\); \(c = [3, 3, 2, 2]\). In that case, there are four intervals: interval \([1, 3]\) with weight \(3\) per unit length, and \(3 \cdot (3-1) = 6\) in total; interval \([2, 4]\) with weight \(3\) per unit length, and \(3 \cdot (4-2) = 6\) in total; interval \([5, 10]\) with weight \(2\) per unit length, and \(2 \cdot (10-5) = 10\) in total; interval \([20, 30]\) with weight \(2\) per unit length, and \(2 \cdot (30-20) = 20\) in total. The sum of the weights is \(42\). It can be shown that there is no configuration of final intervals whose sum of weights is less than \(42\).
Input: 228 312 23100 100420 1 2 530 4 3 102 3 2 3 | Output: 2400 42
Easy
6
880
939
120
19
1,297
H
1297H
H. Paint the String
0
*special; dp; strings
You are given a string \(s\) of lowercase Latin letters. It is required to paint each letter of the string in one of two colors (red or blue) so that if you write all the red letters from left to right and write all the blue letters from left to right, then the lexicographically maximum of the two written strings is lexicographically minimal. For each index, in the string \(s\) you can choose either of two colors.Formally, we write out: the string \(r\) (can be empty) — all red letters in the order from left to right (red subsequence), the string \(b\) (can be empty) — all blue letters in the order from left to right (blue subsequence). Your task is to paint the string such that \(\max(r, b)\) is minimal. Small reminder: the empty string is the lexicographically smallest string.
The first line contains an integer \(t\) (\(1 \le t \le 100\)) — the number of test cases in the test. Next, the test cases are given, one per line.Each test case is a non-empty string \(s\) of length between \(2\) to \(100\) characters, inclusive, which consists of lowercase Latin letters.
Print \(t\) lines, the \(i\)-th of them should contain the answer to the \(i\)-th test case of the input. Print a string of length \(n\), where \(n\) is the length of the given string \(s\): the \(j\)-th character of the string should be either 'R'or 'B' depending on the color of the \(j\)-th character in the answer (painted in red or blue). If there are several possible answers, print any of them.
Input: 5 kotlin codeforces abacaba ffccgc yz | Output: RRRRBB RRRRRRRBBB RRRRBBB RBBBBR RR
Beginner
3
789
291
401
12
734
A
734A
A. Anton and Danik
800
implementation; strings
Anton likes to play chess, and so does his friend Danik.Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.Now Anton wonders, who won more games, he or Danik? Help him determine this.
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played.The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.
If Anton won more games than Danik, print ""Anton"" (without quotes) in the only line of the output.If Danik won more games than Anton, print ""Danik"" (without quotes) in the only line of the output.If Anton and Danik won the same number of games, print ""Friendship"" (without quotes).
In the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is ""Anton"".In the second sample, Anton won 3 games and Danik won 4 games, so the answer is ""Danik"".In the third sample, both Anton and Danik won 3 games and the answer is ""Friendship"".
Input: 6ADAAAA | Output: Anton
Beginner
2
269
345
287
7
811
E
811E
E. Vladik and Entertaining Flags
2,600
data structures; dsu; graphs
In his spare time Vladik estimates beauty of the flags.Every flag could be represented as the matrix n × m which consists of positive integers.Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components: But this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at (1, l) and (n, r), where conditions 1 ≤ l ≤ r ≤ m are satisfied.Help Vladik to calculate the beauty for some segments of the given flag.
First line contains three space-separated integers n, m, q (1 ≤ n ≤ 10, 1 ≤ m, q ≤ 105) — dimensions of flag matrix and number of segments respectively.Each of next n lines contains m space-separated integers — description of flag matrix. All elements of flag matrix is positive integers not exceeding 106.Each of next q lines contains two space-separated integers l, r (1 ≤ l ≤ r ≤ m) — borders of segment which beauty Vladik wants to know.
For each segment print the result on the corresponding line.
Partitioning on components for every segment from first test case:
Input: 4 5 41 1 1 1 11 2 2 3 31 1 1 2 54 4 5 5 51 52 51 24 5 | Output: 6734
Expert
3
804
441
60
8
1,666
I
1666I
I. Interactive Treasure Hunt
2,200
brute force; constructive algorithms; geometry; interactive; math
This is an interactive problem.There is a grid of \(n\times m\) cells. Two treasure chests are buried in two different cells of the grid. Your task is to find both of them. You can make two types of operations: DIG \(r\) \(c\): try to find the treasure in the cell \((r, c)\). The interactor will tell you if you found the treasure or not. SCAN \(r\) \(c\): scan from the cell \((r, c)\). The result of this operation is the sum of Manhattan distances from the cell \((r, c)\) to the cells where the treasures are hidden. Manhattan distance from a cell \((r_1, c_1)\) to a cell \((r_2, c_2)\) is calculated as \(|r_1 - r_2| + |c_1 - c_2|\). You need to find the treasures in at most 7 operations. This includes both DIG and SCAN operations in total. To solve the test you need to call DIG operation at least once in both of the cells where the treasures are hidden.
Input: 1 2 3 1 1 3 0 1 | Output: SCAN 1 2 DIG 1 2 SCAN 2 2 DIG 1 1 DIG 1 3
Hard
5
865
0
0
16
2,114
B
2114B
B. Not Quite a Palindromic String
900
greedy; math
Vlad found a binary string\(^{\text{∗}}\) \(s\) of even length \(n\). He considers a pair of indices (\(i, n - i + 1\)), where \(1 \le i < n - i + 1\), to be good if \(s_i = s_{n - i + 1}\) holds true.For example, in the string '010001' there is only \(1\) good pair, since \(s_1 \ne s_6\), \(s_2 \ne s_5\), and \(s_3=s_4\). In the string '0101' there are no good pairs.Vlad loves palindromes, but not too much, so he wants to rearrange some characters of the string so that there are exactly \(k\) good pairs of indices.Determine whether it is possible to rearrange the characters in the given string so that there are exactly \(k\) good pairs of indices (\(i, n - i + 1\)).\(^{\text{∗}}\)A string \(s\) is called binary if it consists only of the characters '0' and '1'
The first line contains an integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.The first line of each test case contains two integers \(n\) and \(k\) (\(2 \le n \le 2 \cdot 10^5\), \(0 \le k \le \frac{n}{2}\), \(n\) is even) — the length of the string and the required number of good pairs.The second line of each test case contains a binary string \(s\) of length \(n\).It is guaranteed that the sum of \(n\) across all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output ""YES"" if there is a way to rearrange the characters of the string so that there are exactly \(k\) good pairs, otherwise output ""NO"".You may output each letter in any case (lowercase or uppercase). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be accepted as a positive answer.
Input: 66 20000002 1014 1101110 2110101100110 111010110012 111 | Output: NO NO YES NO YES YES
Beginner
2
771
477
330
21
311
C
311C
C. Fetch the Treasure
2,500
brute force; data structures; graphs; shortest paths
Rainbow built h cells in a row that are numbered from 1 to h from left to right. There are n cells with treasure. We call each of these n cells ""Treasure Cell"". The i-th ""Treasure Cell"" is the ai-th cell and the value of treasure in it is ci dollars.Then, Freda went in the first cell. For now, she can go just k cells forward, or return to the first cell. That means Freda was able to reach the 1st, (k + 1)-th, (2·k + 1)-th, (3·k + 1)-th cells and so on.Then Rainbow gave Freda m operations. Each operation is one of the following three types: Add another method x: she can also go just x cells forward at any moment. For example, initially she has only one method k. If at some moment she has methods a1, a2, ..., ar then she can reach all the cells with number in form , where vi — some non-negative integer. Reduce the value of the treasure in the x-th ""Treasure Cell"" by y dollars. In other words, to apply assignment cx = cx - y. Ask the value of the most valuable treasure among the cells Freda can reach. If Freda cannot reach any cell with the treasure then consider the value of the most valuable treasure equal to 0, and do nothing. Otherwise take the most valuable treasure away. If several ""Treasure Cells"" have the most valuable treasure, take the ""Treasure Cell"" with the minimum number (not necessarily with the minimum number of cell). After that the total number of cells with a treasure is decreased by one. As a programmer, you are asked by Freda to write a program to answer each query.
The first line of the input contains four integers: h (1 ≤ h ≤ 1018), n, m (1 ≤ n, m ≤ 105) and k (1 ≤ k ≤ 104).Each of the next n lines contains two integers: ai (1 ≤ ai ≤ h), ci (1 ≤ ci ≤ 109). That means the i-th ""Treasure Cell"" is the ai-th cell and cost of the treasure in that cell is ci dollars. All the ai are distinct.Each of the next m lines is in one of the three following formats: ""1 x"" — an operation of type 1, 1 ≤ x ≤ h; ""2 x y"" — an operation of type 2, 1 ≤ x ≤ n, 0 ≤ y < cx; ""3"" — an operation of type 3. There are at most 20 operations of type 1. It's guaranteed that at any moment treasure in each cell has positive value. It's guaranteed that all operations is correct (no operation can decrease the value of the taken tresure).Please, do not use the %lld specifier to read 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
For each operation of type 3, output an integer indicates the value (in dollars) of the most valuable treasure among the ""Treasure Cells"" Freda can reach. If there is no such treasure, output 0.
In the sample, there are 10 cells and 3 ""Treasure Cells"". The first ""Treasure Cell"" is cell 5, having 50 dollars tresure in it. The second ""Treasure Cell"" is cell 7, having 60 dollars tresure in it. The third ""Treasure Cell"" is cell 8, having 100 dollars tresure in it.At first, Freda can only reach cell 1, 3, 5, 7 and 9. In the first operation, we reduce the value in the second ""Treasure Cell"" from 60 to 55. Then the most valuable treasure among the ""Treasure Cells"" she can reach is max(50, 55) = 55. After the third operation, she can also go 3 cells forward each step, being able to reach cell 1, 3, 4, 5, 6, 7, 8, 9, 10. So the most valuable tresure is 100.Noticed that she took the 55 dollars and 100 dollars treasure away, so the last answer is 50.
Input: 10 3 5 25 507 608 1002 2 531 333 | Output: 5510050
Expert
4
1,518
896
196
3
1,661
D
1661D
D. Progressions Covering
1,900
data structures; greedy
You are given two arrays: an array \(a\) consisting of \(n\) zeros and an array \(b\) consisting of \(n\) integers.You can apply the following operation to the array \(a\) an arbitrary number of times: choose some subsegment of \(a\) of length \(k\) and add the arithmetic progression \(1, 2, \ldots, k\) to this subsegment — i. e. add \(1\) to the first element of the subsegment, \(2\) to the second element, and so on. The chosen subsegment should be inside the borders of the array \(a\) (i.e., if the left border of the chosen subsegment is \(l\), then the condition \(1 \le l \le l + k - 1 \le n\) should be satisfied). Note that the progression added is always \(1, 2, \ldots, k\) but not the \(k, k - 1, \ldots, 1\) or anything else (i.e., the leftmost element of the subsegment always increases by \(1\), the second element always increases by \(2\) and so on).Your task is to find the minimum possible number of operations required to satisfy the condition \(a_i \ge b_i\) for each \(i\) from \(1\) to \(n\). Note that the condition \(a_i \ge b_i\) should be satisfied for all elements at once.
The first line of the input contains two integers \(n\) and \(k\) (\(1 \le k \le n \le 3 \cdot 10^5\)) — the number of elements in both arrays and the length of the subsegment, respectively.The second line of the input contains \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(1 \le b_i \le 10^{12}\)), where \(b_i\) is the \(i\)-th element of the array \(b\).
Print one integer — the minimum possible number of operations required to satisfy the condition \(a_i \ge b_i\) for each \(i\) from \(1\) to \(n\).
Consider the first example. In this test, we don't really have any choice, so we need to add at least five progressions to make the first element equals \(5\). The array \(a\) becomes \([5, 10, 15]\).Consider the second example. In this test, let's add one progression on the segment \([1; 3]\) and two progressions on the segment \([4; 6]\). Then, the array \(a\) becomes \([1, 2, 3, 2, 4, 6]\).
Input: 3 3 5 4 6 | Output: 5
Hard
2
1,104
355
147
16
75
E
75E
E. Ship's Shortest Path
2,400
geometry; shortest paths
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.You can move your ship on the island edge, and it will be considered moving in the sea.Now you have a sea map, and you have to decide what is the minimum cost for your trip.Your starting point is (xStart, yStart), and the end point is (xEnd, yEnd), both points will be different.The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
The first line contains 4 integers, xStart, yStart, xEnd and yEnd ( - 100 ≤ xStart, yStart, xEnd, yEnd ≤ 100). The second line contains an integer n, which is the number of points in the polygon (3 ≤ n ≤ 30), followed by a line containing n pairs of integers x and y, which are the coordinates of the points ( - 100 ≤ x, y ≤ 100), the polygon points will be distinct.
Print one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10 - 6.
Input: 1 7 6 744 2 4 12 3 12 3 2 | Output: 6.000000000
Expert
2
1,639
367
127
0
82
A
82A
A. Double Cola
1,100
implementation; math
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a ""Double Cola"" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on. This process continues ad infinitum.For example, Penny drinks the third can of cola and the queue will look like this: Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny.Write a program that will print the name of a man who will drink the n-th can.Note that in the very beginning the queue looks like that: Sheldon, Leonard, Penny, Rajesh, Howard. The first person is Sheldon.
The input data consist of a single integer n (1 ≤ n ≤ 109).It is guaranteed that the pretests check the spelling of all the five names, that is, that they contain all the five possible answers.
Print the single line — the name of the person who drinks the n-th can of cola. The cans are numbered starting from 1. Please note that you should spell the names like this: ""Sheldon"", ""Leonard"", ""Penny"", ""Rajesh"", ""Howard"" (without the quotes). In that order precisely the friends are in the queue initially.
Input: 1 | Output: Sheldon
Easy
2
782
193
319
0
56
E
56E
E. Domino Principle
2,200
binary search; data structures; sortings
Vasya is interested in arranging dominoes. He is fed up with common dominoes and he uses the dominoes of different heights. He put n dominoes on the table along one axis, going from left to right. Every domino stands perpendicular to that axis so that the axis passes through the center of its base. The i-th domino has the coordinate xi and the height hi. Now Vasya wants to learn for every domino, how many dominoes will fall if he pushes it to the right. Help him do that. Consider that a domino falls if it is touched strictly above the base. In other words, the fall of the domino with the initial coordinate x and height h leads to the fall of all dominoes on the segment [x + 1, x + h - 1].
The first line contains integer n (1 ≤ n ≤ 105) which is the number of dominoes. Then follow n lines containing two integers xi and hi ( - 108 ≤ xi ≤ 108, 2 ≤ hi ≤ 108) each, which are the coordinate and height of every domino. No two dominoes stand on one point.
Print n space-separated numbers zi — the number of dominoes that will fall if Vasya pushes the i-th domino to the right (including the domino itself).
Input: 416 520 510 1018 2 | Output: 3 1 4 1
Hard
3
697
263
150
0
245
G
245G
G. Suggested Friends
2,200
brute force; graphs
Polycarpus works as a programmer in a start-up social network. His boss gave his a task to develop a mechanism for determining suggested friends. Polycarpus thought much about the task and came to the folowing conclusion. Let's say that all friendship relationships in a social network are given as m username pairs ai, bi (ai ≠ bi). Each pair ai, bi means that users ai and bi are friends. Friendship is symmetric, that is, if ai is friends with bi, then bi is also friends with ai. User y is a suggested friend for user x, if the following conditions are met: x ≠ y; x and y aren't friends; among all network users who meet the first two conditions, user y has most of all common friends with user x. User z is a common friend of user x and user y (z ≠ x, z ≠ y), if x and z are friends, and y and z are also friends. Your task is to help Polycarpus to implement a mechanism for determining suggested friends.
The first line contains a single integer m (1 ≤ m ≤ 5000) — the number of pairs of friends in the social network. Next m lines contain pairs of names of the users who are friends with each other. The i-th line contains two space-separated names ai and bi (ai ≠ bi). The users' names are non-empty and consist of at most 20 uppercase and lowercase English letters. It is guaranteed that each pair of friends occurs only once in the input. For example, the input can't contain x, y and y, x at the same time. It is guaranteed that distinct users have distinct names. It is guaranteed that each social network user has at least one friend. The last thing guarantees that each username occurs at least once in the input.
In the first line print a single integer n — the number of network users. In next n lines print the number of suggested friends for each user. In the i-th line print the name of the user ci and the number of his suggested friends di after a space. You can print information about the users in any order.
In the first test case consider user David. Users Mike and Tank have one common friend (Gerald) with David. User Kate has no common friends with David. That's why David's suggested friends are users Mike and Tank.
Input: 5Mike GeraldKate MikeKate TankGerald TankGerald David | Output: 5Mike 1Gerald 1Kate 1Tank 1David 2
Hard
2
911
716
303
2
245
F
245F
F. Log Stream Analysis
2,000
binary search; brute force; implementation; strings
You've got a list of program warning logs. Each record of a log stream is a string in this format: ""2012-MM-DD HH:MM:SS:MESSAGE"" (without the quotes). String ""MESSAGE"" consists of spaces, uppercase and lowercase English letters and characters ""!"", ""."", "","", ""?"". String ""2012-MM-DD"" determines a correct date in the year of 2012. String ""HH:MM:SS"" determines a correct time in the 24 hour format.The described record of a log stream means that at a certain time the record has got some program warning (string ""MESSAGE"" contains the warning's description).Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m.
The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 10000).The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program. It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5·106 (in particular, this means that the length of some line does not exceed 5·106 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE"" in all records is non-empty.
If there is no sought moment of time, print -1. Otherwise print a string in the format ""2012-MM-DD HH:MM:SS"" (without the quotes) — the first moment of time when the number of warnings for the last n seconds got no less than m.
Input: 60 32012-03-16 16:15:25: Disk size is2012-03-16 16:15:25: Network failute2012-03-16 16:16:29: Cant write varlog2012-03-16 16:16:42: Unable to start process2012-03-16 16:16:43: Disk size is too small2012-03-16 16:16:53: Timeout detected | Output: 2012-03-16 16:16:43
Hard
4
693
858
229
2
1,874
G
1874G
G. Jellyfish and Inscryption
3,500
dp
Jellyfish loves playing a game called ""Inscryption"" which is played on a directed acyclic graph with \(n\) vertices and \(m\) edges. All edges \(a \to b\) satisfy \(a < b\).You need to move from vertex \(1\) to vertex \(n\) along the directed edges, and then fight with the final boss.You will collect cards and props in the process.Each card has two attributes: HP and damage. If a card's HP is \(a\) and its damage is \(b\), then the power of the card is \(a \times b\).Each prop has only one attribute: power.In addition to vertex \(1\) and vertex \(n\), there are some vertices that trigger special events. The special events are: You will get a card with \(a\) HP, and \(b\) damage. If you have at least one card, choose one of your cards and increase its HP by \(x\). If you have at least one card, choose one of your cards and increase its damage by \(y\). You will get a prop with \(w\) power. When you get to vertex \(n\), you can choose at most one of your cards and multiply its damage by \(10^9\).The final boss is very strong, so you want to maximize the sum of the power of all your cards and props. Find the maximum possible sum of power of all your cards and props if you play the game optimally.
The first line contains two integers \(n\) and \(m\) (\(2 \leq n \leq 200\), \(n - 1\leq m \leq \min(\frac{n(n-1)}2, 2000)\)) — the number of the vertices and the number of the edges.In the following \(n\) lines, the \(i\)-th \((1 \leq i \leq n)\) line describes the special event that will trigger on vertex \(i\): 0 — no special events. 1 a b (\(1 \leq a, b \leq 200\)) — you will get a card with \(a\) HP, and \(b\) damage. 2 x (\(1 \leq x \leq 200\)) — if you have at least one card, choose one of your cards and increase its HP by \(x\). 3 y (\(1 \leq y \leq 200\)) — if you have at least one card, choose one of your cards and increase its damage by \(y\). 4 w (\(1 \leq w \leq 10^6\)) — you will get a prop with \(w\) power. In the following \(m\) lines, each line contains two integers \(u\) and \(v\) (\(1 \leq u < v \leq n\)) representing a directed edge from vertex \(u\) to vertex \(v\).It is guaranteed that every edge \((u,v)\) appears at most once.It is guaranteed that there are no special events on vertex \(1\) and vertex \(n\).It is guaranteed that for all \(i\), there exists a path from vertex \(1\) to vertex \(n\) that passes through vertex \(i\).
Output a single integer — the maximum sum of the power of all your cards and props.
In the first example, we will play the game in the following order: move from vertex \(1\) to vertex \(2\), get a card with \(2\) HP, and \(10\) damage. move from vertex \(2\) to vertex \(4\), choose the card we get from vertex \(2\) and increase its HP by \(8\). move from vertex \(4\) to vertex \(6\), choose the card we get from vertex \(2\) and multiply its damage by \(10^9\). In the end, we will have a card with \((2+8)=10\) HP and \(10 \times 10^9=10^{10}\) damage, It's power is \(10 \times 10^{10}=10^{11}\). Because we only have the card we get from vertex \(2\), so the sum of power of all your cards and props is \(10^{11}\).
Input: 6 8 0 1 2 10 1 6 6 2 8 3 10 0 1 2 1 3 2 4 2 5 3 4 3 5 4 6 5 6 | Output: 100000000000
Master
1
1,214
1,170
83
18
1,797
B
1797B
B. Li Hua and Pattern
1,100
constructive algorithms; greedy
Li Hua has a pattern of size \(n\times n\), each cell is either blue or red. He can perform exactly \(k\) operations. In each operation, he chooses a cell and changes its color from red to blue or from blue to red. Each cell can be chosen as many times as he wants. Is it possible to make the pattern, that matches its rotation by \(180^{\circ}\)?Suppose you were Li Hua, please solve this problem.
The first line contains the single integer \(t\) (\(1 \le t \le 100\)) — the number of test cases.The first line of each test case contains two integers \(n,k\) (\(1\le n\le 10^3,0\le k \le 10^9\)) — the size of the pattern and the number of operations.Each of next \(n\) lines contains \(n\) integers \(a_{i,j}\) (\(a_{i,j}\in\{0,1\}\)) — the initial color of the cell, \(0\) for blue and \(1\) for red.It's guaranteed that sum of \(n\) over all test cases does not exceed \(10^3\).
For each set of input, print ""YES"" if it's possible to make the pattern, that matches its rotation by \(180^{\circ}\) after applying exactly \(k\) of operations, and ""NO"" otherwise.You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
In test case 1, you can't perform any operation. The pattern after rotation is on the right. In test case 2, you can perform operations on \((2,1),(3,2),(3,4)\). The pattern after operations is in the middle and the pattern after rotation is on the right.
Input: 34 01 1 1 10 0 0 11 0 1 01 1 1 14 31 0 1 11 0 0 00 1 0 11 1 0 15 40 0 0 0 00 1 1 1 10 1 0 0 01 1 1 1 10 0 0 0 0 | Output: NO YES YES
Easy
2
398
483
346
17
353
B
353B
B. Two Heaps
1,900
combinatorics; constructive algorithms; greedy; implementation; math; sortings
Valera has 2·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap. Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube from the second heap and write out its two digits near two digits he had written (to the right of them). In the end he obtained a single fourdigit integer — the first two digits of it is written on the cube from the first heap, and the second two digits of it is written on the second cube from the second heap.Valera knows arithmetic very well. So, he can easily count the number of distinct fourdigit numbers he can get in the game. The other question is: how to split cubes into two heaps so that this number (the number of distinct fourdigit integers Valera can get) will be as large as possible?
The first line contains integer n (1 ≤ n ≤ 100). The second line contains 2·n space-separated integers ai (10 ≤ ai ≤ 99), denoting the numbers on the cubes.
In the first line print a single number — the maximum possible number of distinct four-digit numbers Valera can obtain. In the second line print 2·n numbers bi (1 ≤ bi ≤ 2). The numbers mean: the i-th cube belongs to the bi-th heap in your division.If there are multiple optimal ways to split the cubes into the heaps, print any of them.
In the first test case Valera can put the first cube in the first heap, and second cube — in second heap. In this case he obtain number 1099. If he put the second cube in the first heap, and the first cube in the second heap, then he can obtain number 9910. In both cases the maximum number of distinct integers is equal to one.In the second test case Valera can obtain numbers 1313, 1345, 2413, 2445. Note, that if he put the first and the third cubes in the first heap, he can obtain only two numbers 1324 and 1345.
Input: 110 99 | Output: 12 1
Hard
6
916
156
337
3
1,780
F
1780F
F. Three Chairs
2,300
bitmasks; brute force; combinatorics; data structures; dp; number theory; sortings
One day Kira found \(n\) friends from Morioh and decided to gather them around a table to have a peaceful conversation. The height of friend \(i\) is equal to \(a_i\). It so happened that the height of each of the friends is unique.Unfortunately, there were only \(3\) chairs in Kira's house, and obviously, it will not be possible to seat all friends! So, Kira has to invite only \(3\) of his friends.But everything is not so simple! If the heights of the lowest and the tallest of the invited friends are not coprime, then the friends will play tricks on each other, which will greatly anger Kira.Kira became interested, how many ways are there to choose \(3\) of his friends so that they don't play tricks? Two ways are considered different if there is a friend invited in one way, but not in the other.Formally, if Kira invites friends \(i\), \(j\), and \(k\), then the following should be true: \(\gcd(\min(a_i, a_j, a_k), \max(a_i, a_j, a_k)) = 1\), where \(\gcd(x, y)\) denotes the greatest common divisor (GCD) of the numbers \(x\) and \(y\).Kira is not very strong in computer science, so he asks you to count the number of ways to invide friends.
The first line contains the number \(n\) (\(3 \le n \le 3\cdot10^5\)) — the number of Kira's friends.The next line contains \(n\) distinct integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 3\cdot10^5\)) — heights of Kira's friends.
In a single line output the number of ways to invite three friends.
In the first example, only one way is suitable: invite friends \(1\), \(2\), and \(3\). Here \(1 < 2 < 3\), and the numbers \(1\) and \(3\) are coprime.
Input: 3 1 2 3 | Output: 1
Expert
7
1,156
233
67
17
1,938
M
1938M
3,500
Master
0
0
0
0
19
929
A
929A
A. Прокат велосипедов
1,400
*special; greedy; implementation
Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды.Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть n точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке x1 километров вдоль улицы, второй — в точке x2 и так далее, n-й велопрокат находится в точке xn. Школа Аркадия находится в точке x1 (то есть там же, где и первый велопрокат), а дом — в точке xn (то есть там же, где и n-й велопрокат). Известно, что xi < xi + 1 для всех 1 ≤ i < n.Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше k километров вдоль улицы. Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.
В первой строке следуют два целых числа n и k (2 ≤ n ≤ 1 000, 1 ≤ k ≤ 100 000) — количество велопрокатов и максимальное расстояние, которое Аркадий может проехать на одном велосипеде.В следующей строке следует последовательность целых чисел x1, x2, ..., xn (0 ≤ x1 < x2 < ... < xn ≤ 100 000) — координаты точек, в которых находятся велопрокаты. Гарантируется, что координаты велопрокатов заданы в порядке возрастания.
Если Аркадий не сможет добраться от школы до дома только на велосипедах, выведите -1. В противном случае, выведите минимальное количество велосипедов, которые Аркадию нужно взять в точках проката.
В первом примере Аркадий должен взять первый велосипед в первом велопрокате и доехать на нём до второго велопроката. Во втором велопрокате он должен взять новый велосипед, на котором он сможет добраться до четвертого велопроката, рядом с которым и находится его дом. Поэтому Аркадию нужно всего два велосипеда, чтобы добраться от школы до дома.Во втором примере всего два велопроката, расстояние между которыми 10. Но максимальное расстояние, которое можно проехать на одном велосипеде, равно 9. Поэтому Аркадий не сможет добраться от школы до дома только на велосипедах.
Input: 4 43 6 8 10 | Output: 2
Easy
3
1,527
417
196
9
1,141
F2
1141F2
F2. Same Sum Blocks (Hard)
1,900
data structures; greedy
This problem is given in two editions, which differ exclusively in the constraints on the number \(n\).You are given an array of integers \(a[1], a[2], \dots, a[n].\) A block is a sequence of contiguous (consecutive) elements \(a[l], a[l+1], \dots, a[r]\) (\(1 \le l \le r \le n\)). Thus, a block is defined by a pair of indices \((l, r)\).Find a set of blocks \((l_1, r_1), (l_2, r_2), \dots, (l_k, r_k)\) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks \((l_i, r_i)\) and \((l_j, r_j\)) where \(i \neq j\) either \(r_i < l_j\) or \(r_j < l_i\). For each block the sum of its elements is the same. Formally, $$$\(a[l_1]+a[l_1+1]+\dots+a[r_1]=a[l_2]+a[l_2+1]+\dots+a[r_2]=\)\( \)\(\dots =\)\( \)\(a[l_k]+a[l_k+1]+\dots+a[r_k].\)\( The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks \)(l_1', r_1'), (l_2', r_2'), \dots, (l_{k'}', r_{k'}')\( satisfying the above two requirements with \)k' > k$$$. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.
The first line contains integer \(n\) (\(1 \le n \le 1500\)) — the length of the given array. The second line contains the sequence of elements \(a[1], a[2], \dots, a[n]\) (\(-10^5 \le a_i \le 10^5\)).
In the first line print the integer \(k\) (\(1 \le k \le n\)). The following \(k\) lines should contain blocks, one per line. In each line print a pair of indices \(l_i, r_i\) (\(1 \le l_i \le r_i \le n\)) — the bounds of the \(i\)-th block. You can print blocks in any order. If there are multiple answers, print any of them.
Input: 7 4 1 2 2 1 5 3 | Output: 3 7 7 2 3 4 5
Hard
2
1,106
201
326
11
1,895
B
1895B
B. Points and Minimum Distance
800
greedy; math; sortings
You are given a sequence of integers \(a\) of length \(2n\). You have to split these \(2n\) integers into \(n\) pairs; each pair will represent the coordinates of a point on a plane. Each number from the sequence \(a\) should become the \(x\) or \(y\) coordinate of exactly one point. Note that some points can be equal.After the points are formed, you have to choose a path \(s\) that starts from one of these points, ends at one of these points, and visits all \(n\) points at least once.The length of path \(s\) is the sum of distances between all adjacent points on the path. In this problem, the distance between two points \((x_1, y_1)\) and \((x_2, y_2)\) is defined as \(|x_1-x_2| + |y_1-y_2|\).Your task is to form \(n\) points and choose a path \(s\) in such a way that the length of path \(s\) is minimized.
The first line contains a single integer \(t\) (\(1 \le t \le 100\)) — the number of testcases.The first line of each testcase contains a single integer \(n\) (\(2 \le n \le 100\)) — the number of points to be formed.The next line contains \(2n\) integers \(a_1, a_2, \dots, a_{2n}\) (\(0 \le a_i \le 1\,000\)) — the description of the sequence \(a\).
For each testcase, print the minimum possible length of path \(s\) in the first line.In the \(i\)-th of the following \(n\) lines, print two integers \(x_i\) and \(y_i\) — the coordinates of the point that needs to be visited at the \(i\)-th position.If there are multiple answers, print any of them.
In the first testcase, for instance, you can form points \((10, 1)\) and \((15, 5)\) and start the path \(s\) from the first point and end it at the second point. Then the length of the path will be \(|10 - 15| + |1 - 5| = 5 + 4 = 9\).In the second testcase, you can form points \((20, 20)\), \((10, 30)\), and \((10, 30)\), and visit them in that exact order. Then the length of the path will be \(|20 - 10| + |20 - 30| + |10 - 10| + |30 - 30| = 10 + 10 + 0 + 0 = 20\).
Input: 2215 1 10 5310 30 20 20 30 10 | Output: 9 10 1 15 5 20 20 20 10 30 10 30
Beginner
3
818
351
300
18
1,499
C
1499C
C. Minimum Grid Path
1,500
brute force; data structures; greedy; math
Let's say you are standing on the \(XY\)-plane at point \((0, 0)\) and you want to reach point \((n, n)\).You can move only in two directions: to the right, i. e. horizontally and in the direction that increase your \(x\) coordinate, or up, i. e. vertically and in the direction that increase your \(y\) coordinate. In other words, your path will have the following structure: initially, you choose to go to the right or up; then you go some positive integer distance in the chosen direction (distances can be chosen independently); after that you change your direction (from right to up, or from up to right) and repeat the process. You don't like to change your direction too much, so you will make no more than \(n - 1\) direction changes.As a result, your path will be a polygonal chain from \((0, 0)\) to \((n, n)\), consisting of at most \(n\) line segments where each segment has positive integer length and vertical and horizontal segments alternate.Not all paths are equal. You have \(n\) integers \(c_1, c_2, \dots, c_n\) where \(c_i\) is the cost of the \(i\)-th segment.Using these costs we can define the cost of the path as the sum of lengths of the segments of this path multiplied by their cost, i. e. if the path consists of \(k\) segments (\(k \le n\)), then the cost of the path is equal to \(\sum\limits_{i=1}^{k}{c_i \cdot length_i}\) (segments are numbered from \(1\) to \(k\) in the order they are in the path).Find the path of the minimum cost and print its cost.
The first line contains the single integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases.The first line of each test case contains the single integer \(n\) (\(2 \le n \le 10^5\)).The second line of each test case contains \(n\) integers \(c_1, c_2, \dots, c_n\) (\(1 \le c_i \le 10^9\)) — the costs of each segment.It's guaranteed that the total sum of \(n\) doesn't exceed \(10^5\).
For each test case, print the minimum possible cost of the path from \((0, 0)\) to \((n, n)\) consisting of at most \(n\) alternating segments.
In the first test case, to reach \((2, 2)\) you need to make at least one turn, so your path will consist of exactly \(2\) segments: one horizontal of length \(2\) and one vertical of length \(2\). The cost of the path will be equal to \(2 \cdot c_1 + 2 \cdot c_2 = 26 + 176 = 202\).In the second test case, one of the optimal paths consists of \(3\) segments: the first segment of length \(1\), the second segment of length \(3\) and the third segment of length \(2\).The cost of the path is \(1 \cdot 2 + 3 \cdot 3 + 2 \cdot 1 = 13\).In the third test case, one of the optimal paths consists of \(4\) segments: the first segment of length \(1\), the second one — \(1\), the third one — \(4\), the fourth one — \(4\). The cost of the path is \(1 \cdot 4 + 1 \cdot 3 + 4 \cdot 2 + 4 \cdot 1 = 19\).
Input: 3 2 13 88 3 2 3 1 5 4 3 2 1 4 | Output: 202 13 19
Medium
4
1,487
393
143
14
2,026
C
2026C
C. Action Figures
1,500
binary search; brute force; constructive algorithms; data structures; greedy; implementation
There is a shop that sells action figures near Monocarp's house. A new set of action figures will be released shortly; this set contains \(n\) figures, the \(i\)-th figure costs \(i\) coins and is available for purchase from day \(i\) to day \(n\).For each of the \(n\) days, Monocarp knows whether he can visit the shop.Every time Monocarp visits the shop, he can buy any number of action figures which are sold in the shop (of course, he cannot buy an action figure that is not yet available for purchase). If Monocarp buys at least two figures during the same day, he gets a discount equal to the cost of the most expensive figure he buys (in other words, he gets the most expensive of the figures he buys for free). Monocarp wants to buy exactly one \(1\)-st figure, one \(2\)-nd figure, ..., one \(n\)-th figure from the set. He cannot buy the same figure twice. What is the minimum amount of money he has to spend?
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.Each test case consists of two lines: the first line contains one integer \(n\) (\(1 \le n \le 4 \cdot 10^5\)) — the number of figures in the set (and the number of days); the second line contains a string \(s\) (\(|s| = n\), each \(s_i\) is either 0 or 1). If Monocarp can visit the shop on the \(i\)-th day, then \(s_i\) is 1; otherwise, \(s_i\) is 0. Additional constraints on the input: in each test case, \(s_n\) is 1, so Monocarp is always able to buy all figures during the \(n\)-th day; the sum of \(n\) over all test cases does not exceed \(4 \cdot 10^5\).
For each test case, print one integer — the minimum amount of money Monocarp has to spend.
In the first test case, Monocarp buys the \(1\)-st figure on the \(1\)-st day and spends \(1\) coin.In the second test case, Monocarp can buy the \(1\)-st and the \(3\)-rd figure on the \(3\)-rd day, the \(2\)-nd and the \(4\)-th figure on the \(4\)-th day, and the \(5\)-th and the \(6\)-th figure on the \(6\)-th day. Then, he will spend \(1+2+5=8\) coins. In the third test case, Monocarp can buy the \(2\)-nd and the \(3\)-rd figure on the \(3\)-rd day, and all other figures on the \(7\)-th day. Then, he will spend \(1+2+4+5+6 = 18\) coins.
Input: 411610110171110001511111 | Output: 1 8 18 6
Medium
6
920
657
90
20
5
B
5B
B. Center Alignment
1,200
implementation; strings
Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck!
The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.
Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.
Input: This isCodeforcesBetaRound5 | Output: ************* This is ** **Codeforces** Beta ** Round ** 5 *************
Easy
2
293
300
476
0
1,009
B
1009B
B. Minimum Ternary String
1,400
greedy; implementation
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace ""01"" with ""10"" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace ""12"" with ""21"" or vice versa).For example, for string ""010210"" we can perform the following moves: ""010210"" \(\rightarrow\) ""100210""; ""010210"" \(\rightarrow\) ""001210""; ""010210"" \(\rightarrow\) ""010120""; ""010210"" \(\rightarrow\) ""010201"". Note than you cannot swap ""02"" \(\rightarrow\) ""20"" and vice versa. You cannot perform any other operations with the given string excluding described above.You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).String \(a\) is lexicographically less than string \(b\) (if strings \(a\) and \(b\) have the same length) if there exists some position \(i\) (\(1 \le i \le |a|\), where \(|s|\) is the length of the string \(s\)) such that for every \(j < i\) holds \(a_j = b_j\), and \(a_i < b_i\).
The first line of the input contains the string \(s\) consisting only of characters '0', '1' and '2', its length is between \(1\) and \(10^5\) (inclusive).
Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Input: 100210 | Output: 001120
Easy
2
1,123
155
165
10
87
B
87B
B. Vasya and Types
1,800
implementation; strings
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.There is a very powerful system of pointers on &K* — you can add an asterisk to the right of the existing type X — that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of X, which is a pointer, you can add an ampersand — that will result in a type &X, to which refers X. That is called a dereference operation.The &K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof. The operator ""typedef A B"" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**. The operator ""typeof A"" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T * is always equal to T.Note, that the operators are executed consecutively one by one. If we have two operators ""typedef &void a"" and ""typedef a* b"", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
The first line contains an integer n (1 ≤ n ≤ 100) — the number of operators. Then follow n lines with operators. Each operator is of one of two types: either ""typedef A B"", or ""typeof A"". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
For every typeof operator print on the single line the answer to that operator — the type that the given operator returned.
Let's look at the second sample.After the first two queries typedef the b type is equivalent to void*, and c — to void**.The next query typedef redefines b — it is now equal to &b = &void* = void. At that, the c type doesn't change.After that the c type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.Then the b type is again redefined as &void = errtype. Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.
Input: 5typedef void* ptvtypeof ptvtypedef &&ptv nodetypeof nodetypeof &ptv | Output: void*errtypevoid
Medium
2
2,472
590
123
0
140
C
140C
C. New Year Snowmen
1,800
binary search; data structures; greedy
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
Input: 71 2 3 4 5 6 7 | Output: 23 2 16 5 4
Medium
3
580
190
393
1
1,801
F
1801F
F. Another n-dimensional chocolate bar
2,700
dp; math; meet-in-the-middle; number theory
Mom bought the boy Vasya a \(n\)-dimensional chocolate bar, which is a \(n\)-dimensional cube with the length of each side equal to \(1\). The chocolate is planned to be divided into slices. According to the \(i\)th dimension, it can be divided by hyperplanes into \(a_i\) equal parts. Thus, the chocolate is divided in total into \(a_1 \cdot a_2 \cdot a_3 \cdot \ldots \cdot a_n\) slices, each slice has a length of \(i\)-th dimension equal to \(\frac{1}{a_i}\), respectively, the volume of each slice is \(\frac{1}{a_1 a_2 \cdots a_n}\).Vasya and his friends want to cut a chocolate bar to get at least \(k\) pieces, while Vasya wants to maximize the volume of the smallest of them. It is possible to cut the chocolate bar only at the junction of the lobules, and each incision must pass through the entire chocolate bar along some hyperplane involved in the formation of lobules. Only after making all the cuts, Vasya disassembles the chocolate into pieces.More formally, Vasya wants to choose the numbers \(b_1, b_2, \dots, b_n\) (\(1 \le b_i \le a_i\)) — the number of parts into which Vasya will cut the chocolate bar along each dimension. The condition \(b_1 \cdot b_2 \cdot \ldots \cdot b_n \ge k\) must be met to get at least \(k\) pieces after all cuts. It can be noted that with optimal cutting with such parameters, the minimum piece will contain \(\lfloor \frac{a_1}{b_1} \rfloor \dotsm \lfloor \frac{a_n}{b_n} \rfloor\) slices, and its volume will be equal to \(\lfloor \frac{a_1}{b_1} \rfloor \dotsm \lfloor \frac{a_n}{b_n} \rfloor \cdot \frac{1}{a_1 a_2 \cdots a_n}\).Vasya wants to get the maximum possible value of the volume of the minimum piece multiplied by \(k\), that is, he wants to maximize the number of \(\lfloor \frac{a_1}{b_1} \rfloor \dotsm \lfloor \frac{a_n}{b_n} \rfloor \cdot \frac{1}{a_1 a_2 \cdots a_n} \cdot k\). Help him with this.
The first line contains two integers \(n\) and \(k\) \((1 \le n \le 100\), \(1 \le k \le 10^7)\) — the dimension of the chocolate bar, and how many parts it needs to be divided into.The second line contains \(n\) integers \(a_1,\ a_2,\ \dots,\ a_n\) \((1 \le a_i \le 10^7)\) — the number of pieces on which the chocolate is placed along each of the dimensions.
Print one number — the maximum possible volume of the smallest of the obtained pieces, multiplied by \(k\), with an absolute or relative error of no more than \(10^{-9}\).If it is impossible to cut a chocolate bar into at least \(k\) pieces under the given restrictions, output \(0\).
In the first example, a one – dimensional chocolate bar can be divided as follows: Then the answer will be \(\frac{2}{5} \cdot 2 = 0.8\)In the second example, the chocolate bar can be cut as follows:Then the answer will be \(\frac{2}{5} \cdot \frac{3}{10} \cdot 6 = 0.72\)In the third example, the chocolate bar can be cut as follows: Then the answer will be \(\frac{2}{4} \cdot \frac{1}{4} \cdot 7 = 0.875\)
Input: 1 2 5 | Output: 0.8
Master
4
1,868
360
284
18
290
A
290A
A. Mysterious strings
1,400
*special; implementation
The input contains a single integer a (1 ≤ a ≤ 40).
Output a single string.
Input: 2 | Output: Adams
Easy
2
0
51
23
2
1,899
C
1899C
C. Yarik and Array
1,100
dp; greedy; two pointers
A subarray is a continuous part of array.Yarik recently found an array \(a\) of \(n\) elements and became very interested in finding the maximum sum of a non empty subarray. However, Yarik doesn't like consecutive integers with the same parity, so the subarray he chooses must have alternating parities for adjacent elements.For example, \([1, 2, 3]\) is acceptable, but \([1, 2, 4]\) is not, as \(2\) and \(4\) are both even and adjacent.You need to help Yarik by finding the maximum sum of such a subarray.
The first line contains an integer \(t\) \((1 \le t \le 10^4)\) — number of test cases. Each test case is described as follows.The first line of each test case contains an integer \(n\) \((1 \le n \le 2 \cdot 10^5)\) — length of the array.The second line of each test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) \((-10^3 \le a_i \le 10^3)\) — elements of the array.It is guaranteed that the sum of \(n\) for all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output a single integer — the answer to the problem.
Input: 751 2 3 4 549 9 8 86-1 4 -1 0 5 -44-1 2 4 -31-10003101 -99 10120-10 5 -8 10 6 -10 7 9 -2 -6 7 2 -4 6 -1 7 -6 -7 4 1 | Output: 15 17 8 4 -1000 101 10
Easy
3
508
466
72
18
935
A
935A
A. Fafa and his Company
800
brute force; implementation
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.
The input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company.
Print a single integer representing the answer to the problem.
In the second sample Fafa has 3 ways: choose only 1 employee as a team leader with 9 employees under his responsibility. choose 2 employees as team leaders with 4 employees under the responsibility of each of them. choose 5 employees as team leaders with 1 employee under the responsibility of each of them.
Input: 2 | Output: 1
Beginner
2
1,014
126
62
9
1,575
E
1575E
E. Eye-Pleasing City Park Tour
2,600
data structures; trees
There is a city park represented as a tree with \(n\) attractions as its vertices and \(n - 1\) rails as its edges. The \(i\)-th attraction has happiness value \(a_i\).Each rail has a color. It is either black if \(t_i = 0\), or white if \(t_i = 1\). Black trains only operate on a black rail track, and white trains only operate on a white rail track. If you are previously on a black train and want to ride a white train, or you are previously on a white train and want to ride a black train, you need to use \(1\) ticket.The path of a tour must be a simple path — it must not visit an attraction more than once. You do not need a ticket the first time you board a train. You only have \(k\) tickets, meaning you can only switch train types at most \(k\) times. In particular, you do not need a ticket to go through a path consisting of one rail color.Define \(f(u, v)\) as the sum of happiness values of the attractions in the tour \((u, v)\), which is a simple path that starts at the \(u\)-th attraction and ends at the \(v\)-th attraction. Find the sum of \(f(u,v)\) for all valid tours \((u, v)\) (\(1 \leq u \leq v \leq n\)) that does not need more than \(k\) tickets, modulo \(10^9 + 7\).
The first line contains two integers \(n\) and \(k\) (\(2 \leq n \leq 2 \cdot 10^5\), \(0 \leq k \leq n-1\)) — the number of attractions in the city park and the number of tickets you have.The second line contains \(n\) integers \(a_1, a_2,\ldots, a_n\) (\(0 \leq a_i \leq 10^9\)) — the happiness value of each attraction.The \(i\)-th of the next \(n - 1\) lines contains three integers \(u_i\), \(v_i\), and \(t_i\) (\(1 \leq u_i, v_i \leq n\), \(0 \leq t_i \leq 1\)) — an edge between vertices \(u_i\) and \(v_i\) with color \(t_i\). The given edges form a tree.
Output an integer denoting the total happiness value for all valid tours \((u, v)\) (\(1 \leq u \leq v \leq n\)), modulo \(10^9 + 7\).
Input: 5 0 1 3 2 6 4 1 2 1 1 4 0 3 2 1 2 5 0 | Output: 45
Expert
2
1,197
564
134
15
244
A
244A
A. Dividing Orange
900
implementation
One day Ms Swan bought an orange in a shop. The orange consisted of n·k segments, numbered with integers from 1 to n·k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1 ≤ i ≤ k) child wrote the number ai (1 ≤ ai ≤ n·k). All numbers ai accidentally turned out to be different.Now the children wonder, how to divide the orange so as to meet these conditions: each child gets exactly n orange segments; the i-th child gets the segment with number ai for sure; no segment goes to two children simultaneously. Help the children, divide the orange and fulfill the requirements, described above.
The first line contains two integers n, k (1 ≤ n, k ≤ 30). The second line contains k space-separated integers a1, a2, ..., ak (1 ≤ ai ≤ n·k), where ai is the number of the orange segment that the i-th child would like to get.It is guaranteed that all numbers ai are distinct.
Print exactly n·k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces.You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.
Input: 2 24 1 | Output: 2 4 1 3
Beginner
1
803
276
425
2
60
D
60D
D. Savior
2,500
brute force; dsu; math
Misha decided to help Pasha and Akim be friends again. He had a cunning plan — to destroy all the laughy mushrooms. He knows that the laughy mushrooms can easily burst when they laugh. Mushrooms grow on the lawns. There are a[t] mushrooms on the t-th lawn.Misha knows that the lawns where the mushrooms grow have a unique ability. A lawn (say, i) can transfer laugh to other lawn (say, j) if there exists an integer (say, b) such, that some permutation of numbers a[i], a[j] and b is a beautiful triple (i ≠ j). A beautiful triple is such three pairwise coprime numbers x, y, z, which satisfy the following condition: x2 + y2 = z2.Misha wants to know on which minimal number of lawns he should laugh for all the laughy mushrooms to burst.
The first line contains one integer n (1 ≤ n ≤ 106) which is the number of lawns. The next line contains n integers ai which are the number of mushrooms on the i-lawn (1 ≤ ai ≤ 107). All the numbers are different.
Print a single number — the minimal number of lawns on which Misha should laugh for all the mushrooms to burst.
Input: 12 | Output: 1
Expert
3
738
213
111
0
2,039
F1
2039F1
F1. Shohag Loves Counting (Easy Version)
2,800
combinatorics; dp; math; number theory
This is the easy version of the problem. The only differences between the two versions of this problem are the constraints on \(t\), \(m\), and the sum of \(m\). You can only make hacks if both versions of the problem are solved.For an integer array \(a\) of length \(n\), define \(f(k)\) as the greatest common divisor (GCD) of the maximum values of all subarrays\(^{\text{∗}}\) of length \(k\). For example, if the array is \([2, 1, 4, 6, 2]\), then \(f(3) = \operatorname{gcd}(\operatorname{max}([2, 1, 4]), \operatorname{max}([1, 4, 6]), \operatorname{max}([4, 6, 2])) = \operatorname{gcd}(4, 6, 6) = 2\).An array is good if \(f(i) \neq f(j)\) is satisfied over all pairs \(1 \le i \lt j \le n\).Shohag has an integer \(m\). Help him count the number, modulo \(998\,244\,353\), of non-empty good arrays of arbitrary length such that each element of the array is an integer from \(1\) to \(m\).\(^{\text{∗}}\)An array \(d\) is a subarray of an array \(c\) if \(d\) can be obtained from \(c\) by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.The first and only line of each test case contains an integer \(m\) (\(1 \le m \le 10^5\)).It is guaranteed that the sum of \(m\) over all test cases does not exceed \(10^5\).
For each test case, output an integer — the number of valid arrays modulo \(998\,244\,353\).
In the first test case, the valid arrays are \([1]\), \([1, 2]\), \([2]\), and \([2, 1]\).In the second test case, there are a total of \(29\) valid arrays. In particular, the array \([2, 1, 4]\) with length \(n = 3\) is valid because all elements are from \(1\) to \(m = 5\) and \(f(1)\), \(f(2)\) and \(f(n = 3)\) all are distinct: \(f(1) = \operatorname{gcd}(\operatorname{max}([2]), \operatorname{max}([1]), \operatorname{max}([4])) = \operatorname{gcd}(2, 1, 4) = 1.\) \(f(2) = \operatorname{gcd}(\operatorname{max}([2, 1]), \operatorname{max}([1, 4])) = \operatorname{gcd}(2, 4) = 2.\) \(f(3) = \operatorname{gcd}(\operatorname{max}([2, 1, 4])) = \operatorname{gcd}(4) = 4.\)
Input: 3259 | Output: 4 29 165
Master
4
1,128
272
92
20
547
A
547A
A. Mike and Frog
2,200
brute force; greedy; implementation; math
Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar. So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become and height of Abol will become where x1, y1, x2 and y2 are some integer numbers and denotes the remainder of a modulo b.Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is a1 and height of Abol is a2.Mike has asked you for your help. Calculate the minimum time or say it will never happen.
The first line of input contains integer m (2 ≤ m ≤ 106).The second line of input contains integers h1 and a1 (0 ≤ h1, a1 < m).The third line of input contains integers x1 and y1 (0 ≤ x1, y1 < m).The fourth line of input contains integers h2 and a2 (0 ≤ h2, a2 < m).The fifth line of input contains integers x2 and y2 (0 ≤ x2, y2 < m).It is guaranteed that h1 ≠ a1 and h2 ≠ a2.
Print the minimum number of seconds until Xaniar reaches height a1 and Abol reaches height a2 or print -1 otherwise.
In the first sample, heights sequences are following:Xaniar: Abol:
Input: 54 21 10 12 3 | Output: 3
Hard
4
643
377
116
5
164
E
164E
E. Polycarpus and Tasks
3,100
Polycarpus has many tasks. Each task is characterized by three integers li, ri and ti. Three integers (li, ri, ti) mean that to perform task i, one needs to choose an integer si (li ≤ si; si + ti - 1 ≤ ri), then the task will be carried out continuously for ti units of time, starting at time si and up to time si + ti - 1, inclusive. In other words, a task is performed for a continuous period of time lasting ti, should be started no earlier than li, and completed no later than ri.Polycarpus's tasks have a surprising property: for any task j, k (with j < k) lj < lk and rj < rk.Let's suppose there is an ordered set of tasks A, containing |A| tasks. We'll assume that aj = (lj, rj, tj) (1 ≤ j ≤ |A|). Also, we'll assume that the tasks are ordered by increasing lj with the increase in number.Let's consider the following recursive function f, whose argument is an ordered set of tasks A, and the result is an integer. The function f(A) is defined by the greedy algorithm, which is described below in a pseudo-language of programming. Step 1. , ans = 0. Step 2. We consider all tasks in the order of increasing of their numbers in the set A. Lets define the current task counter i = 0. Step 3. Consider the next task: i = i + 1. If i > |A| fulfilled, then go to the 8 step. Step 4. If you can get the task done starting at time si = max(ans + 1, li), then do the task i: si = max(ans + 1, li), ans = si + ti - 1, . Go to the next task (step 3). Step 5. Otherwise, find such task , that first, task ai can be done at time si = max, and secondly, the value of is positive and takes the maximum value among all bk that satisfy the first condition. If you can choose multiple tasks as bk, choose the one with the maximum number in set A. Step 6. If you managed to choose task bk, then , . Go to the next task (step 3). Step 7. If you didn't manage to choose task bk, then skip task i. Go to the next task (step 3). Step 8. Return ans as a result of executing f(A). Polycarpus got entangled in all these formulas and definitions, so he asked you to simulate the execution of the function f, calculate the value of f(A).
The first line of the input contains a single integer n (1 ≤ n ≤ 105) — the number of tasks in set A. Then n lines describe the tasks. The i-th line contains three space-separated integers li, ri, ti (1 ≤ li ≤ ri ≤ 109, 1 ≤ ti ≤ ri - li + 1) — the description of the i-th task.It is guaranteed that for any tasks j, k (considering that j < k) the following is true: lj < lk and rj < rk.
For each task i print a single integer — the result of processing task i on the i-th iteration of the cycle (step 3) in function f(A). In the i-th line print: 0 — if you managed to add task i on step 4. -1 — if you didn't manage to add or replace task i (step 7). resi (1 ≤ resi ≤ n) — if you managed to replace the task (step 6): resi equals the task number (in set A), that should be chosen as bk and replaced by task ai.
Input: 51 8 52 9 33 10 38 11 411 12 2 | Output: 0 0 1 0 -1
Master
0
2,117
386
423
1
374
D
374D
D. Inna and Sequence
2,000
binary search; data structures; dp; trees
Dima's spent much time thinking what present to give to Inna and gave her an empty sequence w. Now they want to fill sequence w with numbers zero and one. For that, they decided to play an amusing game. Before the game begins, Dima chooses m integers a1, a2, ..., am (1 ≤ a1 < a2 < ... < am). Then Inna and Dima start playing, that is, adding numbers to sequence w. Each new number they choose is added to the end of the sequence. At some moments of time Dima feels that the game is going to end too soon (and he wants to play with Inna as long as possible), so he hits a table hard with his fist. At that the a1-th, a2-th, a3-th, ..., ak-th numbers from the beginning simultaneously fall out of the sequence (the sequence gets k numbers less). Here k is such maximum number that value ak doesn't exceed the current length of the sequence. If number a1 is larger than the current length of w, then nothing falls out of the sequence.You are given the chronological sequence of events in the game. Each event is either adding a number to the end of sequence w or Dima's hit on the table. Calculate the sequence w after all these events happen.
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 106) showing how many events took place and how many numbers Dima chose.The next line contains m distinct integers ai (1 ≤ ai ≤ 106) sorted in the increasing order. Next n lines describe the events in the chronological order. Each line contains a single integer: -1, 0 or 1. Number -1 means that Dima hits the table. Number 0 means that Inna and Dima add number 0 to the end of the sequence. Number 1 means that Inna and Dima add number 1 to the end of the sequence.
In a single line print a sequence of numbers 0 and 1 — the elements of the sequence after all events happen. Print the elements of the sequence in the order from the beginning to the end of the sequence.If after all events the sequence ends up empty, print ""Poor stack!"".
Input: 10 31 3 6-11100-101-11 | Output: 011
Hard
4
1,141
536
273
3
1,360
B
1360B
B. Honest Coach
800
greedy; sortings
There are \(n\) athletes in front of you. Athletes are numbered from \(1\) to \(n\) from left to right. You know the strength of each athlete — the athlete number \(i\) has the strength \(s_i\).You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams \(A\) and \(B\) so that the value \(|\max(A) - \min(B)|\) is as small as possible, where \(\max(A)\) is the maximum strength of an athlete from team \(A\), and \(\min(B)\) is the minimum strength of an athlete from team \(B\).For example, if \(n=5\) and the strength of the athletes is \(s=[3, 1, 2, 6, 4]\), then one of the possible split into teams is: first team: \(A = [1, 2, 4]\), second team: \(B = [3, 6]\). In this case, the value \(|\max(A) - \min(B)|\) will be equal to \(|4-3|=1\). This example illustrates one of the ways of optimal split into two teams.Print the minimum value \(|\max(A) - \min(B)|\).
The first line contains an integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases in the input. Then \(t\) test cases follow.Each test case consists of two lines. The first line contains positive integer \(n\) (\(2 \le n \le 50\)) — number of athletes. The second line contains \(n\) positive integers \(s_1, s_2, \ldots, s_n\) (\(1 \le s_i \le 1000\)), where \(s_i\) — is the strength of the \(i\)-th athlete. Please note that \(s\) values may not be distinct.
For each test case print one integer — the minimum value of \(|\max(A) - \min(B)|\) with the optimal split of all athletes into two teams. Each of the athletes must be a member of exactly one of the two teams.
The first test case was explained in the statement. In the second test case, one of the optimal splits is \(A=[2, 1]\), \(B=[3, 2, 4, 3]\), so the answer is \(|2-2|=0\).
Input: 5 5 3 1 2 6 4 6 2 1 3 2 4 3 4 7 9 3 1 2 1 1000 3 100 150 200 | Output: 1 0 2 999 50
Beginner
2
1,128
470
209
13
1,619
G
1619G
G. Unusual Minesweeper
2,000
binary search; dfs and similar; dsu; greedy; sortings
Polycarp is very fond of playing the game Minesweeper. Recently he found a similar game and there are such rules.There are mines on the field, for each the coordinates of its location are known (\(x_i, y_i\)). Each mine has a lifetime in seconds, after which it will explode. After the explosion, the mine also detonates all mines vertically and horizontally at a distance of \(k\) (two perpendicular lines). As a result, we get an explosion on the field in the form of a ""plus"" symbol ('+'). Thus, one explosion can cause new explosions, and so on.Also, Polycarp can detonate anyone mine every second, starting from zero seconds. After that, a chain reaction of explosions also takes place. Mines explode instantly and also instantly detonate other mines according to the rules described above.Polycarp wants to set a new record and asks you to help him calculate in what minimum number of seconds all mines can be detonated.
The first line of the input contains an integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases in the test.An empty line is written in front of each test suite.Next comes a line that contains integers \(n\) and \(k\) (\(1 \le n \le 2 \cdot 10^5\), \(0 \le k \le 10^9\)) — the number of mines and the distance that hit by mines during the explosion, respectively.Then \(n\) lines follow, the \(i\)-th of which describes the \(x\) and \(y\) coordinates of the \(i\)-th mine and the time until its explosion (\(-10^9 \le x, y \le 10^9\), \(0 \le timer \le 10^9\)). It is guaranteed that all mines have different coordinates.It is guaranteed that the sum of the values \(n\) over all test cases in the test does not exceed \(2 \cdot 10^5\).
Print \(t\) lines, each of the lines must contain the answer to the corresponding set of input data — the minimum number of seconds it takes to explode all the mines.
Picture from examples First example: \(0\) second: we explode a mine at the cell \((2, 2)\), it does not detonate any other mine since \(k=0\). \(1\) second: we explode the mine at the cell \((0, 1)\), and the mine at the cell \((0, 0)\) explodes itself. \(2\) second: we explode the mine at the cell \((1, 1)\), and the mine at the cell \((1, 0)\) explodes itself.Second example: \(0\) second: we explode a mine at the cell \((2, 2)\) we get: \(1\) second: the mine at coordinate \((0, 0)\) explodes and since \(k=2\) the explosion detonates mines at the cells \((0, 1)\) and \((1, 0)\), and their explosions detonate the mine at the cell \((1, 1)\) and there are no mines left on the field.
Input: 3 5 0 0 0 1 0 1 4 1 0 2 1 1 3 2 2 9 5 2 0 0 1 0 1 4 1 0 2 1 1 3 2 2 9 6 1 1 -1 3 0 -1 9 0 1 7 -1 0 1 -1 1 9 -1 -1 7 | Output: 2 1 0
Hard
5
928
745
166
16
366
D
366D
D. Dima and Trap Graph
2,000
binary search; data structures; dfs and similar; dsu; shortest paths; two pointers
Dima and Inna love spending time together. The problem is, Seryozha isn't too enthusiastic to leave his room for some reason. But Dima and Inna love each other so much that they decided to get criminal...Dima constructed a trap graph. He shouted: ""Hey Seryozha, have a look at my cool graph!"" to get his roommate interested and kicked him into the first node.A trap graph is an undirected graph consisting of n nodes and m edges. For edge number k, Dima denoted a range of integers from lk to rk (lk ≤ rk). In order to get out of the trap graph, Seryozha initially (before starting his movements) should pick some integer (let's call it x), then Seryozha must go some way from the starting node with number 1 to the final node with number n. At that, Seryozha can go along edge k only if lk ≤ x ≤ rk.Seryozha is a mathematician. He defined the loyalty of some path from the 1-st node to the n-th one as the number of integers x, such that if he initially chooses one of them, he passes the whole path. Help Seryozha find the path of maximum loyalty and return to his room as quickly as possible!
The first line of the input contains two integers n and m (2 ≤ n ≤ 103, 0 ≤ m ≤ 3·103). Then follow m lines describing the edges. Each line contains four integers ak, bk, lk and rk (1 ≤ ak, bk ≤ n, 1 ≤ lk ≤ rk ≤ 106). The numbers mean that in the trap graph the k-th edge connects nodes ak and bk, this edge corresponds to the range of integers from lk to rk.Note that the given graph can have loops and multiple edges.
In a single line of the output print an integer — the maximum loyalty among all paths from the first node to the n-th one. If such paths do not exist or the maximum loyalty equals 0, print in a single line ""Nice work, Dima!"" without the quotes.
Explanation of the first example.Overall, we have 2 ways to get from node 1 to node 4: first you must go along the edge 1-2 with range [1-10], then along one of the two edges 2-4. One of them contains range [3-5], that is, we can pass through with numbers 3, 4, 5. So the loyalty of such path is 3.If we go along edge 2-4 with range [2-7], then we can pass through with numbers 2, 3, 4, 5, 6, 7. The loyalty is 6. That is the answer.The edge 1-2 have no influence on the answer because its range includes both ranges of the following edges.
Input: 4 41 2 1 102 4 3 51 3 1 52 4 2 7 | Output: 6
Hard
6
1,097
419
246
3
412
D
412D
D. Giving Awards
2,000
dfs and similar
The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one for the hard work this month. The CEO knows who owes money to whom. And he also understands that if he invites person x to his office for a reward, and then immediately invite person y, who has lent some money to person x, then they can meet. Of course, in such a situation, the joy of person x from his brand new money reward will be much less. Therefore, the R1 CEO decided to invite the staff in such an order that the described situation will not happen for any pair of employees invited one after another.However, there are a lot of employees in the company, and the CEO doesn't have a lot of time. Therefore, the task has been assigned to you. Given the debt relationships between all the employees, determine in which order they should be invited to the office of the R1 company CEO, or determine that the described order does not exist.
The first line contains space-separated integers n and m — the number of employees in R1 and the number of debt relations. Each of the following m lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi), these integers indicate that the person number ai owes money to a person a number bi. Assume that all the employees are numbered from 1 to n.It is guaranteed that each pair of people p, q is mentioned in the input data at most once. In particular, the input data will not contain pairs p, q and q, p simultaneously.
Print -1 if the described order does not exist. Otherwise, print the permutation of n distinct integers. The first number should denote the number of the person who goes to the CEO office first, the second number denote the person who goes second and so on.If there are multiple correct orders, you are allowed to print any of them.
Input: 2 11 2 | Output: 2 1
Hard
1
1,162
540
332
4
571
D
571D
D. Campus
3,100
binary search; data structures; dsu; trees
Oscolcovo city has a campus consisting of n student dormitories, n universities and n military offices. Initially, the i-th dormitory belongs to the i-th university and is assigned to the i-th military office.Life goes on and the campus is continuously going through some changes. The changes can be of four types: University aj merges with university bj. After that all the dormitories that belonged to university bj are assigned to to university aj, and university bj disappears. Military office cj merges with military office dj. After that all the dormitories that were assigned to military office dj, are assigned to military office cj, and military office dj disappears. Students of university xj move in dormitories. Lets kxj is the number of dormitories that belong to this university at the time when the students move in. Then the number of students in each dormitory of university xj increases by kxj (note that the more dormitories belong to the university, the more students move in each dormitory of the university). Military office number yj conducts raids on all the dormitories assigned to it and takes all students from there. Thus, at each moment of time each dormitory is assigned to exactly one university and one military office. Initially, all the dormitory are empty.Your task is to process the changes that take place in the campus and answer the queries, how many people currently live in dormitory qj.
The first line contains two integers, n and m (1 ≤ n, m ≤ 5·105) — the number of dormitories and the number of queries, respectively.Next m lines contain the queries, each of them is given in one of the following formats: «U aj bj» — merging universities; «M cj dj» — merging military offices; «A xj» — students of university xj moving in the dormitories; «Z yj» — a raid in military office yj; «Q qj» — a query asking the number of people in dormitory qj. All the numbers in the queries are positive integers and do not exceed n. It is guaranteed that at the moment of the query the universities and military offices, that are present in the query, exist.
In the i-th line print the answer to the i-th query asking the number of people in the dormitory.
Consider the first sample test: In the first query university 1 owns only dormitory 1, so after the query dormitory 1 will have 1 student. After the third query university 1 owns dormitories 1 and 2. The fourth query increases by 2 the number of students living in dormitories 1 and 2 that belong to university number 1. After that 3 students live in the first dormitory and 2 students live in the second dormitory. At the fifth query the number of students living in dormitory 1, assigned to the military office 1, becomes zero.
Input: 2 7A 1Q 1U 1 2A 1Z 1Q 1Q 2 | Output: 102
Master
4
1,428
656
97
5
1,649
A
1649A
A. Game
800
implementation
You are playing a very popular computer game. The next level consists of \(n\) consecutive locations, numbered from \(1\) to \(n\), each of them containing either land or water. It is known that the first and last locations contain land, and for completing the level you have to move from the first location to the last. Also, if you become inside a location with water, you will die, so you can only move between locations with land.You can jump between adjacent locations for free, as well as no more than once jump from any location with land \(i\) to any location with land \(i + x\), spending \(x\) coins (\(x \geq 0\)).Your task is to spend the minimum possible number of coins to move from the first location to the last one.Note that this is always possible since both the first and last locations are the land locations.
There are several test cases in the input data. The first line contains a single integer \(t\) (\(1 \leq t \leq 100\)) — the number of test cases. This is followed by the test cases description.The first line of each test case contains one integer \(n\) (\(2 \leq n \leq 100\)) — the number of locations.The second line of the test case contains a sequence of integers \(a_1, a_2, \ldots, a_n\) (\(0 \leq a_i \leq 1\)), where \(a_i = 1\) means that the \(i\)-th location is the location with land, and \(a_i = 0\) means that the \(i\)-th location is the location with water. It is guaranteed that \(a_1 = 1\) and \(a_n = 1\).
For each test case print a single integer — the answer to the problem.
In the first test case, it is enough to make one free jump from the first location to the second one, which is also the last one, so the answer is \(0\).In the second test case, the only way to move from the first location to the last one is to jump between them, which will cost \(4\) coins.In the third test case, you can jump from the first location to the third for \(2\) coins, and then jump to the fourth location for free, so the answer is \(2\). It can be shown that this is the optimal way.
Input: 321 151 0 1 0 141 0 1 1 | Output: 0 4 2
Beginner
1
829
625
70
16
1,874
C
1874C
C. Jellyfish and EVA
2,300
dp; graphs; greedy; math; probabilities
Monsters have invaded the town again! Asuka invites her good friend, Jellyfish, to drive EVA with her.There are \(n\) cities in the town. All the monsters are in city \(n\). Jellyfish and Asuka are currently in city \(1\) and need to move to city \(n\) to defeat the monsters.There are \(m\) roads. The \(i\)-th road allows one to travel from city \(a_i\) to city \(b_i\). All the roads are directed. That is, one cannot travel from city \(b_i\) to \(a_i\) using the \(i\)-th road. Interestingly, all roads satisfy \(a_i<b_i\).Driving EVA requires two people to work together. However, Asuka and Jellyfish have not done any training together before.Suppose that EVA is currently in city \(u\). Jellyfish and Asuka will both choose an undestroyed road that starts at city \(u\). Suppose Jellyfish and Asuka choose roads that end at cities \(v_1\) and \(v_2\) respectively. If \(v_1 = v_2\), EVA moves to city \(v_1\) successfully. Otherwise, EVA stays in city \(u\) and both roads that they have chosen will be destroyed.It is possible that EVA is currently in city \(u\) (\(u \neq n\)) and there are no undestroyed roads that start at city \(u\). In that case, the mission will be a failure. Otherwise, if they reach city \(n\) in the end, the mission is considered a success.Every time they choose the roads, Jellyfish knows that Asuka will choose a road randomly. Now, Jellyfish wants to know, if she chooses the roads optimally, what is the maximum probability of the mission being successful.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \leq t \leq 2000\)). The description of the test cases follows.The first line of each test case contains two integers, \(n\) and \(m\) (\(2 \leq n \leq 5000\), \(0 \leq m \leq \min(\frac{n(n-1)}{2}, 2 \cdot 10^5)\)) — the number of the cities and the number of the roads.In the following \(m\) lines of each test case, each line contains two integers \(a\) and \(b\) (\(1 \leq a < b \leq n\)) — representing a road from city \(a\) to city \(b\).It is guaranteed that for each test case, each road appears at most once.It is guaranteed that the sum of \(n\) over all test cases will not exceed \(5000\) and that the sum of \(m\) over all test cases will not exceed \(2 \cdot 10^5\).
Output the maximum probability of the mission being successful if Jellyfish chooses the roads optimally.Your answer will be accepted if the absolute or relative error does not exceed \(10^{-9}\). Formally, let your answer be \(a\), and the jury's answer be \(b\). Your answer is considered correct if \(\frac{|a-b|}{\max(1,|b|)} \leq 10^{-9}\).
In the first test case, Jellyfish will choose \(v_1=3\), and Asuka will choose \(v_2=2\) with a possibility of \(0.5\) and \(v_2=3\) with a possibility of \(0.5\). The mission is considered a success with a possibility of \(0.5\).
Input: 33 21 21 37 81 21 31 41 52 63 64 66 710 201 21 31 41 51 62 62 72 82 93 43 73 83 104 64 84 106 107 87 97 10 | Output: 0.500000000000 0.625000000000 0.491666666667
Expert
5
1,496
781
344
18
2,014
D
2014D
D. Robert Hood and Mrs Hood
1,400
brute force; data structures; greedy; sortings
Impress thy brother, yet fret not thy mother.Robin's brother and mother are visiting, and Robin gets to choose the start day for each visitor.All days are numbered from \(1\) to \(n\). Visitors stay for \(d\) continuous days, all of those \(d\) days must be between day \(1\) and \(n\) inclusive.Robin has a total of \(k\) risky 'jobs' planned. The \(i\)-th job takes place between days \(l_i\) and \(r_i\) inclusive, for \(1 \le i \le k\). If a job takes place on any of the \(d\) days, the visit overlaps with this job (the length of overlap is unimportant).Robin wants his brother's visit to overlap with the maximum number of distinct jobs, and his mother's the minimum.Find suitable start days for the visits of Robin's brother and mother. If there are multiple suitable days, choose the earliest one.
The first line of the input contains a single integer \(t\) (\(1\leq t \leq 10^4\)) — the number of test cases.The first line of each test case consists of three integers \(n\), \(d\), \(k\) (\(1 \le n \le 10^5, 1 \le d, k \le n\)) — the number of total days, duration of the visits, and the number of jobs. Then follow \(k\) lines of each test case, each with two integers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le n\)) — the start and end day of each job.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output two integers, the best starting days of Robin's brother and mother respectively. Both visits must fit between day \(1\) and \(n\) inclusive.
In the first test case, the only job fills all \(2\) days, both should visit on day \(1\).In the second test case, day \(2\) overlaps with \(2\) jobs and day \(1\) overlaps with only \(1\).In the third test case, Robert visits for days \([1,2]\), Mrs. Hood visits for days \([4,5]\).
Input: 62 1 11 24 1 21 22 47 2 31 21 36 75 1 21 23 59 2 12 89 2 47 94 81 32 3 | Output: 1 1 2 1 1 4 1 1 1 1 3 4
Easy
4
806
552
167
20
207
B1
207B1
B1. Military Trainings
1,600
The Smart Beaver from ABBYY started cooperating with the Ministry of Defence. Now they train soldiers to move armoured columns. The training involves testing a new type of tanks that can transmit information. To test the new type of tanks, the training has a special exercise, its essence is as follows.Initially, the column consists of n tanks sequentially numbered from 1 to n in the order of position in the column from its beginning to its end. During the whole exercise, exactly n messages must be transferred from the beginning of the column to its end.Transferring one message is as follows. The tank that goes first in the column transmits the message to some tank in the column. The tank which received the message sends it further down the column. The process is continued until the last tank receives the message. It is possible that not all tanks in the column will receive the message — it is important that the last tank in the column should receive the message.After the last tank (tank number n) receives the message, it moves to the beginning of the column and sends another message to the end of the column in the same manner. When the message reaches the last tank (tank number n - 1), that tank moves to the beginning of the column and sends the next message to the end of the column, and so on. Thus, the exercise is completed when the tanks in the column return to their original order, that is, immediately after tank number 1 moves to the beginning of the column.If the tanks were initially placed in the column in the order 1, 2, ..., n, then after the first message their order changes to n, 1, ..., n - 1, after the second message it changes to n - 1, n, 1, ..., n - 2, and so on.The tanks are constructed in a very peculiar way. The tank with number i is characterized by one integer ai, which is called the message receiving radius of this tank.Transferring a message between two tanks takes one second, however, not always one tank can transmit a message to another one. Let's consider two tanks in the column such that the first of them is the i-th in the column counting from the beginning, and the second one is the j-th in the column, and suppose the second tank has number x. Then the first tank can transmit a message to the second tank if i < j and i ≥ j - ax.The Ministry of Defense (and soon the Smart Beaver) faced the question of how to organize the training efficiently. The exercise should be finished as quickly as possible. We'll neglect the time that the tanks spend on moving along the column, since improving the tanks' speed is not a priority for this training.You are given the number of tanks, as well as the message receiving radii of all tanks. You must help the Smart Beaver and organize the transferring of messages in a way that makes the total transmission time of all messages as small as possible.
The first line contains integer n — the number of tanks in the column. Each of the next n lines contains one integer ai (1 ≤ ai ≤ 250000, 1 ≤ i ≤ n) — the message receiving radii of the tanks in the order from tank 1 to tank n (let us remind you that initially the tanks are located in the column in ascending order of their numbers).To get the full points for the first group of tests it is sufficient to solve the problem with 2 ≤ n ≤ 300.To get the full points for the second group of tests it is sufficient to solve the problem with 2 ≤ n ≤ 10000.To get the full points for the third group of tests it is sufficient to solve the problem with 2 ≤ n ≤ 250000.
Print a single integer — the minimum possible total time of transmitting the messages.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.
In the first sample the original order of tanks is 1, 2, 3. The first tank sends a message to the second one, then the second tank sends it to the third one — it takes two seconds. The third tank moves to the beginning of the column and the order of tanks now is 3, 1, 2. The third tank sends a message to the first one, then the first one sends it to the second one — it takes two more seconds. The second tank moves to the beginning and the order of the tanks is now 2, 3, 1. With this arrangement, the second tank can immediately send a message to the first one, since the message receiving radius of the first tank is large enough — it takes one second. Finally, the tanks return to their original order 1, 2, 3. In total, the exercise takes 5 seconds.In the second sample, all five tanks are the same and sending a single message takes two seconds, so in total the exercise takes 10 seconds.
Input: 3211 | Output: 5
Medium
0
2,856
661
233
2
1,887
F
1887F
F. Minimum Segments
3,400
constructive algorithms
You had a sequence \(a_1, a_2, \ldots, a_n\) consisting of integers from \(1\) to \(n\), not necessarily distinct. For some unknown reason, you decided to calculate the following characteristic of the sequence: Let \(r_i\) (\(1 \le i \le n\)) be the smallest \(j \ge i\) such that on the subsegment \(a_i, a_{i+1}, \ldots, a_j\) all distinct numbers from the sequence \(a\) appear. More formally, for any \(k \in [1, n]\), there exists \(l \in [i, j]\) such that \(a_k = a_l\). If such \(j\) does not exist, \(r_i\) is considered to be equal to \(n+1\). The characteristic of the sequence \(a\) is defined as the sequence \(r_1, r_2, \ldots, r_n\). Unfortunately, the sequence \(a\) got lost, but you still have its characteristic \(r\). You want to reconstruct any sequence \(a\) that matches the characteristic, or determine that there is an error in the characteristic and such a sequence does not exist.
Each test consist 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 test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) — the length of the lost sequence \(a\).The second line of each test case contains \(n\) integers \(r_1, r_2, \ldots, r_n\) (\(i \le r_i \le n+1\)) — the characteristic of the lost sequence \(a\). 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 following: If there is no sequence \(a\) with the characteristic \(r\), print ""No"". Otherwise, print ""Yes"" on the first line, and on the second line, print any sequence of integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le n\)) that matches the characteristic \(r\). You can output ""YES"" and ""NO"" in any case (for example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as a positive answer).
In the first test case, the sequence \(a = [1, 2, 1]\) is suitable. The integers \(1\) and \(2\) appear on the subsegments \([1, 2]\) and \([2, 3]\).In the second test case, it can be proved that there is no suitable sequence \(a\).
Input: 532 3 452 3 5 4 61131 3 483 6 6 6 8 9 9 9 | Output: Yes 1 2 1 No Yes 1 No Yes 1 3 5 3 5 1 1 3
Master
1
907
563
455
18
146
B
146B
B. Lucky Mask
1,300
brute force; 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 calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number.Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b.
The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky.
In the only line print a single number — the number c that is sought by Petya.
Input: 1 7 | Output: 7
Easy
2
687
102
78
1
1,801
E
1801E
E. Gasoline prices
3,000
data structures; divide and conquer; dsu; hashing; trees
Berland — is a huge country consisting of \(n\) cities. The road network of Berland can be represented as a root tree, that is, there is only \(n - 1\) road in the country, and you can get from any city to any other exactly one way, if you do not visit any city twice. For the convenience of representing the country, for each city \(i\), the city \(p_i\) is fixed, equal to the first city to which you need to go from the city \(i\) to get to the city \(1\). In other words, the city \(p_i\) is equal to the ancestor of the city \(i\) if the tree is hung for the city \(1\).There is one gas station in each city of Berland. Gas stations have special pricing, and for each gas station there is a fixed range of prices for which they are ready to sell gasoline. A gas station in the city with the number \(i\) is ready to sell gasoline at any price from \(l_i\) to \(r_i\) inclusive.The King of Berland — is an exemplary family man, and for \(m\) years, two sons were born to him every year. The king's children have been involved in public affairs since early childhood, and at the end of each year they check the honesty of gasoline prices. From birth, the king's children, who are born in the year \(i\), are responsible for checking gasoline prices on the ways from the city of \(a_i\) to the city of \(b_i\) and from the city of \(c_i\) to the city of \(d_i\), respectively.The check is as follows: both children simultaneously start their journey from the cities \(a_i\) and \(c_i\), respectively. The first son of the king, born in the year \(i\), moves along the path from the city \(a_i\) to the city \(b_i\), and the second — from the city \(c_i\) to the city \(d_i\). Children check that the price of gasoline in the city of \(a_i\) coincides with the price of gasoline in the city of \(c_i\). Next, they check that the price of gasoline in the second city on the way from \(a_i\) to \(b_i\) coincides with the price in the second city on the way from \(c_i\) to \(d_i\). Then they repeat the same thing for a couple of third cities on their paths and so on. At the end, they check that the price of gasoline in the city of \(b_i\) coincides with the price of gasoline in the city of \(d_i\). It is guaranteed that the length of the path from the city \(a_i\) to the city \(b_i\) coincides with the length of the path from the city \(c_i\) to the city \(d_i\).Gas stations must strictly obey the laws, and therefore all checks of gasoline prices should not reveal violations. Help Berland gas stations find out how many ways they can set gasoline prices for \(m\) years. In other words, for each \(i\) from \(1\) to \(m\), calculate how many ways you can set gasoline prices at all gas stations so that after the birth of the first \(i\) pairs of the king's children, all their checks did not reveal violations, and at any gas station the price was in the acceptable price range. Since the number of such methods can be large, calculate the answer modulo \(10^9 + 7\).
The first line contains a single integer \(n\) (\(1 \le n \le 200\,000\)) — the number of cities in Berland.The second line contains \((n - 1)\) numbers \(p_2,\ p_3,\ p_4,\ \ldots,\ p_n\) (\(1 \le p_i \le n\)), where \(p_i\) denotes the number of the next city on the way from city \(i\) to city \(1\).In each of the following lines, two integers are given \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i < 10^9+7\)), specifying the acceptable range of prices at the gas station number \(i\).The following line contains a single integer \(m\) (\(1 \le m \le 200\,000\)) — the number of years during which two sons were born to the king.In each of the following \(m\) lines, four integers are given \(a_i\), \(b_i\), \(c_i\) and \(d_i\) (\(1 \le a_i, b_i, c_i, d_i \le n\)), specifying two paths on which the king's children will check gasoline prices, born in the year \(i\). It is guaranteed that the length of the path between the cities \(a_i\) and \(b_i\) is equal to the length of the path between the cities \(c_i\) and \(d_i\).
In \(m\) lines, print one number each. The number in the \(i\) line should be equal to the number of ways to set gasoline prices in all cities so that the king's children born in the years up to and including \(i\) do not reveal violations in inspections. Output the numbers modulo \(10^9 + 7\).
Consider the first example.After the birth of the first two sons, the prices in the cities of \(1\) and \(2\) should be equal. In total, there are 2 ways to choose the same gasoline price for the cities of \(1\) and \(2\) so that it falls within the acceptable price range for these cities. So, there are only ways to set gasoline prices: \(2 \cdot 3 \cdot 3 \cdot 1 = 18\).The second pair of sons will check the prices on the paths \(1 - 2\) and \(2 - 1\). This means that gasoline prices in the cities of \(1\) and \(2\) must match, which is already being done. Therefore, after the birth of the second pair of sons, the answer did not change in any way.The third pair of sons will check the prices on the tracks \(3 - 1 - 2 - 4\) and \(4 - 2 - 1 - 3\). Then the price of non-gasoline in the city of \(3\) should be equal to the price in the city of \(4\), and the price in the city of \(1\) should be equal to the price in the city of \(2\). Prices in the cities of \(1\) and \(2\) are already the same. For the cities of \(3\) and \(4\), there are 2 ways to choose the same price for gasoline so that it falls within the acceptable price range for these cities. So, there are only ways to set gasoline prices: \(2 \cdot 2 \cdot 1 = 4\). The fourth pair of sons will check the prices on the tracks \(3 - 1 - 2 - 4\) and \(3 - 1 - 2 - 5\). This means that the prices in the cities of \(4\) and \(5\) should be equal, and since the prices in the cities of \(3\) and \(4\) already coincide, then in the cities of \(3\), \(4\) and \(5\) there should be the same price for gasoline. The price of gasoline in the city of \(3\) should be no more than 3, and the price of gasoline in the city of \(5\) should be no less than 4. So, after the birth of the fourth pair of sons, there are no ways to set gasoline prices so that all checks are carried out and prices are in the required ranges.
Input: 5 1 1 2 2 2 4 1 3 1 3 2 4 4 4 4 1 1 2 2 1 2 2 1 3 4 4 3 3 4 3 5 | Output: 18 18 4 0
Master
5
2,978
1,027
295
18
1,323
A
1323A
A. Even Subset Sum Problem
800
brute force; dp; greedy; implementation
You are given an array \(a\) consisting of \(n\) positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by \(2\)) or determine that there is no such subset.Both the given array and required subset may contain equal values.
The first line contains a single integer \(t\) (\(1 \leq t \leq 100\)), number of test cases to solve. Descriptions of \(t\) test cases follow.A description of each test case consists of two lines. The first line contains a single integer \(n\) (\(1 \leq n \leq 100\)), length of array \(a\).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 100\)), elements of \(a\). The given array \(a\) can contain equal values (duplicates).
For each test case output \(-1\) if there is no such subset of elements. Otherwise output positive integer \(k\), number of elements in the required subset. Then output \(k\) distinct integers (\(1 \leq p_i \leq n\)), indexes of the chosen elements. If there are multiple solutions output any of them.
There are three test cases in the example.In the first test case, you can choose the subset consisting of only the second element. Its sum is \(4\) and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
Input: 3 3 1 4 3 1 15 2 3 5 | Output: 1 2 -1 2 1 2
Beginner
4
270
464
301
13
2,004
G
2004G
G. Substring Compression
3,200
data structures; dp; matrices
Let's define the operation of compressing a string \(t\), consisting of at least \(2\) digits from \(1\) to \(9\), as follows: split it into an even number of non-empty substrings — let these substrings be \(t_1, t_2, \dots, t_m\) (so, \(t = t_1 + t_2 + \dots + t_m\), where \(+\) is the concatenation operation); write the string \(t_2\) \(t_1\) times, then the string \(t_4\) \(t_3\) times, and so on. For example, for a string ""12345"", one could do the following: split it into (""1"", ""23"", ""4"", ""5""), and write ""235555"".Let the function \(f(t)\) for a string \(t\) return the minimum length of the string that can be obtained as a result of that process.You are given a string \(s\), consisting of \(n\) digits from \(1\) to \(9\), and an integer \(k\). Calculate the value of the function \(f\) for all contiguous substrings of \(s\) of length exactly \(k\).
The first line contains two integers \(n\) and \(k\) (\(2 \le k \le n \le 2 \cdot 10^5\)).The second line contains the string \(s\) (\(|s| = n\)), consisting only of digits from \(1\) to \(9\).
Output \(n - k + 1\) integers — \(f(s_{1,k}), f(s_{2,k+1}), \dots, f(s_{n - k + 1, n})\).
Input: 4 45999 | Output: 14
Master
3
874
193
89
20
630
I
630I
I. Parking Lot
1,700
combinatorics; math
To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes.The parking lot before the office consists of one line of (2n - 2) parking spaces. Unfortunately the total number of cars is greater than the parking lot capacity. Furthermore even amount of cars of each make is greater than the amount of parking spaces! That's why there are no free spaces on the parking lot ever.Looking on the straight line of cars the company CEO thought that parking lot would be more beautiful if it contained exactly n successive cars of the same make. Help the CEO determine the number of ways to fill the parking lot this way.
The only line of the input contains one integer n (3 ≤ n ≤ 30) — the amount of successive cars of the same make.
Output one integer — the number of ways to fill the parking lot by cars of four makes using the described way.
Let's denote car makes in the following way: A — Aston Martin, B — Bentley, M — Mercedes-Maybach, Z — Zaporozhets. For n = 3 there are the following appropriate ways to fill the parking lot: AAAB AAAM AAAZ ABBB AMMM AZZZ BBBA BBBM BBBZ BAAA BMMM BZZZ MMMA MMMB MMMZ MAAA MBBB MZZZ ZZZA ZZZB ZZZM ZAAA ZBBB ZMMMOriginally it was planned to grant sport cars of Ferrari, Lamborghini, Maserati and Bugatti makes but this idea was renounced because it is impossible to drive these cars having small road clearance on the worn-down roads of IT City.
Input: 3 | Output: 24
Medium
2
749
112
110
6
2,021
E2
2021E2
E2. Digital Village (Hard Version)
2,500
data structures; dp; dsu; graphs; math; trees
This is the hard version of the problem. In the three versions, the constraints on \(n\) and \(m\) are different. You can make hacks only if all the versions of the problem are solved.Pak Chanek is setting up internet connections for the village of Khuntien. The village can be represented as a connected simple graph with \(n\) houses and \(m\) internet cables connecting house \(u_i\) and house \(v_i\), each with a latency of \(w_i\).There are \(p\) houses that require internet. Pak Chanek can install servers in at most \(k\) of the houses. The houses that need internet will then be connected to one of the servers. However, since each cable has its latency, the latency experienced by house \(s_i\) requiring internet will be the maximum latency of the cables between that house and the server it is connected to.For each \(k = 1,2,\ldots,n\), help Pak Chanek determine the minimum total latency that can be achieved for all the houses requiring internet.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 2000\)). The description of the test cases follows.The first line of each test case contains three integers \(n\), \(m\), \(p\) (\(2 \le n \le 5000\); \(n-1 \le m \le 5000\); \(1 \le p \le n\)) — the number of houses, the number of cables, and the number of houses that need internet.The second line of each test case contains \(p\) integers \(s_1, s_2, \ldots, s_p\) (\(1 \le s_i \le n\)) — the houses that need internet. It is guaranteed that all elements of \(s\) are distinct. The \(i\)-th of the next \(m\) lines of each test case contains three integers \(u_i\), \(v_i\), and \(w_i\) (\(1 \le u_i < v_i \le n\); \(1 \le w_i \le 10^9\)) — the internet cable connecting house \(u_i\) and house \(v_i\) with latency of \(w_i\). It is guaranteed that the given edges form a connected simple graph.It is guaranteed that the sum of \(n\) and the sum of \(m\) do not exceed \(5000\).
For each test case, output \(n\) integers: the minimum total latency that can be achieved for all the houses requiring internet for each \(k = 1,2,\ldots,n\).
In the first test case for \(k=3\), a possible optimal solution is to install servers at vertices \(2\), \(6\) and \(8\) and obtain the following latency: \(\text{latency}(2) = 0\) \(\text{latency}(5) = \max(3, 5) = 5\) \(\text{latency}(6) = 0\) \(\text{latency}(8) = 0\) \(\text{latency}(9) = \max(2, 4) = 4\) So the total latency is \(9\).
Input: 29 8 52 5 6 8 91 2 11 3 23 4 104 5 34 6 51 7 107 8 47 9 23 3 23 11 2 12 3 31 3 2 | Output: 34 19 9 4 0 0 0 0 0 2 0 0
Expert
6
962
992
158
20
91
A
91A
A. Newspaper Headline
1,500
greedy; strings
A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is ""abc"". If we take two such headings and glue them one to the other one, we get ""abcabc"". If we erase the letters on positions 1 and 5, we get a word ""bcac"".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2?
The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1 ≤ |s1| ≤ 104, 1 ≤ |s2| ≤ 106).
If it is impossible to get the word s2 in the above-described manner, print ""-1"" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2.
Input: abcxyz | Output: -1
Medium
2
828
194
210
0
76
B
76B
B. Mice
2,100
greedy; two pointers
Modern researches has shown that a flock of hungry mice searching for a piece of cheese acts as follows: if there are several pieces of cheese then each mouse chooses the closest one. After that all mice start moving towards the chosen piece of cheese. When a mouse or several mice achieve the destination point and there is still a piece of cheese in it, they eat it and become well-fed. Each mice that reaches this point after that remains hungry. Moving speeds of all mice are equal.If there are several ways to choose closest pieces then mice will choose it in a way that would minimize the number of hungry mice. To check this theory scientists decided to conduct an experiment. They located N mice and M pieces of cheese on a cartesian plane where all mice are located on the line y = Y0 and all pieces of cheese — on another line y = Y1. To check the results of the experiment the scientists need a program which simulates the behavior of a flock of hungry mice.Write a program that computes the minimal number of mice which will remain hungry, i.e. without cheese.
The first line of the input contains four integer numbers N (1 ≤ N ≤ 105), M (0 ≤ M ≤ 105), Y0 (0 ≤ Y0 ≤ 107), Y1 (0 ≤ Y1 ≤ 107, Y0 ≠ Y1). The second line contains a strictly increasing sequence of N numbers — x coordinates of mice. Third line contains a strictly increasing sequence of M numbers — x coordinates of cheese. All coordinates are integers and do not exceed 107 by absolute value.
The only line of output should contain one number — the minimal number of mice which will remain without cheese.
All the three mice will choose the first piece of cheese. Second and third mice will eat this piece. The first one will remain hungry, because it was running towards the same piece, but it was late. The second piece of cheese will remain uneaten.
Input: 3 2 0 20 1 32 5 | Output: 1
Hard
2
1,072
393
112
0
123
C
123C
C. Brackets
2,300
combinatorics; dp; greedy
A two dimensional array is called a bracket array if each grid contains one of the two possible brackets — ""("" or "")"". A path through the two dimensional array cells is called monotonous if any two consecutive cells in the path are side-adjacent and each cell of the path is located below or to the right from the previous one. A two dimensional array whose size equals n × m is called a correct bracket array, if any string formed by writing out the brackets on some monotonous way from cell (1, 1) to cell (n, m) forms a correct bracket sequence. Let's define the operation of comparing two correct bracket arrays of equal size (a and b) like that. Let's consider a given two dimensional array of priorities (c) — a two dimensional array of same size, containing different integers from 1 to nm. Let's find such position (i, j) in the two dimensional array, that ai, j ≠ bi, j. If there are several such positions, let's choose the one where number ci, j is minimum. If ai, j = ""("", then a < b, otherwise a > b. If the position (i, j) is not found, then the arrays are considered equal.Your task is to find a k-th two dimensional correct bracket array. It is guaranteed that for the given sizes of n and m there will be no less than k two dimensional correct bracket arrays.
The first line contains integers n, m and k — the sizes of the array and the number of the sought correct bracket array (1 ≤ n, m ≤ 100, 1 ≤ k ≤ 1018). Then an array of priorities is given, n lines each containing m numbers, number pi, j shows the priority of character j in line i (1 ≤ pi, j ≤ nm, all pi, j are different).Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Print the k-th two dimensional correct bracket array.
In the first sample exists only one correct two-dimensional bracket array.In the second and in the third samples two arrays exist.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.
Input: 1 2 11 2 | Output: ()
Expert
3
1,282
476
53
1
119
D
119D
D. String Transformation
2,500
hashing; strings
Let s be a string whose length equals n. Its characters are numbered from 0 to n - 1, i and j are integers, 0 ≤ i < j < n. Let's define function f as follows:f(s, i, j) = s[i + 1... j - 1] + r(s[j... n - 1]) + r(s[0... i]).Here s[p... q] is a substring of string s, that starts in position p and ends in position q (inclusive); ""+"" is the string concatenation operator; r(x) is a string resulting from writing the characters of the x string in the reverse order. If j = i + 1, then the substring s[i + 1... j - 1] is considered empty.You are given two strings a and b. Find such values of i and j, that f(a, i, j) = b. Number i should be maximally possible. If for this i there exists several valid values of j, choose the minimal j.
The first two input lines are non-empty strings a and b correspondingly. Each string's length does not exceed 106 characters. The strings can contain any characters with ASCII codes from 32 to 126 inclusive.
Print two integers i, j — the answer to the problem. If no solution exists, print ""-1 -1"" (without the quotes).
Input: Die Polizei untersucht eine Straftat im IT-Bereich.untersucht eine Straftat.hciereB-TI mi ieziloP eiD | Output: 11 36
Expert
2
735
207
113
1
51
D
51D
D. Geometrical problem
2,200
implementation
Polycarp loves geometric progressions — he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression.In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ..., ak, where ai = c·bi - 1 for some real numbers c and b. For example, the sequences [2, -4, 8], [0, 0, 0, 0], [199] are geometric progressions and [0, 1, 2, 3] is not.Recently Polycarp has found a sequence and he can't classify it. Help him to do it. Determine whether it is a geometric progression. If it is not, check if it can become a geometric progression if an element is deleted from it.
The first line contains an integer n (1 ≤ n ≤ 105) — the number of elements in the given sequence. The second line contains the given sequence. The numbers are space-separated. All the elements of the given sequence are integers and their absolute value does not exceed 104.
Print 0, if the given sequence is a geometric progression. Otherwise, check if it is possible to make the sequence a geometric progression by deleting a single element. If it is possible, print 1. If it is impossible, print 2.
Input: 43 6 12 24 | Output: 0
Hard
1
711
274
226
0
1,721
A
1721A
A. Image
800
greedy; implementation
You have an image file of size \(2 \times 2\), consisting of \(4\) pixels. Each pixel can have one of \(26\) different colors, denoted by lowercase Latin letters.You want to recolor some of the pixels of the image so that all \(4\) pixels have the same color. In one move, you can choose no more than two pixels of the same color and paint them into some other color (if you choose two pixels, both should be painted into the same color).What is the minimum number of moves you have to make in order to fulfill your goal?
The first line contains one integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases.Each test case consists of two lines. Each of these lines contains two lowercase letters of Latin alphabet without any separators, denoting a row of pixels in the image.
For each test case, print one integer — the minimum number of moves you have to make so that all \(4\) pixels of the image have the same color.
Let's analyze the test cases of the example.In the first test case, you can paint the bottom left pixel and the top right pixel (which share the same color) into the color r, so all pixels have this color.In the second test case, two moves are enough: paint both top pixels, which have the same color c, into the color b; paint the bottom left pixel into the color b. In the third test case, all pixels already have the same color.In the fourth test case, you may leave any of the pixels unchanged, and paint all three other pixels into the color of that pixel in three moves.In the fifth test case, you can paint both top pixels into the color x.
Input: 5rbbrccwbaaaaabcdyyxx | Output: 1 2 0 3 1
Beginner
2
521
261
143
17
918
A
918A
A. Eleven
800
brute force; implementation
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters. Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the i-th letter of her name should be 'O' (uppercase) if i is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to n. Fibonacci sequence is the sequence f where f1 = 1, f2 = 1, fn = fn - 2 + fn - 1 (n > 2). As her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name.
The first and only line of input contains an integer n (1 ≤ n ≤ 1000).
Print Eleven's new name on the first and only line of output.
Input: 8 | Output: OOOoOooO
Beginner
2
694
70
61
9
460
A
460A
A. Vasya and Socks
900
brute force; implementation; math
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?
The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100), separated by a space.
Print a single integer — the answer to the problem.
In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two.In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day.
Input: 2 2 | Output: 3
Beginner
3
456
95
51
4
551
A
551A
A. GukiZ and Contest
800
brute force; implementation; sortings
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the rating of i-th student as ai. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings. He thinks that each student will take place equal to . In particular, if student A has rating strictly lower then student B, A will get the strictly better position than B, and if two students have equal ratings, they will share the same position. GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.
The first line contains integer n (1 ≤ n ≤ 2000), number of GukiZ's students. The second line contains n numbers a1, a2, ... an (1 ≤ ai ≤ 2000) where ai is the rating of i-th student (1 ≤ i ≤ n).
In a single line, print the position after the end of the contest for each of n students in the same order as they appear in the input.
In the first sample, students 2 and 3 are positioned first (there is no other student with higher rating), and student 1 is positioned third since there are two students with higher rating.In the second sample, first student is the only one on the contest.In the third sample, students 2 and 5 share the first position with highest rating, student 4 is next with third position, and students 1 and 3 are the last sharing fourth position.
Input: 31 3 3 | Output: 3 1 1
Beginner
3
961
195
135
5
995
C
995C
C. Leaving the Bar
2,300
brute force; data structures; geometry; greedy; math; sortings
For a vector \(\vec{v} = (x, y)\), define \(|v| = \sqrt{x^2 + y^2}\).Allen had a bit too much to drink at the bar, which is at the origin. There are \(n\) vectors \(\vec{v_1}, \vec{v_2}, \cdots, \vec{v_n}\). Allen will make \(n\) moves. As Allen's sense of direction is impaired, during the \(i\)-th move he will either move in the direction \(\vec{v_i}\) or \(-\vec{v_i}\). In other words, if his position is currently \(p = (x, y)\), he will either move to \(p + \vec{v_i}\) or \(p - \vec{v_i}\).Allen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position \(p\) satisfies \(|p| \le 1.5 \cdot 10^6\) so that he can stay safe.
The first line contains a single integer \(n\) (\(1 \le n \le 10^5\)) — the number of moves.Each of the following lines contains two space-separated integers \(x_i\) and \(y_i\), meaning that \(\vec{v_i} = (x_i, y_i)\). We have that \(|v_i| \le 10^6\) for all \(i\).
Output a single line containing \(n\) integers \(c_1, c_2, \cdots, c_n\), each of which is either \(1\) or \(-1\). Your solution is correct if the value of \(p = \sum_{i = 1}^n c_i \vec{v_i}\), satisfies \(|p| \le 1.5 \cdot 10^6\).It can be shown that a solution always exists under the given constraints.
Input: 3999999 00 999999999999 0 | Output: 1 1 -1
Expert
6
768
266
305
9
408
A
408A
A. Line to Cashier
900
implementation
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi, j items in the basket. Vasya knows that: the cashier needs 5 seconds to scan one item; after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.
The first line contains integer n (1 ≤ n ≤ 100) — the number of cashes in the shop. The second line contains n space-separated integers: k1, k2, ..., kn (1 ≤ ki ≤ 100), where ki is the number of people in the queue to the i-th cashier.The i-th of the next n lines contains ki space-separated integers: mi, 1, mi, 2, ..., mi, ki (1 ≤ mi, j ≤ 100) — the number of products the j-th person in the queue for the i-th cash has.
Print a single integer — the minimum number of seconds Vasya needs to get to the cashier.
In the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1·5 + 2·5 + 2·5 + 3·5 + 4·15 = 100 seconds. He will need 1·5 + 9·5 + 1·5 + 3·15 = 100 seconds for the third one and 7·5 + 8·5 + 2·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue.
Input: 111 | Output: 20
Beginner
1
821
422
89
4
1,740
H
1740H
H. MEX Tree Manipulation
3,300
data structures; trees
Given a rooted tree, define the value of vertex \(u\) in the tree recursively as the MEX\(^\dagger\) of the values of its children. Note that it is only the children, not all of its descendants. In particular, the value of a leaf is \(0\).Pak Chanek has a rooted tree that initially only contains a single vertex with index \(1\), which is the root. Pak Chanek is going to do \(q\) queries. In the \(i\)-th query, Pak Chanek is given an integer \(x_i\). Pak Chanek needs to add a new vertex with index \(i+1\) as the child of vertex \(x_i\). After adding the new vertex, Pak Chanek needs to recalculate the values of all vertices and report the sum of the values of all vertices in the current tree.\(^\dagger\) The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For example, the MEX of \([0,1,1,2,6,7]\) is \(3\) and the MEX of \([6,9]\) is \(0\).
The first line contains a single integer \(q\) (\(1 \le q \le 3 \cdot 10^5\)) — the number of operations.Each of the next \(q\) lines contains a single integer \(x_i\) (\(1 \leq x_i \leq i\)) — the description of the \(i\)-th query.
For each query, print a line containing an integer representing the sum of the new values of all vertices in the tree after adding the vertex.
In the first example, the tree after the \(6\)-th query will look like this. Vertex \(7\) is a leaf, so its value is \(0\). Vertex \(6\) is a leaf, so its value is \(0\). Vertex \(5\) only has a child with value \(0\), so its value is \(1\). Vertex \(4\) is a leaf, so its value is \(0\). Vertex \(3\) only has a child with value \(0\), so its value is \(1\). Vertex \(2\) has children with values \(0\) and \(1\), so its value is \(2\). Vertex \(1\) has children with values \(1\) and \(2\), so its value is \(0\). The sum of the values of all vertices is \(0+0+1+0+1+2+0=4\).
Input: 7 1 1 3 2 5 2 1 | Output: 1 1 3 2 4 4 7
Master
2
908
232
142
17
883
C
883C
C. Downloading B++
2,300
binary search; implementation
Only T milliseconds left before the start of well-known online programming contest Codehorses Round 2017.Polycarp needs to download B++ compiler to take part in the contest. The size of the file is f bytes.Polycarp's internet tariff allows to download data at the rate of one byte per t0 milliseconds. This tariff is already prepaid, and its use does not incur any expense for Polycarp. In addition, the Internet service provider offers two additional packages: download a1 bytes at the rate of one byte per t1 milliseconds, paying p1 burles for the package; download a2 bytes at the rate of one byte per t2 milliseconds, paying p2 burles for the package. Polycarp can buy any package many times. When buying a package, its price (p1 or p2) is prepaid before usage. Once a package is bought it replaces the regular tariff until package data limit is completely used. After a package is consumed Polycarp can immediately buy a new package or switch to the regular tariff without loosing any time. While a package is in use Polycarp can't buy another package or switch back to the regular internet tariff.Find the minimum amount of money Polycarp has to spend to download an f bytes file no more than in T milliseconds.Note that because of technical reasons Polycarp can download only integer number of bytes using regular tariff and both packages. I.e. in each of three downloading modes the number of downloaded bytes will be integer. It means that Polycarp can't download a byte partially using the regular tariff or/and both packages.
The first line contains three integer numbers f, T and t0 (1 ≤ f, T, t0 ≤ 107) — size of the file to download (in bytes), maximal time to download the file (in milliseconds) and number of milliseconds to download one byte using the regular internet tariff.The second line contains a description of the first additional package. The line contains three integer numbers a1, t1 and p1 (1 ≤ a1, t1, p1 ≤ 107), where a1 is maximal sizes of downloaded data (in bytes), t1 is time to download one byte (in milliseconds), p1 is price of the package (in burles).The third line contains a description of the second additional package. The line contains three integer numbers a2, t2 and p2 (1 ≤ a2, t2, p2 ≤ 107), where a2 is maximal sizes of downloaded data (in bytes), t2 is time to download one byte (in milliseconds), p2 is price of the package (in burles).Polycarp can buy any package many times. Once package is bought it replaces the regular tariff until package data limit is completely used. While a package is in use Polycarp can't buy another package or switch back to the regular internet tariff.
Print the minimum amount of money that Polycarp needs to pay to download B++ compiler no more than in T milliseconds. If there is no solution, print the only integer -1.
In the first example Polycarp has to buy the first additional package 5 times and do not buy the second additional package. He downloads 120 bytes (of total 26·5 = 130 bytes) in 120·8 = 960 milliseconds (960 ≤ 964). He spends 8·5 = 40 burles on it.In the second example Polycarp has enough time to download 10 bytes. It takes 10·20 = 200 milliseconds which equals to upper constraint on download time.In the third example Polycarp has to buy one first additional package and one second additional package.In the fourth example Polycarp has no way to download the file on time.
Input: 120 964 2026 8 813 10 4 | Output: 40
Expert
2
1,536
1,097
169
8
1,090
I
1090I
2,000
Hard
0
0
0
0
10
2,013
C
2013C
C. Password Cracking
1,400
constructive algorithms; interactive; strings
Dimash learned that Mansur wrote something very unpleasant about him to a friend, so he decided to find out his password at all costs and discover what exactly he wrote.Believing in the strength of his password, Mansur stated that his password — is a binary string of length \(n\). He is also ready to answer Dimash's questions of the following type:Dimash says a binary string \(t\), and Mansur replies whether it is true that \(t\) is a substring of his password.Help Dimash find out the password in no more than \(2n\) operations; otherwise, Mansur will understand the trick and stop communicating with him.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 100\)). The description of the test cases follows.
In the first example, the string \(010\) is given. Therefore, the answers to the queries are as follows:""? 00"" \(00\) is not a substring of \(010\), so the answer is \(0\).""? 000"" \(000\) is not a substring, so the answer is \(0\).""? 010"" \(010\) is a substring, so the answer is \(1\).In the second example, the string is \(1100\), in the third \(0110\), and in the fourth \(10\).
Input: 4 3 0 0 1 4 4 2 | Output: ? 00 ? 000 ? 010 ! 010 ! 1100 ! 0110 ! 10
Easy
3
610
160
0
20
1,919
E
1919E
E. Counting Prefixes
2,600
combinatorics; constructive algorithms; dp; implementation; math
There is a hidden array \(a\) of size \(n\) consisting of only \(1\) and \(-1\). Let \(p\) be the prefix sums of array \(a\). More formally, \(p\) is an array of length \(n\) defined as \(p_i = a_1 + a_2 + \ldots + a_i\). Afterwards, array \(p\) is sorted in non-decreasing order. For example, if \(a = [1, -1, -1, 1, 1]\), then \(p = [1, 0, -1, 0, 1]\) before sorting and \(p = [-1, 0, 0, 1, 1]\) after sorting.You are given the prefix sum array \(p\) after sorting, but you do not know what array \(a\) is. Your task is to count the number of initial arrays \(a\) such that the above process results in the given sorted prefix sum array \(p\). As this number can be large, you are only required to find it modulo \(998\,244\,353\).
Each test contains 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 a single integer \(n\) (\(1 \le n \le 5000\)) — the size of the hidden array \(a\).The second line of each test case contains \(n\) integers \(p_1, p_2, \ldots, p_n\) (\(|p_i| \le n\)) — the \(n\) prefix sums of \(a\) sorted in non-decreasing order.It is guaranteed that \(p_1 \le p_2 \le \ldots \le p_n\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5000\).
For each test case, output the answer modulo \(998\,244\,353\).
In the first two test cases, the only possible arrays \(a\) for \(n = 1\) are \(a = [1]\) and \(a = [-1]\). Their respective sorted prefix sum arrays \(p\) are \(p = [1]\) and \(p = [-1]\). Hence, there is no array \(a\) that can result in the sorted prefix sum array \(p = [0]\) and there is exactly \(1\) array \(a\) that can result in the sorted prefix sum array \(p = [1]\).In the third test case, it can be proven that there is no array \(a\) that could result in the sorted prefix sum array \(p = [-1, 1, 2]\).In the fourth test case, the \(3\) possible arrays \(a\) that could result in the sorted prefix sum array \(p = [-1, 0, 0, 1, 1]\) are: \(a = [1, -1, 1, -1, -1]\). The prefix sum array before sorting is \(p = [1, 0, 1, 0, -1]\), which after sorting gives \(p = [-1, 0, 0, 1, 1]\). \(a = [1, -1, -1, 1, 1]\). The prefix sum array before sorting is \(p = [1, 0, -1, 0, 1]\), which after sorting gives \(p = [-1, 0, 0, 1, 1]\). \(a = [-1, 1, 1, -1, 1]\). The prefix sum array before sorting is \(p = [-1, 0, 1, 0, 1]\), which after sorting gives \(p = [-1, 0, 0, 1, 1]\). For the fifth test case, the only possible array \(a\) that could result in the sorted prefix sum array \(p = [-4, -3, -3, -2, -1]\) is \(a = [-1, -1, -1, -1, 1]\).
Input: 510113-1 1 25-1 0 0 1 15-4 -3 -3 -2 -1 | Output: 0 1 0 3 1
Expert
5
733
614
63
19
250
C
250C
C. Movie Critics
1,600
greedy
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres.The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
In the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Input: 10 31 1 2 3 2 3 3 1 1 3 | Output: 3
Medium
1
1,330
366
156
2
1,867
E2
1867E2
E2. Salyg1n and Array (hard version)
2,200
constructive algorithms; interactive
This is the hard version of the problem. The only difference between the versions is the limit on the number of queries. In this version, you can make no more than 57 queries. You can make hacks only if both versions of the problem are solved.This is an interactive problem!salyg1n has given you a positive integer \(k\) and wants to play a game with you. He has chosen an array of \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 10^9\)). You must print \(a_1 \oplus a_2 \oplus \ldots \oplus a_n\), where \(\oplus\) denotes the bitwise XOR operation. You can make queries of the following type: \(?\) \(i\): in response to this query, you will receive \(a_i \oplus a_{i + 1} \oplus \ldots \oplus a_{i + k - 1}\). Also, after this query, the subarray \(a_i, a_{i + 1}, \ldots, a_{i + k - 1}\) will be reversed, i.e., the chosen array \(a\) will become: \(a_1, a_2, \ldots a_{i - 1}, a_{i + k - 1}, a_{i + k - 2}, \ldots, a_{i + 1}, a_i, a_{i + k}, \ldots, a_n\). You can make no more than \(57\) queries to answer the problem.
The first line contains a single integer \(t\) (\(1 \leq t \leq 1000\)) – the number of test cases.
In the first test case, the jury has chosen the array \(a\) \(=\) \([4, 2, 5, 1]\)In the second test case, the jury has chosen the array \(a\) \(=\) \([5, 7, 1, 3, 3, 7]\)
Input: 2 4 2 6 4 6 6 4 | Output: ? 1 ? 3 ! 2 ? 1 ! 4
Hard
2
1,037
99
0
18
1,526
E
1526E
E. Oolimry and Suffix Array
2,400
combinatorics; constructive algorithms; math
Once upon a time, Oolimry saw a suffix array. He wondered how many strings can produce this suffix array. More formally, given a suffix array of length \(n\) and having an alphabet size \(k\), count the number of strings that produce such a suffix array. Let \(s\) be a string of length \(n\). Then the \(i\)-th suffix of \(s\) is the substring \(s[i \ldots n-1]\). A suffix array is the array of integers that represent the starting indexes of all the suffixes of a given string, after the suffixes are sorted in the lexicographic order. For example, the suffix array of oolimry is \([3,2,4,1,0,5,6]\) as the array of sorted suffixes is \([\texttt{imry},\texttt{limry},\texttt{mry},\texttt{olimry},\texttt{oolimry},\texttt{ry},\texttt{y}]\). A string \(x\) is lexicographically smaller than string \(y\), if either \(x\) is a prefix of \(y\) (and \(x\neq y\)), or there exists such \(i\) that \(x_i < y_i\), and for any \(1\leq j < i\) , \(x_j = y_j\).
The first line contain 2 integers \(n\) and \(k\) (\(1 \leq n \leq 200000,1 \leq k \leq 200000\)) — the length of the suffix array and the alphabet size respectively.The second line contains \(n\) integers \(s_0, s_1, s_2, \ldots, s_{n-1}\) (\(0 \leq s_i \leq n-1\)) where \(s_i\) is the \(i\)-th element of the suffix array i.e. the starting position of the \(i\)-th lexicographically smallest suffix. It is guaranteed that for all \(0 \leq i< j \leq n-1\), \(s_i \neq s_j\).
Print how many strings produce such a suffix array. Since the number can be very large, print the answer modulo \(998244353\).
In the first test case, ""abb"" is the only possible solution. In the second test case, it can be easily shown no possible strings exist as all the letters have to be equal. In the fourth test case, one possible string is ""ddbacef"".Please remember to print your answers modulo \(998244353\).
Input: 3 2 0 2 1 | Output: 1
Expert
3
953
476
126
15
867
A
867A
A. Between the Offices
800
implementation
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last n days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last n days, or not.
The first line of input contains single integer n (2 ≤ n ≤ 100) — the number of days.The second line contains a string of length n consisting of only capital 'S' and 'F' letters. If the i-th letter is 'S', then you were in Seattle office on that day. Otherwise you were in San Francisco. The days are given in chronological order, i.e. today is the last day in this sequence.
Print ""YES"" if you flew more times from Seattle to San Francisco, and ""NO"" otherwise.You can print each letter in any case (upper or lower).
In the first example you were initially at San Francisco, then flew to Seattle, were there for two days and returned to San Francisco. You made one flight in each direction, so the answer is ""NO"".In the second example you just flew from Seattle to San Francisco, so the answer is ""YES"".In the third example you stayed the whole period in San Francisco, so the answer is ""NO"".In the fourth example if you replace 'S' with ones, and 'F' with zeros, you'll get the first few digits of π in binary representation. Not very useful information though.
Input: 4FSSF | Output: NO
Beginner
1
685
375
144
8
540
E
540E
E. Infinite Inversions
2,100
binary search; data structures; implementation; sortings; trees
There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i < j and pi > pj.
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of swap operations applied to the sequence.Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109, ai ≠ bi) — the arguments of the swap operation.
Print a single integer — the number of inversions in the resulting sequence.
In the first sample the sequence is being modified as follows: . It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4).
Input: 24 21 4 | Output: 4
Hard
5
394
236
76
5
1,361
E
1361E
E. James and the Chase
3,000
dfs and similar; graphs; probabilities; trees
James Bond has a new plan for catching his enemy. There are some cities and directed roads between them, such that it is possible to travel between any two cities using these roads. When the enemy appears in some city, Bond knows her next destination but has no idea which path she will choose to move there. The city \(a\) is called interesting, if for each city \(b\), there is exactly one simple path from \(a\) to \(b\). By a simple path, we understand a sequence of distinct cities, such that for every two neighboring cities, there exists a directed road from the first to the second city. Bond's enemy is the mistress of escapes, so only the chase started in an interesting city gives the possibility of catching her. James wants to arrange his people in such cities. However, if there are not enough interesting cities, the whole action doesn't make sense since Bond's people may wait too long for the enemy.You are responsible for finding all the interesting cities or saying that there is not enough of them. By not enough, James means strictly less than \(20\%\) of all cities.
The first line contains one integer \(t\) (\(1 \leq t \leq 2\,000\)) — the number of test cases. Each test case is described as follows:The first line contains two integers \(n\) and \(m\) (\(1 \leq n \le 10^5\), \(0 \leq m \le 2 \cdot 10^5\)) — the number of cities and roads between them. Each of the following \(m\) lines contains two integers \(u\), \(v\) (\(u \neq v\); \(1 \leq u, v \leq n\)), which denote that there is a directed road from \(u\) to \(v\).You can assume that between each ordered pair of cities there is at most one road. The sum of \(n\) over all test cases doesn't exceed \(10^5\), and the sum of \(m\) doesn't exceed \(2 \cdot 10^5\).
If strictly less than \(20\%\) of all cities are interesting, print \(-1\). Otherwise, let \(k\) be the number of interesting cities. Print \(k\) distinct integers in increasing order — the indices of interesting cities.
In all drawings, if a city is colored green, then it is interesting; otherwise, it is colored red.In the first sample, each city is interesting. In the second sample, no city is interesting. In the third sample, cities \(1\), \(2\), \(3\) and \(5\) are interesting. In the last sample, only the city \(1\) is interesting. It is strictly less than \(20\%\) of all cities, so the answer is \(-1\).
Input: 4 3 3 1 2 2 3 3 1 3 6 1 2 2 1 2 3 3 2 1 3 3 1 7 10 1 2 2 3 3 1 1 4 4 5 5 1 4 6 6 7 7 4 6 1 6 8 1 2 2 3 3 4 4 5 5 6 6 1 6 2 5 1 | Output: 1 2 3 -1 1 2 3 5 -1
Master
4
1,088
661
220
13
436
C
436C
C. Dungeons and Candies
1,800
dsu; graphs; greedy; trees
During the loading of the game ""Dungeons and Candies"" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as ""."" on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same. When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A: You can transmit the whole level A. Then you need to transmit n·m bytes via the network. You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit dA, B·w bytes, where dA, B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate dA, B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other. Your task is to find a way to transfer all the k levels and minimize the traffic.
The first line contains four integers n, m, k, w (1 ≤ n, m ≤ 10; 1 ≤ k, w ≤ 1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("".""). Please note that the case of the letters matters.
In the first line print the required minimum number of transferred bytes.Then print k pairs of integers x1, y1, x2, y2, ..., xk, yk, describing the way to transfer levels. Pair xi, yi means that level xi needs to be transferred by way yi. If yi equals 0, that means that the level must be transferred using the first way, otherwise yi must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels yi and xi to transfer level xi. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input.If there are multiple optimal solutions, you can print any of them.
Input: 2 3 3 2A.A...A.a..CX.Y... | Output: 141 02 13 1
Medium
4
1,336
319
686
4
2,119
A
2119A
A. Add or XOR
800
bitmasks; greedy; math
r-906 & IA AI - Psychologic Disco You are given two non-negative integers \(a, b\). You can apply two types of operations on \(a\) any number of times and in any order: \(a \gets a + 1\). The cost of this operation is \(x\); \(a \gets a \oplus 1\), where \(\oplus\) denotes the bitwise XOR operation. The cost of this operation is \(y\). Now you are asked to make \(a = b\). If it's possible, output the minimum cost; otherwise, report it.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The only line of each test case contains four integers \(a, b, x, y\) (\(1 \le a, b \le 100, 1 \le x, y \le 10^7\)) — the two integers given to you and the respective costs of two types of operations.
For each test case, output an integer — the minimum cost to make \(a = b\), or \(-1\) if it is impossible.
In the first test case, the optimal strategy is to apply \(a \gets a + 1\) three times. The total cost is \(1+1+1=3\).In the second test case, the optimal strategy is to apply \(a \gets a + 1\), \(a \gets a \oplus 1\), \(a \gets a + 1\), \(a \gets a \oplus 1\) in order. The total cost is \(2+1+2+1=6\).In the fifth test case, it can be proved that there isn't a way to make \(a = b\).
Input: 71 4 1 21 5 2 13 2 2 11 3 2 12 1 1 23 1 1 21 100 10000000 10000000 | Output: 3 6 1 3 -1 -1 990000000
Beginner
3
439
362
106
21
1,430
F
1430F
F. Realistic Gameplay
2,600
dp; greedy
Recently you've discovered a new shooter. They say it has realistic game mechanics.Your character has a gun with magazine size equal to \(k\) and should exterminate \(n\) waves of monsters. The \(i\)-th wave consists of \(a_i\) monsters and happens from the \(l_i\)-th moment of time up to the \(r_i\)-th moments of time. All \(a_i\) monsters spawn at moment \(l_i\) and you have to exterminate all of them before the moment \(r_i\) ends (you can kill monsters right at moment \(r_i\)). For every two consecutive waves, the second wave starts not earlier than the first wave ends (though the second wave can start at the same moment when the first wave ends) — formally, the condition \(r_i \le l_{i + 1}\) holds. Take a look at the notes for the examples to understand the process better.You are confident in yours and your character's skills so you can assume that aiming and shooting are instant and you need exactly one bullet to kill one monster. But reloading takes exactly \(1\) unit of time.One of the realistic mechanics is a mechanic of reloading: when you reload you throw away the old magazine with all remaining bullets in it. That's why constant reloads may cost you excessive amounts of spent bullets.You've taken a liking to this mechanic so now you are wondering: what is the minimum possible number of bullets you need to spend (both used and thrown) to exterminate all waves.Note that you don't throw the remaining bullets away after eradicating all monsters, and you start with a full magazine.
The first line contains two integers \(n\) and \(k\) (\(1 \le n \le 2000\); \(1 \le k \le 10^9\)) — the number of waves and magazine size.The next \(n\) lines contain descriptions of waves. The \(i\)-th line contains three integers \(l_i\), \(r_i\) and \(a_i\) (\(1 \le l_i \le r_i \le 10^9\); \(1 \le a_i \le 10^9\)) — the period of time when the \(i\)-th wave happens and the number of monsters in it.It's guaranteed that waves don't overlap (but may touch) and are given in the order they occur, i. e. \(r_i \le l_{i + 1}\).
If there is no way to clear all waves, print \(-1\). Otherwise, print the minimum possible number of bullets you need to spend (both used and thrown) to clear all waves.
In the first example: At the moment \(2\), the first wave occurs and \(6\) monsters spawn. You kill \(3\) monsters and start reloading. At the moment \(3\), the second wave occurs and \(3\) more monsters spawn. You kill remaining \(3\) monsters from the first wave and start reloading. At the moment \(4\), you kill remaining \(3\) monsters from the second wave. In total, you'll spend \(9\) bullets.In the second example: At moment \(3\), the first wave occurs and \(11\) monsters spawn. You kill \(5\) monsters and start reloading. At moment \(4\), you kill \(5\) more monsters and start reloading. At moment \(5\), you kill the last monster and start reloading throwing away old magazine with \(4\) bullets. At moment \(10\), the second wave occurs and \(15\) monsters spawn. You kill \(5\) monsters and start reloading. At moment \(11\), you kill \(5\) more monsters and start reloading. At moment \(12\), you kill last \(5\) monsters. In total, you'll spend \(30\) bullets.
Input: 2 3 2 3 6 3 4 3 | Output: 9
Expert
2
1,514
527
169
14
1,807
A
1807A
A. Plus or Minus
800
implementation
You are given three integers \(a\), \(b\), and \(c\) such that exactly one of these two equations is true: \(a+b=c\) \(a-b=c\) Output + if the first equation is true, and - otherwise.
The first line contains a single integer \(t\) (\(1 \leq t \leq 162\)) — the number of test cases.The description of each test case consists of three integers \(a\), \(b\), \(c\) (\(1 \leq a, b \leq 9\), \(-8 \leq c \leq 18\)). The additional constraint on the input: it will be generated so that exactly one of the two equations will be true.
For each test case, output either + or - on a new line, representing the correct equation.
In the first test case, \(1+2=3\).In the second test case, \(3-2=1\).In the third test case, \(2-9=-7\). Note that \(c\) can be negative.
Input: 111 2 33 2 12 9 -73 4 71 1 21 1 03 3 69 9 189 9 01 9 -81 9 10 | Output: + - - + + - + + - - +
Beginner
1
183
343
90
18
1,533
H
1533H
H. Submatrices
0
*special; bitmasks; data structures; dp
You are given matrix \(s\) that contains \(n\) rows and \(m\) columns. Each element of a matrix is one of the \(5\) first Latin letters (in upper case).For each \(k\) (\(1 \le k \le 5\)) calculate the number of submatrices that contain exactly \(k\) different letters. Recall that a submatrix of matrix \(s\) is a matrix that can be obtained from \(s\) after removing several (possibly zero) first rows, several (possibly zero) last rows, several (possibly zero) first columns, and several (possibly zero) last columns. If some submatrix can be obtained from \(s\) in two or more ways, you have to count this submatrix the corresponding number of times.
The first line contains two integers \(n\) and \(m\) (\(1 \le n, m \le 800\)).Then \(n\) lines follow, each containing the string \(s_i\) (\(|s_i| = m\)) — \(i\)-th row of the matrix.
For each \(k\) (\(1 \le k \le 5\)) print one integer — the number of submatrices that contain exactly \(k\) different letters.
Input: 2 3 ABB ABA | Output: 9 9 0 0 0
Beginner
4
653
183
126
15
1,313
D
1313D
D. Happy New Year
2,500
bitmasks; dp; implementation
Being Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were \(m\) children lined up in front of him. Let's number them from \(1\) to \(m\). Grandfather Frost knows \(n\) spells. The \(i\)-th spell gives a candy to every child whose place is in the \([L_i, R_i]\) range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most \(k\) candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.
The first line contains three integers of \(n\), \(m\), and \(k\) (\(1 \leq n \leq 100\,000, 1 \leq m \leq 10^9, 1 \leq k \leq 8\)) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by \(n\) lines, each containing integers \(L_i\) and \(R_i\) (\(1 \leq L_i \leq R_i \leq m\)) — the parameters of the \(i\) spell.
Print a single integer — the maximum number of children that Santa can make happy.
In the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.
Input: 3 5 31 32 43 5 | Output: 4
Expert
3
1,016
422
82
13
838
D
838D
D. Airplane Arrangements
2,700
math; number theory
There is an airplane which has n rows from front to back. There will be m people boarding this airplane.This airplane has an entrance at the very front and very back of the plane.Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person 1. Each person can independently choose either the front entrance or back entrance to enter the plane.When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo 109 + 7.
The first line of input will contain two integers n, m (1 ≤ m ≤ n ≤ 1 000 000), the number of seats, and the number of passengers, respectively.
Print a single number, the number of ways, modulo 109 + 7.
Here, we will denote a passenger by which seat they were assigned, and which side they came from (either ""F"" or ""B"" for front or back, respectively).For example, one valid way is 3B, 3B, 3B (i.e. all passengers were assigned seat 3 and came from the back entrance). Another valid way would be 2F, 1B, 3F.One invalid way would be 2B, 2B, 2B, since the third passenger would get to the front without finding a seat.
Input: 3 3 | Output: 128
Master
2
1,076
144
58
8
630
H
630H
H. Benches
1,400
combinatorics; math
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections.The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Obviously this requirement is satisfied by the following scheme: each bench is placed on a cross of paths and each path contains not more than one bench.Help the park administration count the number of ways to place the benches.
The only line of the input contains one integer n (5 ≤ n ≤ 100) — the number of east to west paths and north to south paths.
Output one integer — the number of ways to place the benches.
Input: 5 | Output: 120
Easy
2
544
124
61
6
39
B
39B
B. Company Income Growth
1,300
greedy
Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to a1 billion bourles, in 2002 — to a2 billion, ..., and in the current (2000 + n)-th year — an billion bourles. On the base of the information Petya decided to show in his presentation the linear progress history which is in his opinion perfect. According to a graph Petya has already made, in the first year BerSoft company income must amount to 1 billion bourles, in the second year — 2 billion bourles etc., each following year the income increases by 1 billion bourles. Unfortunately, the real numbers are different from the perfect ones. Among the numbers ai can even occur negative ones that are a sign of the company’s losses in some years. That is why Petya wants to ignore some data, in other words, cross some numbers ai from the sequence and leave only some subsequence that has perfect growth.Thus Petya has to choose a sequence of years y1, y2, ..., yk,so that in the year y1 the company income amounted to 1 billion bourles, in the year y2 — 2 billion bourles etc., in accordance with the perfect growth dynamics. Help him to choose the longest such sequence.
The first line contains an integer n (1 ≤ n ≤ 100). The next line contains n integers ai ( - 100 ≤ ai ≤ 100). The number ai determines the income of BerSoft company in the (2000 + i)-th year. The numbers in the line are separated by spaces.
Output k — the maximum possible length of a perfect sequence. In the next line output the sequence of years y1, y2, ..., yk. Separate the numbers by spaces. If the answer is not unique, output any. If no solution exist, output one number 0.
Input: 10-2 1 1 3 2 3 4 -10 -2 5 | Output: 52002 2005 2006 2007 2010
Easy
1
1,309
240
240
0
1,490
B
1490B
B. Balanced Remainders
1,000
brute force; constructive algorithms; math
You are given a number \(n\) (divisible by \(3\)) and an array \(a[1 \dots n]\). In one move, you can increase any of the array elements by one. Formally, you choose the index \(i\) (\(1 \le i \le n\)) and replace \(a_i\) with \(a_i + 1\). You can choose the same index \(i\) multiple times for different moves.Let's denote by \(c_0\), \(c_1\) and \(c_2\) the number of numbers from the array \(a\) that have remainders \(0\), \(1\) and \(2\) when divided by the number \(3\), respectively. Let's say that the array \(a\) has balanced remainders if \(c_0\), \(c_1\) and \(c_2\) are equal.For example, if \(n = 6\) and \(a = [0, 2, 5, 5, 4, 8]\), then the following sequence of moves is possible: initially \(c_0 = 1\), \(c_1 = 1\) and \(c_2 = 4\), these values are not equal to each other. Let's increase \(a_3\), now the array \(a = [0, 2, 6, 5, 4, 8]\); \(c_0 = 2\), \(c_1 = 1\) and \(c_2 = 3\), these values are not equal. Let's increase \(a_6\), now the array \(a = [0, 2, 6, 5, 4, 9]\); \(c_0 = 3\), \(c_1 = 1\) and \(c_2 = 2\), these values are not equal. Let's increase \(a_1\), now the array \(a = [1, 2, 6, 5, 4, 9]\); \(c_0 = 2\), \(c_1 = 2\) and \(c_2 = 2\), these values are equal to each other, which means that the array \(a\) has balanced remainders. Find the minimum number of moves needed to make the array \(a\) have balanced remainders.
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)). Then \(t\) test cases follow.The first line of each test case contains one integer \(n\) (\(3 \le n \le 3 \cdot 10^4\)) — the length of the array \(a\). It is guaranteed that the number \(n\) is divisible by \(3\).The next line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \leq a_i \leq 100\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(150\,000\).
For each test case, output one integer — the minimum number of moves that must be made for the \(a\) array to make it have balanced remainders.
The first test case is explained in the statements.In the second test case, you need to make one move for \(i=2\).The third test case you need to make three moves: the first move: \(i=9\); the second move: \(i=9\); the third move: \(i=2\). In the fourth test case, the values \(c_0\), \(c_1\) and \(c_2\) initially equal to each other, so the array \(a\) already has balanced remainders.
Input: 4 6 0 2 5 5 4 8 6 2 0 2 1 0 0 9 7 1 3 4 2 10 3 9 6 6 0 1 2 3 4 5 | Output: 3 1 3 0
Beginner
3
1,355
458
143
14