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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
720 |
E
|
720E
|
E. Cipher
| 3,100 |
implementation
|
Borya has recently found a big electronic display. The computer that manages the display stores some integer number. The number has n decimal digits, the display shows the encoded version of the number, where each digit is shown using some lowercase letter of the English alphabet.There is a legend near the display, that describes how the number is encoded. For each digit position i and each digit j the character c is known, that encodes this digit at this position. Different digits can have the same code characters.Each second the number is increased by 1. And one second after a moment when the number reaches the value that is represented as n 9-s in decimal notation, the loud beep sounds. Andrew knows the number that is stored in the computer. Now he wants to know how many seconds must pass until Borya can definitely tell what was the original number encoded by the display. Assume that Borya can precisely measure time, and that the encoded number will first be increased exactly one second after Borya started watching at the display.
|
Input data contains multiple test cases. The first line of input contains t (1 ≤ t ≤ 100) — the number of test cases. Each test case is described as follows. The first line of the description contains n (1 ≤ n ≤ 18) — the number of digits in the number. The second line contains n decimal digits without spaces (but possibly with leading zeroes) — the number initially stored in the display computer. The following n lines contain 10 characters each. The j-th character of the i-th of these lines is the code character for a digit j - 1 in position i, most significant digit positions are described first.
|
For each test case print an integer: the number of seconds until Borya definitely knows what was the initial number stored on the display of the computer. Do not print leading zeroes.
|
Input: 3242abcdefghijjihgfedcba242aaaaaaaaaaaaaaaaaaaa12abcdabcdff | Output: 0582
|
Master
| 1 | 1,049 | 605 | 183 | 7 |
|
810 |
A
|
810A
|
A. Straight «A»
| 900 |
implementation; math
|
Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one.In school, where Noora is studying, teachers are putting down marks to the online class register, which are integers from 1 to k. The worst mark is 1, the best is k. Mark that is going to the certificate, is calculated as an average of all the marks, rounded to the closest integer. If several answers are possible, rounding up is produced. For example, 7.3 is rounded to 7, but 7.5 and 7.8784 — to 8. For instance, if Noora has marks [8, 9], then the mark to the certificate is 9, because the average is equal to 8.5 and rounded to 9, but if the marks are [8, 8, 9], Noora will have graduation certificate with 8.To graduate with «A» certificate, Noora has to have mark k.Noora got n marks in register this year. However, she is afraid that her marks are not enough to get final mark k. Noora decided to ask for help in the internet, where hacker Leha immediately responded to her request. He is ready to hack class register for Noora and to add Noora any number of additional marks from 1 to k. At the same time, Leha want his hack be unseen to everyone, so he decided to add as less as possible additional marks. Please help Leha to calculate the minimal number of marks he has to add, so that final Noora's mark will become equal to k.
|
The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 100) denoting the number of marks, received by Noora and the value of highest possible mark.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ k) denoting marks received by Noora before Leha's hack.
|
Print a single integer — minimal number of additional marks, that Leha has to add in order to change Noora's final mark to k.
|
Consider the first example testcase.Maximal mark is 10, Noora received two marks — 8 and 9, so current final mark is 9. To fix it, Leha can add marks [10, 10, 10, 10] (4 marks in total) to the registry, achieving Noora having average mark equal to . Consequently, new final mark is 10. Less number of marks won't fix the situation.In the second example Leha can add [5, 5, 5] to the registry, so that making average mark equal to 4.5, which is enough to have 5 in the certificate.
|
Input: 2 108 9 | Output: 4
|
Beginner
| 2 | 1,457 | 276 | 125 | 8 |
1,223 |
B
|
1223B
|
B. Strings Equalization
| 1,000 |
strings
|
You are given two strings of equal length \(s\) and \(t\) consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.For example, if \(s\) is ""acbc"" you can get the following strings in one operation: ""aabc"" (if you perform \(s_2 = s_1\)); ""ccbc"" (if you perform \(s_1 = s_2\)); ""accc"" (if you perform \(s_3 = s_2\) or \(s_3 = s_4\)); ""abbc"" (if you perform \(s_2 = s_3\)); ""acbb"" (if you perform \(s_4 = s_3\)); Note that you can also apply this operation to the string \(t\).Please determine whether it is possible to transform \(s\) into \(t\), applying the operation above any number of times.Note that you have to answer \(q\) independent queries.
|
The first line contains one integer \(q\) (\(1 \le q \le 100\)) — the number of queries. Each query is represented by two consecutive lines.The first line of each query contains the string \(s\) (\(1 \le |s| \le 100\)) consisting of lowercase Latin letters.The second line of each query contains the string \(t\) (\(1 \le |t| \leq 100\), \(|t| = |s|\)) consisting of lowercase Latin letters.
|
For each query, print ""YES"" if it is possible to make \(s\) equal to \(t\), and ""NO"" otherwise.You may print every letter in any case you want (so, for example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will all be recognized as positive answer).
|
In the first query, you can perform two operations \(s_1 = s_2\) (after it \(s\) turns into ""aabb"") and \(t_4 = t_3\) (after it \(t\) turns into ""aabb""). In the second query, the strings are equal initially, so the answer is ""YES"".In the third query, you can not make strings \(s\) and \(t\) equal. Therefore, the answer is ""NO"".
|
Input: 3 xabb aabx technocup technocup a z | Output: YES YES NO
|
Beginner
| 1 | 872 | 391 | 259 | 12 |
267 |
B
|
267B
|
B. Dominoes
| 2,000 |
dfs and similar; graphs
|
You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touch with the sides that had the same number of points? You can rotate the dominoes, changing the left and the right side (domino ""1-4"" turns into ""4-1"").
|
The first line contains the number n (1 ≤ n ≤ 100). Next n lines contain the dominoes. Each of these lines contains two numbers — the number of points (spots) on the left and the right half, correspondingly. The numbers of points (spots) are non-negative integers from 0 to 6. Duplicates (identical tiles) may be present in the given set.
|
Print ""No solution"", if it is impossible to arrange the dominoes in the required manner. If the solution exists, then describe any way to arrange the dominoes. You put the dominoes from left to right. In each of the n lines print the index of the domino to put in the corresponding position and then, after a space, the character ""+"" (if you don't need to turn the domino) or ""–"" (if you need to turn it).
|
Input: 51 22 42 46 42 1 | Output: 2 -1 -5 -3 +4 -
|
Hard
| 2 | 363 | 338 | 411 | 2 |
|
1,051 |
E
|
1051E
|
E. Vasya and Big Integers
| 2,600 |
binary search; data structures; dp; hashing; strings
|
Vasya owns three big integers — \(a, l, r\). Let's define a partition of \(x\) such a sequence of strings \(s_1, s_2, \dots, s_k\) that \(s_1 + s_2 + \dots + s_k = x\), where \(+\) is a concatanation of strings. \(s_i\) is the \(i\)-th element of the partition. For example, number \(12345\) has the following partitions: [""1"", ""2"", ""3"", ""4"", ""5""], [""123"", ""4"", ""5""], [""1"", ""2345""], [""12345""] and lots of others.Let's call some partition of \(a\) beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number \(a\), which has each of \(s_i\) satisfy the condition \(l \le s_i \le r\). Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number \(a\) such that they match all the given requirements. The result can be rather big, so print it modulo \(998244353\).
|
The first line contains a single integer \(a~(1 \le a \le 10^{1000000})\).The second line contains a single integer \(l~(0 \le l \le 10^{1000000})\).The third line contains a single integer \(r~(0 \le r \le 10^{1000000})\).It is guaranteed that \(l \le r\).It is also guaranteed that numbers \(a, l, r\) contain no leading zeros.
|
Print a single integer — the amount of partitions of number \(a\) such that they match all the given requirements modulo \(998244353\).
|
In the first test case, there are two good partitions \(13+5\) and \(1+3+5\).In the second test case, there is one good partition \(1+0+0+0+0\).
|
Input: 135115 | Output: 2
|
Expert
| 5 | 913 | 329 | 135 | 10 |
822 |
A
|
822A
|
A. I'm bored with life
| 800 |
implementation; math; number theory
|
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom!Leha came up with a task for himself to relax a little. He chooses two integers A and B and then calculates the greatest common divisor of integers ""A factorial"" and ""B factorial"". Formally the hacker wants to find out GCD(A!, B!). It's well known that the factorial of an integer x is a product of all positive integers less than or equal to x. Thus x! = 1·2·3·...·(x - 1)·x. For example 4! = 1·2·3·4 = 24. Recall that GCD(x, y) is the largest positive integer q that divides (without a remainder) both x and y.Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?
|
The first and single line contains two integers A and B (1 ≤ A, B ≤ 109, min(A, B) ≤ 12).
|
Print a single integer denoting the greatest common divisor of integers A! and B!.
|
Consider the sample.4! = 1·2·3·4 = 24. 3! = 1·2·3 = 6. The greatest common divisor of integers 24 and 6 is exactly 6.
|
Input: 4 3 | Output: 6
|
Beginner
| 3 | 1,063 | 89 | 82 | 8 |
1,638 |
D
|
1638D
|
D. Big Brush
| 2,000 |
constructive algorithms; data structures; greedy; implementation
|
You found a painting on a canvas of size \(n \times m\). The canvas can be represented as a grid with \(n\) rows and \(m\) columns. Each cell has some color. Cell \((i, j)\) has color \(c_{i,j}\).Near the painting you also found a brush in the shape of a \(2 \times 2\) square, so the canvas was surely painted in the following way: initially, no cell was painted. Then, the following painting operation has been performed some number of times: Choose two integers \(i\) and \(j\) (\(1 \le i < n\), \(1 \le j < m\)) and some color \(k\) (\(1 \le k \le nm\)). Paint cells \((i, j)\), \((i + 1, j)\), \((i, j + 1)\), \((i + 1, j + 1)\) in color \(k\). All cells must be painted at least once. A cell can be painted multiple times. In this case, its final color will be the last one.Find any sequence of at most \(nm\) operations that could have led to the painting you found or state that it's impossible.
|
The first line of input contains two integers \(n\) and \(m\) (\(2 \le n, m \le 1000\)) — the dimensions of the canvas.On the \(i\)-th of the next \(n\) lines of input, there will be \(m\) integers. The \(j\)-th of them is \(a_{i,j}\) (\(1 \le a_{i,j} \le nm\)) — the color of cell \((i, j)\).
|
If there is no solution, print a single integer \(-1\).Otherwise, on the first line, print one integer \(q\) (\(1 \le q \le nm\)) — the number of operations.Next, print the operations in order. On the \(k\)-th of the next \(q\) lines, print three integers \(i\), \(j\), \(c\) (\(1 \le i < n\), \(1 \le j < m\), \(1 \le c \le nm\)) — the description of the \(k\)-th operation.If there are multiple solutions, print any.
|
In the first test case, the solution is not unique. Here's one of them: In the second test case, there is no way one could obtain the given painting, thus the answer is \(-1\).
|
Input: 4 4 5 5 3 3 1 1 5 3 2 2 5 4 2 2 4 4 | Output: 6 1 3 3 3 3 4 2 2 5 1 1 5 2 1 1 3 1 2
|
Hard
| 4 | 903 | 293 | 418 | 16 |
683 |
A
|
683A
|
A. The Check of the Point
| 1,200 |
*special; geometry
|
On the coordinate plane there is a square with sides parallel to the coordinate axes. The length of the square side is equal to a. The lower left corner of the square coincides with the point (0, 0) (the point of the origin). The upper right corner of the square has positive coordinates.You are given a point with coordinates (x, y). Your task is to determine whether this point is located strictly inside the square, on its side, or strictly outside the square.
|
The first line contains three integers a, x and y (1 ≤ a ≤ 1000, - 1000 ≤ x, y ≤ 1000) — the length of the square side and the coordinates of the point which should be checked.
|
Print one integer: 0, if the point is located strictly inside the square; 1, if the point is located on the side of the square; 2, if the point is located strictly outside the square.
|
Input: 2 1 1 | Output: 0
|
Easy
| 2 | 463 | 176 | 183 | 6 |
|
1,446 |
D2
|
1446D2
|
D2. Frequency Problem (Hard Version)
| 3,000 |
data structures; greedy; two pointers
|
This is the hard version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.You are given an array \([a_1, a_2, \dots, a_n]\). Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs \(f\) times in this subarray, then at least \(2\) different values should occur exactly \(f\) times.An array \(c\) is a subarray of an array \(d\) if \(c\) can be obtained from \(d\) 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 \(n\) (\(1 \le n \le 200\,000\)) — the length of the array.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le n\)) — elements of the array.
|
You should output exactly one integer — the length of the longest subarray of the array whose most frequent value is not unique. If there is no such subarray, output \(0\).
|
In the first sample, the subarray \([1, 1, 2, 2, 3, 3]\) is good, but \([1, 1, 2, 2, 3, 3, 3]\) isn't: in the latter there are \(3\) occurrences of number \(3\), and no other element appears \(3\) times.
|
Input: 7 1 1 2 2 3 3 3 | Output: 6
|
Master
| 3 | 771 | 212 | 172 | 14 |
833 |
C
|
833C
|
C. Ever-Hungry Krakozyabra
| 2,700 |
brute force; combinatorics; greedy; math
|
Recently, a wild Krakozyabra appeared at Jelly Castle. It is, truth to be said, always eager to have something for dinner.Its favorite meal is natural numbers (typically served with honey sauce), or, to be more precise, the zeros in their corresponding decimal representations. As for other digits, Krakozyabra dislikes them; moreover, they often cause it indigestion! So, as a necessary precaution, Krakozyabra prefers to sort the digits of a number in non-descending order before proceeding to feast. Then, the leading zeros of the resulting number are eaten and the remaining part is discarded as an inedible tail.For example, if Krakozyabra is to have the number 57040 for dinner, its inedible tail would be the number 457.Slastyona is not really fond of the idea of Krakozyabra living in her castle. Hovewer, her natural hospitality prevents her from leaving her guest without food. Slastyona has a range of natural numbers from L to R, which she is going to feed the guest with. Help her determine how many distinct inedible tails are going to be discarded by Krakozyabra by the end of the dinner.
|
In the first and only string, the numbers L and R are given – the boundaries of the range (1 ≤ L ≤ R ≤ 1018).
|
Output the sole number – the answer for the problem.
|
In the first sample case, the inedible tails are the numbers from 1 to 9. Note that 10 and 1 have the same inedible tail – the number 1.In the second sample case, each number has a unique inedible tail, except for the pair 45, 54. The answer to this sample case is going to be (57 - 40 + 1) - 1 = 17.
|
Input: 1 10 | Output: 9
|
Master
| 4 | 1,103 | 109 | 52 | 8 |
2,053 |
F
|
2053F
|
F. Earnest Matrix Complement
| 2,600 |
brute force; data structures; dp; greedy; implementation; math
|
3, 2, 1, ... We are the — RiOI Team!— Felix & All, Special Thanks 3 Peter: Good news: My problem T311013 is approved! \(\delta\): I'm glad my computer had gone out of battery so that I wouldn't have participated in wyrqwq's round and gained a negative delta. Felix: [thumbs_up] The problem statement concerning a removed song! Aquawave: Do I mourn my Chemistry? E.Space: ahh? Trine: Bread. Iris: So why am I always testing problems? Time will pass, and we might meet again. Looking back at the past, everybody has lived the life they wanted.Aquawave has a matrix \(A\) of size \(n\times m\), whose elements can only be integers in the range \([1, k]\), inclusive. In the matrix, some cells are already filled with an integer, while the rest are currently not filled, denoted by \(-1\).You are going to fill in all the unfilled places in \(A\). After that, let \(c_{u,i}\) be the number of occurrences of element \(u\) in the \(i\)-th row. Aquawave defines the beauty of the matrix as$$$\(\sum_{u=1}^k \sum_{i=1}^{n-1} c_{u,i} \cdot c_{u,i+1}.\)\(You have to find the maximum possible beauty of \)A$$$ after filling in the blanks optimally.
|
The first line of input contains a single integer \(t\) (\(1 \leq t \leq 2\cdot 10^4\)) — the number of test cases. The description of test cases follows.The first line of each test case contains three integers \(n\), \(m\), and \(k\) (\(2 \leq n \leq 2\cdot 10^5\), \(2 \leq m \leq 2\cdot 10^5\), \(n \cdot m \leq 6\cdot 10^5\), \(1 \leq k \leq n\cdot m\)) — the number of rows and columns of the matrix \(A\), and the range of the integers in the matrix, respectively.Then \(n\) lines follow, the \(i\)-th line containing \(m\) integers \(A_{i,1},A_{i,2},\ldots,A_{i,m}\) (\(1 \leq A_{i,j} \leq k\) or \(A_{i,j} = -1\)) — the elements in \(A\).It is guaranteed that the sum of \(n\cdot m\) over all test cases does not exceed \(6\cdot 10^5\).
|
For each test case, output a single integer — the maximum possible beauty.
|
In the first test case, the matrix \(A\) is already determined. Its beauty is$$$\(\sum_{u=1}^k \sum_{i=1}^{n-1} c_{u,i} \cdot c_{u,i+1} = c_{1,1}\cdot c_{1,2} + c_{1,2}\cdot c_{1,3} + c_{2,1}\cdot c_{2,2} + c_{2,2}\cdot c_{2,3} + c_{3,1}\cdot c_{3,2} + c_{3,2}\cdot c_{3,3} = 1\cdot 1 + 1\cdot 1 + 2\cdot 0 + 0\cdot 1 + 0\cdot 2 + 2\cdot 1 = 4.\)\(In the second test case, one can fill the matrix as follows:\)\( \begin{bmatrix} 2 &3 &3 \\ 2 &2 &3 \end{bmatrix}, \)\(and get the value \)4\(. It can be proven this is the maximum possible answer one can get.In the third test case, one of the possible optimal configurations is:\)\( \begin{bmatrix} 1 &1 &1 \\ 1 &2 &1 \\ 1 &1 &4 \end{bmatrix}. \)\(In the fourth test case, one of the possible optimal configurations is:\)\( \begin{bmatrix} 1 &3 &2 &3 \\ 1 &3 &2 &1 \\ 3 &1 &5 &1 \end{bmatrix}. \)\(In the fifth test case, one of the possible optimal configurations is:\)\( \begin{bmatrix} 5 &5 &2 \\ 1 &8 &5 \\ 7 &5 &6 \\ 7 &7 &4 \\ 4 &4 &4 \end{bmatrix}. \)$$$
|
Input: 93 3 31 2 23 1 33 2 12 3 3-1 3 32 2 -13 3 6-1 -1 11 2 -1-1 -1 43 4 51 3 2 3-1 -1 2 -13 1 5 15 3 85 -1 21 8 -1-1 5 67 7 -14 4 46 6 5-1 -1 5 -1 -1 -1-1 -1 -1 -1 2 -1-1 1 3 3 -1 -1-1 1 -1 -1 -1 44 2 -1 -1 -1 4-1 -1 1 2 -1 -16 6 4-1 -1 -1 -1 1 -13 -1 2 2 4 -13 1 2 2 -1 -13 3 3 3 -1 2-1 3 3 -1 1 33 -1 2 2 3 -15 5 31 1 3 -1 12 2 -1 -1 3-1 -1 -1 2 -13 -1 -1 -1 2-1 1 2 3 -16 2 7-1 7-1 67 -1-1 -1-1 -12 2 | Output: 4 4 10 10 8 102 93 58 13
|
Expert
| 6 | 1,139 | 744 | 74 | 20 |
858 |
D
|
858D
|
D. Polycarp's phone book
| 1,600 |
data structures; implementation; sortings
|
There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then: if he enters 00 two numbers will show up: 100000000 and 100123456, if he enters 123 two numbers will show up 123456789 and 100123456, if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.
|
The first line contains single integer n (1 ≤ n ≤ 70000) — the total number of phone contacts in Polycarp's contacts.The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.
|
Print exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them.
|
Input: 3123456789100000000100123456 | Output: 900001
|
Medium
| 3 | 868 | 267 | 251 | 8 |
|
708 |
C
|
708C
|
C. Centroids
| 2,300 |
data structures; dfs and similar; dp; graphs; greedy; trees
|
Tree is a connected acyclic graph. Suppose you are given a tree consisting of n vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed .You are given a tree of size n and can perform no more than one edge replacement. Edge replacement is the operation of removing one edge from the tree (without deleting incident vertices) and inserting one new edge (without adding new vertices) in such a way that the graph remains a tree. For each vertex you have to determine if it's possible to make it centroid by performing no more than one edge replacement.
|
The first line of the input contains an integer n (2 ≤ n ≤ 400 000) — the number of vertices in the tree. Each of the next n - 1 lines contains a pair of vertex indices ui and vi (1 ≤ ui, vi ≤ n) — endpoints of the corresponding edge.
|
Print n integers. The i-th of them should be equal to 1 if the i-th vertex can be made centroid by replacing no more than one edge, and should be equal to 0 otherwise.
|
In the first sample each vertex can be made a centroid. For example, in order to turn vertex 1 to centroid one have to replace the edge (2, 3) with the edge (1, 3).
|
Input: 31 22 3 | Output: 1 1 1
|
Expert
| 6 | 655 | 234 | 167 | 7 |
865 |
A
|
865A
|
A. Save the problem!
| 1,400 |
constructive algorithms
|
Attention: we lost all the test cases for this problem, so instead of solving the problem, we need you to generate test cases. We're going to give you the answer, and you need to print a test case that produces the given answer. The original problem is in the following paragraph.People don't use cash as often as they used to. Having a credit card solves some of the hassles of cash, such as having to receive change when you can't form the exact amount of money needed to purchase an item. Typically cashiers will give you as few coins as possible in change, but they don't have to. For example, if your change is 30 cents, a cashier could give you a 5 cent piece and a 25 cent piece, or they could give you three 10 cent pieces, or ten 1 cent pieces, two 5 cent pieces, and one 10 cent piece. Altogether there are 18 different ways to make 30 cents using only 1 cent pieces, 5 cent pieces, 10 cent pieces, and 25 cent pieces. Two ways are considered different if they contain a different number of at least one type of coin. Given the denominations of the coins and an amount of change to be made, how many different ways are there to make change?As we mentioned before, we lost all the test cases for this problem, so we're actually going to give you the number of ways, and want you to produce a test case for which the number of ways is the given number. There could be many ways to achieve this (we guarantee there's always at least one), so you can print any, as long as it meets the constraints described below.
|
Input will consist of a single integer A (1 ≤ A ≤ 105), the desired number of ways.
|
In the first line print integers N and M (1 ≤ N ≤ 106, 1 ≤ M ≤ 10), the amount of change to be made, and the number of denominations, respectively.Then print M integers D1, D2, ..., DM (1 ≤ Di ≤ 106), the denominations of the coins. All denominations must be distinct: for any i ≠ j we must have Di ≠ Dj.If there are multiple tests, print any of them. You can print denominations in atbitrary order.
|
Input: 18 | Output: 30 41 5 10 25
|
Easy
| 1 | 1,520 | 83 | 399 | 8 |
|
1,117 |
B
|
1117B
|
B. Emotes
| 1,000 |
greedy; math; sortings
|
There are \(n\) emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The \(i\)-th emote increases the opponent's happiness by \(a_i\) units (we all know that emotes in this game are used to make opponents happy).You have time to use some emotes only \(m\) times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you cannot use the same emote more than \(k\) times in a row (otherwise the opponent will think that you're trolling him).Note that two emotes \(i\) and \(j\) (\(i \ne j\)) such that \(a_i = a_j\) are considered different.You have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.
|
The first line of the input contains three integers \(n, m\) and \(k\) (\(2 \le n \le 2 \cdot 10^5\), \(1 \le k \le m \le 2 \cdot 10^9\)) — the number of emotes, the number of times you can use emotes and the maximum number of times you may use the same emote in a row.The second line of the input contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\)), where \(a_i\) is value of the happiness of the \(i\)-th emote.
|
Print one integer — the maximum opponent's happiness if you use emotes in a way satisfying the problem statement.
|
In the first example you may use emotes in the following sequence: \(4, 4, 5, 4, 4, 5, 4, 4, 5\).
|
Input: 6 9 2 1 3 3 7 4 2 | Output: 54
|
Beginner
| 3 | 747 | 435 | 113 | 11 |
1,397 |
A
|
1397A
|
A. Juggling Letters
| 800 |
greedy; strings
|
You are given \(n\) strings \(s_1, s_2, \ldots, s_n\) consisting of lowercase Latin letters.In one operation you can remove a character from a string \(s_i\) and insert it to an arbitrary position in a string \(s_j\) (\(j\) may be equal to \(i\)). You may perform this operation any number of times. Is it possible to make all \(n\) strings equal?
|
The first line contains \(t\) (\(1 \le t \le 10\)): the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 1000\)): the number of strings.\(n\) lines follow, the \(i\)-th line contains \(s_i\) (\(1 \le \lvert s_i \rvert \le 1000\)).The sum of lengths of all strings in all test cases does not exceed \(1000\).
|
If it is possible to make the strings equal, print ""YES"" (without quotes).Otherwise, print ""NO"" (without quotes).You can output each character in either lowercase or uppercase.
|
In the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings ""ca"" and ""cbab"" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to ""cab"". In the second test case, it is impossible to make all \(n\) strings equal.
|
Input: 4 2 caa cbb 3 cba cba cbb 4 ccab cbac bca acbcc 4 acb caf c cbafc | Output: YES NO YES NO
|
Beginner
| 2 | 347 | 359 | 180 | 13 |
842 |
D
|
842D
|
D. Vitya and Strange Lesson
| 2,000 |
binary search; data structures
|
Today at the lesson Vitya learned a very interesting function — mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, mex([4, 33, 0, 1, 1, 5]) = 2 and mex([1, 2, 3]) = 0.Vitya quickly understood all tasks of the teacher, but can you do the same?You are given an array consisting of n non-negative integers, and m queries. Each query is characterized by one number x and consists of the following consecutive steps: Perform the bitwise addition operation modulo 2 (xor) of each array element with the number x. Find mex of the resulting array. Note that after each query the array changes.
|
First line contains two integer numbers n and m (1 ≤ n, m ≤ 3·105) — number of elements in array and number of queries.Next line contains n integer numbers ai (0 ≤ ai ≤ 3·105) — elements of then array.Each of next m lines contains query — one integer number x (0 ≤ x ≤ 3·105).
|
For each query print the answer on a separate line.
|
Input: 2 21 313 | Output: 10
|
Hard
| 2 | 664 | 276 | 51 | 8 |
|
888 |
D
|
888D
|
D. Almost Identity Permutations
| 1,600 |
combinatorics; dp; math
|
A permutation p of size n is an array such that every integer from 1 to n occurs exactly once in this array.Let's call a permutation an almost identity permutation iff there exist at least n - k indices i (1 ≤ i ≤ n) such that pi = i.Your task is to count the number of almost identity permutations for given numbers n and k.
|
The first line contains two integers n and k (4 ≤ n ≤ 1000, 1 ≤ k ≤ 4).
|
Print the number of almost identity permutations for given n and k.
|
Input: 4 1 | Output: 1
|
Medium
| 3 | 325 | 71 | 67 | 8 |
|
1,753 |
A1
|
1753A1
|
A1. Make Nonzero Sum (easy version)
| 1,300 |
constructive algorithms; dp; greedy
|
This is the easy version of the problem. The difference is that in this version the array can not contain zeros. You can make hacks only if both versions of the problem are solved.You are given an array \([a_1, a_2, \ldots a_n]\) consisting of integers \(-1\) and \(1\). You have to build a partition of this array into the set of segments \([l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]\) with the following property: Denote the alternating sum of all elements of the \(i\)-th segment as \(s_i\): \(s_i\) = \(a_{l_i} - a_{l_i+1} + a_{l_i+2} - a_{l_i+3} + \ldots \pm a_{r_i}\). For example, the alternating sum of elements of segment \([2, 4]\) in array \([1, 0, -1, 1, 1]\) equals to \(0 - (-1) + 1 = 2\). The sum of \(s_i\) over all segments of partition should be equal to zero. Note that each \(s_i\) does not have to be equal to zero, this property is about sum of \(s_i\) over all segments of partition.The set of segments \([l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]\) is called a partition of the array \(a\) of length \(n\) if \(1 = l_1 \le r_1, l_2 \le r_2, \ldots, l_k \le r_k = n\) and \(r_i + 1 = l_{i+1}\) for all \(i = 1, 2, \ldots k-1\). In other words, each element of the array must belong to exactly one segment.You have to build a partition of the given array with properties described above or determine that such partition does not exist.Note that it is not required to minimize the number of segments in the partition.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10\,000\)). Description of the test cases follows.The first line of each test case contains an integer \(n\) (\(1 \le n \le 200\,000\)) — the length of the array \(a\).The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(a_i\) is \(-1\) or \(1\)) — the elements of the given array.It's guaranteed that the sum of \(n\) over all test cases does not exceed \(200\,000\).
|
For each test case, if required partition does not exist, print \(-1\). Otherwise, print an integer \(k\) — the number of segments in the partition. Then in the \(i\)-th of the following \(k\) lines print two integers \(l_i\) and \(r_i\) — description of the \(i\)-th segment. The following conditions should be satisfied: \(l_i \le r_i\) for each \(i\) from \(1\) to \(k\). \(l_{i + 1} = r_i + 1\) for each \(i\) from \(1\) to \((k - 1)\). \(l_1 = 1, r_k = n\). If there are multiple correct partitions of the array, print any of them.
|
In the first test case we can build a partition of one segment of length \(4\). The sum of this segment will be equal to \(1 - 1 + 1 - 1 = 0\).In the second test case we can build a partition of two segments of length \(3\). The sum of the first segment will be equal to \(-1 -1 + 1 = -1\), and the sum of the second segment: \(1 - 1 + 1 = 1\). So, the total sum will be equal to \(-1 + 1 = 0\).In the third and in the fourth test cases it can be proved that there are no required partition.
|
Input: 441 1 1 16-1 1 1 1 1 131 -1 111 | Output: 1 1 4 2 1 3 4 6 -1 -1
|
Easy
| 3 | 1,438 | 512 | 536 | 17 |
355 |
B
|
355B
|
B. Vasya and Public Transport
| 1,100 |
greedy; implementation
|
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.Public transport is not free. There are 4 types of tickets: A ticket for one ride on some bus or trolley. It costs c1 burles; A ticket for an unlimited number of rides on some bus or on some trolley. It costs c2 burles; A ticket for an unlimited number of rides on all buses or all trolleys. It costs c3 burles; A ticket for an unlimited number of rides on all buses and trolleys. It costs c4 burles. Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.
|
The first line contains four integers c1, c2, c3, c4 (1 ≤ c1, c2, c3, c4 ≤ 1000) — the costs of the tickets.The second line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of buses and trolleys Vasya is going to use.The third line contains n integers ai (0 ≤ ai ≤ 1000) — the number of times Vasya is going to use the bus number i.The fourth line contains m integers bi (0 ≤ bi ≤ 1000) — the number of times Vasya is going to use the trolley number i.
|
Print a single number — the minimum sum of burles Vasya will have to spend on the tickets.
|
In the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2·1) + 3 + 7 = 12 burles.In the second sample the profitable strategy is to buy one ticket of the fourth type.In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys.
|
Input: 1 3 7 192 32 54 4 4 | Output: 12
|
Easy
| 2 | 826 | 464 | 90 | 3 |
1,381 |
C
|
1381C
|
C. Mastermind
| 2,500 |
constructive algorithms; graph matchings; greedy; implementation; sortings; two pointers
|
In the game of Mastermind, there are two players — Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of \(n\) colors. There are exactly \(n+1\) colors in the entire universe, numbered from \(1\) to \(n+1\) inclusive.When Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers \(x\) and \(y\).The first integer \(x\) is the number of indices where Bob's guess correctly matches Alice's code. The second integer \(y\) is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, \(y\) is the maximum number of indices he could get correct.For example, suppose \(n=5\), Alice's code is \([3,1,6,1,2]\), and Bob's guess is \([3,1,1,2,5]\). At indices \(1\) and \(2\) colors are equal, while in the other indices they are not equal. So \(x=2\). And the two codes have the four colors \(1,1,2,3\) in common, so \(y=4\). Solid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. \(x\) is the number of solid lines, and \(y\) is the total number of lines. You are given Bob's guess and two values \(x\) and \(y\). Can you find one possibility of Alice's code so that the values of \(x\) and \(y\) are correct?
|
The first line contains a single integer \(t\) (\(1\le t\le 1000\)) — the number of test cases. Next \(2t\) lines contain descriptions of test cases.The first line of each test case contains three integers \(n,x,y\) (\(1\le n\le 10^5, 0\le x\le y\le n\)) — the length of the codes, and two values Alice responds with.The second line of each test case contains \(n\) integers \(b_1,\ldots,b_n\) (\(1\le b_i\le n+1\)) — Bob's guess, where \(b_i\) is the \(i\)-th color of the guess.It is guaranteed that the sum of \(n\) across all test cases does not exceed \(10^5\).
|
For each test case, on the first line, output ""YES"" if there is a solution, or ""NO"" if there is no possible secret code consistent with the described situation. You can print each character in any case (upper or lower).If the answer is ""YES"", on the next line output \(n\) integers \(a_1,\ldots,a_n\) (\(1\le a_i\le n+1\)) — Alice's secret code, where \(a_i\) is the \(i\)-th color of the code.If there are multiple solutions, output any.
|
The first test case is described in the statement.In the second test case, \(x=3\) because the colors are equal at indices \(2,4,5\). And \(y=4\) because they share the colors \(1,1,1,2\).In the third test case, \(x=0\) because there is no index where the colors are the same. But \(y=4\) because they share the colors \(3,3,5,5\).In the fourth test case, it can be proved that no solution exists.
|
Input: 7 5 2 4 3 1 1 2 5 5 3 4 1 1 2 1 2 4 0 4 5 5 3 3 4 1 4 2 3 2 3 6 1 2 3 2 1 1 1 1 6 2 4 3 3 2 1 1 1 6 2 6 1 1 3 2 1 1 | Output: YES 3 1 6 1 2 YES 3 1 1 1 2 YES 3 3 5 5 NO YES 4 4 4 4 3 1 YES 3 1 3 1 7 7 YES 2 3 1 1 1 1
|
Expert
| 6 | 1,340 | 566 | 444 | 13 |
1,651 |
E
|
1651E
|
E. Sum of Matchings
| 2,600 |
brute force; combinatorics; constructive algorithms; dfs and similar; graph matchings; greedy; math
|
Let's denote the size of the maximum matching in a graph \(G\) as \(\mathit{MM}(G)\).You are given a bipartite graph. The vertices of the first part are numbered from \(1\) to \(n\), the vertices of the second part are numbered from \(n+1\) to \(2n\). Each vertex's degree is \(2\).For a tuple of four integers \((l, r, L, R)\), where \(1 \le l \le r \le n\) and \(n+1 \le L \le R \le 2n\), let's define \(G'(l, r, L, R)\) as the graph which consists of all vertices of the given graph that are included in the segment \([l, r]\) or in the segment \([L, R]\), and all edges of the given graph such that each of their endpoints belongs to one of these segments. In other words, to obtain \(G'(l, r, L, R)\) from the original graph, you have to remove all vertices \(i\) such that \(i \notin [l, r]\) and \(i \notin [L, R]\), and all edges incident to these vertices.Calculate the sum of \(\mathit{MM}(G(l, r, L, R))\) over all tuples of integers \((l, r, L, R)\) having \(1 \le l \le r \le n\) and \(n+1 \le L \le R \le 2n\).
|
The first line contains one integer \(n\) (\(2 \le n \le 1500\)) — the number of vertices in each part.Then \(2n\) lines follow, each denoting an edge of the graph. The \(i\)-th line contains two integers \(x_i\) and \(y_i\) (\(1 \le x_i \le n\); \(n + 1 \le y_i \le 2n\)) — the endpoints of the \(i\)-th edge.There are no multiple edges in the given graph, and each vertex has exactly two incident edges.
|
Print one integer — the sum of \(\mathit{MM}(G(l, r, L, R))\) over all tuples of integers \((l, r, L, R)\) having \(1 \le l \le r \le n\) and \(n+1 \le L \le R \le 2n\).
|
Input: 5 4 6 4 9 2 6 3 9 1 8 5 10 2 7 3 7 1 10 5 8 | Output: 314
|
Expert
| 7 | 1,024 | 405 | 169 | 16 |
|
1,735 |
D
|
1735D
|
D. Meta-set
| 1,700 |
brute force; combinatorics; data structures; hashing; math
|
You like the card board game ""Set"". Each card contains \(k\) features, each of which is equal to a value from the set \(\{0, 1, 2\}\). The deck contains all possible variants of cards, that is, there are \(3^k\) different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all \(k\) features are good for them.For example, the cards \((0, 0, 0)\), \((0, 2, 1)\), and \((0, 1, 2)\) form a set, but the cards \((0, 2, 2)\), \((2, 1, 2)\), and \((1, 2, 0)\) do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given \(n\) distinct cards?
|
The first line of the input contains two integers \(n\) and \(k\) (\(1 \le n \le 10^3\), \(1 \le k \le 20\)) — the number of cards on a table and the number of card features. The description of the cards follows in the next \(n\) lines.Each line describing a card contains \(k\) integers \(c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}\) (\(0 \le c_{i, j} \le 2\)) — card features. It is guaranteed that all cards are distinct.
|
Output one integer — the number of meta-sets.
|
Let's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: \(1\), \(2\), \(3\). The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards \((0000,\ 0001,\ 0002,\ 0010,\ 0020)\). The sets in it are the triples \((0000,\ 0001,\ 0002)\) and \((0000,\ 0010,\ 0020)\). Also, a set is the triple \((0100,\ 1000,\ 2200)\) which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: \((0000,\ 0001,\ 0002,\ 0010,\ 0020)\), \((0000,\ 0001,\ 0002,\ 0100,\ 0200)\), \((0000,\ 0010,\ 0020,\ 0100,\ 0200)\). In there third test, there are \(54\) meta-sets.
|
Input: 8 4 0 0 0 0 0 0 0 1 0 0 0 2 0 0 1 0 0 0 2 0 0 1 0 0 1 0 0 0 2 2 0 0 | Output: 1
|
Medium
| 5 | 761 | 418 | 45 | 17 |
1,795 |
F
|
1795F
|
F. Blocking Chips
| 2,400 |
binary search; constructive algorithms; dfs and similar; greedy; trees
|
You are given a tree, consisting of \(n\) vertices. There are \(k\) chips, placed in vertices \(a_1, a_2, \dots, a_k\). All \(a_i\) are distinct. Vertices \(a_1, a_2, \dots, a_k\) are colored black initially. The remaining vertices are white.You are going to play a game where you perform some moves (possibly, zero). On the \(i\)-th move (\(1\)-indexed) you are going to move the \(((i - 1) \bmod k + 1)\)-st chip from its current vertex to an adjacent white vertex and color that vertex black. So, if \(k=3\), you move chip \(1\) on move \(1\), chip \(2\) on move \(2\), chip \(3\) on move \(3\), chip \(1\) on move \(4\), chip \(2\) on move \(5\) and so on. If there is no adjacent white vertex, then the game ends.What's the maximum number of moves you can perform?
|
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of testcases.The first line of each testcase contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) — the number of vertices of the tree.Each of the next \(n - 1\) lines contains two integers \(v\) and \(u\) (\(1 \le v, u \le n\)) — the descriptions of the edges. The given edges form a tree.The next line contains a single integer \(k\) (\(1 \le k \le n\)) — the number of chips.The next line contains \(k\) integers \(a_1, a_2, \dots, a_k\) (\(1 \le a_i \le n\)) — the vertices with the chips. All \(a_i\) are distinct.The sum of \(n\) over all testcases doesn't exceed \(2 \cdot 10^5\).
|
For each testcase, print a single integer — the maximum number of moves you can perform.
|
Input: 551 22 33 44 51351 22 33 44 521 251 22 33 44 522 161 21 32 42 53 631 4 6111 | Output: 2 0 1 2 0
|
Expert
| 5 | 769 | 680 | 88 | 17 |
|
698 |
B
|
698B
|
B. Fix a Tree
| 1,700 |
constructive algorithms; dfs and similar; dsu; graphs; trees
|
A tree is an undirected connected graph without cycles.Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent). For this rooted tree the array p is [2, 3, 3, 2]. Given a sequence p1, p2, ..., pn, one is able to restore a tree: There must be exactly one index r that pr = r. A vertex r is a root of the tree. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi. A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
|
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
|
In the first line print the minimum number of elements to change, in order to get a valid sequence.In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
|
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red. In the second sample, the given sequence is already valid.
|
Input: 42 3 3 4 | Output: 12 3 4 4
|
Medium
| 5 | 1,151 | 170 | 280 | 6 |
312 |
B
|
312B
|
B. Archer
| 1,300 |
math; probabilities
|
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
|
A single line contains four integers .
|
Print a single real number, the probability that SmallR will win the match.The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
|
Input: 1 2 1 2 | Output: 0.666666666667
|
Easy
| 2 | 331 | 38 | 169 | 3 |
|
144 |
B
|
144B
|
B. Meeting
| 1,300 |
implementation
|
The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at the integer points of the plane. At each integer point which belongs to the table perimeter there is a chair in which a general sits.Some points on the plane contain radiators for the generals not to freeze in winter. Each radiator is characterized by the number ri — the radius of the area this radiator can heat. That is, if the distance between some general and the given radiator is less than or equal to ri, than the general feels comfortable and warm. Here distance is defined as Euclidean distance, so the distance between points (x1, y1) and (x2, y2) is Each general who is located outside the radiators' heating area can get sick. Thus, you should bring him a warm blanket. Your task is to count the number of warm blankets you should bring to the Super Duper Secret Place.The generals who are already comfortable do not need a blanket. Also the generals never overheat, ever if they are located in the heating area of several radiators. The radiators can be located at any integer points on the plane, even inside the rectangle (under the table) or on the perimeter (directly under some general). Even in this case their radius does not change.
|
The first input line contains coordinates of two opposite table corners xa, ya, xb, yb (xa ≠ xb, ya ≠ yb). The second line contains integer n — the number of radiators (1 ≤ n ≤ 103). Then n lines contain the heaters' coordinates as ""xi yi ri"", the numbers are separated by spaces. All input data numbers are integers. The absolute value of all coordinates does not exceed 1000, 1 ≤ ri ≤ 1000. Several radiators can be located at the same point.
|
Print the only number — the number of blankets you should bring.
|
In the first sample the generals are sitting at points: (2, 2), (2, 3), (2, 4), (2, 5), (3, 2), (3, 5), (4, 2), (4, 3), (4, 4), (4, 5). Among them, 4 generals are located outside the heating range. They are the generals at points: (2, 5), (3, 5), (4, 4), (4, 5).In the second sample the generals are sitting at points: (5, 2), (5, 3), (6, 2), (6, 3). All of them are located inside the heating range.
|
Input: 2 5 4 233 1 25 3 11 3 2 | Output: 4
|
Easy
| 1 | 1,475 | 446 | 64 | 1 |
2,077 |
C
|
2077C
|
C. Binary Subsequence Value Sum
| 2,300 |
combinatorics; data structures; dp; fft; math; matrices
|
Last | Moment - onoken For a binary string\(^{\text{∗}}\) \(v\), the score of \(v\) is defined as the maximum value of $$$\(F\big(v, 1, i\big) \cdot F\big(v, i+1, |v|\big)\)\( over all \)i\( (\)0 \leq i \leq |v|\().Here, \)F\big(v, l, r\big) = r - l + 1 - 2 \cdot \operatorname{zero}(v, l, r)\(, where \)\operatorname{zero}(v, l, r)\( denotes the number of \)\mathtt{0}\(s in \)v_lv_{l+1} \ldots v_r\(. If \)l > r\(, then \)F\big(v, l, r\big) = 0\(.You are given a binary string \)s\( of length \)n\( and a positive integer \)q\(.You will be asked \)q\( queries.In each query, you are given an integer \)i\( (\)1 \leq i \leq n\(). You must flip \)s_i\( from \)\mathtt{0}\( to \)\mathtt{1}\( (or from \)\mathtt{1}\( to \)\mathtt{0}\(). Find the sum of the scores over all non-empty subsequences\)^{\text{†}}\( of \)s\( after each modification query. Since the result may be large, output the answer modulo \)998\,244\,353\(.Note that the modifications are persistent.\)^{\text{∗}}\(A binary string is a string that consists only of the characters \)\mathtt{0}\( and \)\mathtt{1}\(.\)^{\text{†}}\(A binary string \)x\( is a subsequence of a binary string \)y\( if \)x\( can be obtained from \)y$$$ by deleting several (possibly zero or all) characters.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The first line of each test case contains two integers \(n\) and \(q\) (\(1 \leq n \leq 2 \cdot 10^5\), \(1 \leq q \leq 2 \cdot 10^5\)) — the length of the string \(s\) and the number of modification queries, respectively.The second line contains the binary string \(s\) of length \(n\), consisting of characters \(\mathtt{0}\) and \(\mathtt{1}\).The following \(q\) lines each contain an integer \(i\) (\(1 \leq i \leq n\)), indicating that \(s_i\) is flipped from \(\mathtt{0}\) to \(\mathtt{1}\) or from \(\mathtt{1}\) to \(\mathtt{0}\).It is guaranteed that neither the total sum of all values of \(n\) nor the total sum of all values of \(q\) across all test cases exceeds \(2 \cdot 10^5\).
|
For each test case, output \(q\) lines, each line containing a single integer — the required sum modulo \(998\,244\,353\).
|
For the first test case, after the first modification, we have \(s = \texttt{110}\). We can compute the sum of scores over all subsequences as follows: IndicesSubsequenceScore\(1\)1\(0\)\(2\)1\(0\)\(1, 2\)11\(1\)\(3\)0\(0\)\(1, 3\)10\(0\)\(2, 3\)10\(0\)\(1, 2, 3\)110\(0\) Summing up: \(0+0+1+0+0+0+0 = 1\).After the second modification, we have \(s = \texttt{111}\). We can compute the sum of scores over all subsequences as follows: IndicesSubsequenceScore\(1\)1\(0\)\(2\)1\(0\)\(1, 2\)11\(1\)\(3\)1\(0\)\(1, 3\)11\(1\)\(2, 3\)11\(1\)\(1, 2, 3\)111\(2\) Summing up: \(0+0+1+0+1+1+2 = 5\).
|
Input: 33 20101310 30101000110351024 101100110011000010111100024 | Output: 1 5 512 768 1536 23068672
|
Expert
| 6 | 1,250 | 857 | 122 | 20 |
1,861 |
F
|
1861F
|
F. Four Suits
| 3,200 |
binary search; bitmasks; flows; greedy
|
The game of Berland poker is played as follows. There are \(n+1\) people: \(n\) players, numbered from \(1\) to \(n\), and the dealer. The dealer has a deck which contains cards of four different suits (the number of cards of each suit is not necessarily the same); the number of cards in the deck is divisible by \(n\). The dealer gives all cards to the players, so that every player receives the same number of cards, and the whole deck is used.After the cards are dealt, every player chooses one of four suits (independently) and discards all cards from their hand which do not belong to their chosen suit. The winner of the game is the player with the maximum number of cards left in their hand. The number of points the winner receives is \(x - y\), where \(x\) is the number of cards in the winner's hand, and \(y\) is the maximum number of cards among all other players; everyone else receives \(0\) points. Note that it means that if there are multiple players with the maximum number of cards, everyone receives \(0\) points.Since every player wants to maximize their odds to win, they will choose a suit with the maximum number of cards in their hand.Monocarp is the dealer. He has already given some cards to the players; the \(i\)-th player received \(a_{i,j}\) cards of suit \(j\). Note that the number of cards in players' hands don't have to be the same at this moment. Monocarp has \(b_1, b_2, b_3, b_4\) cards of suit \(1, 2, 3, 4\) respectively left in his deck. He has to give them to the players so that, after all cards are dealt, every player has the same number of cards.For each player, calculate the maximum number of points they can receive among all ways to deal the remaining cards according to the rules of the game.
|
The first line of the input contains one integer \(n\) (\(2 \le n \le 5 \cdot 10^4\)) — the number of players.Then \(n\) lines follow. The \(i\)-th of them contains four integers \(a_{i,1}, a_{i,2}, a_{i,3}, a_{i,4}\) (\(0 \le a_{i,j} \le 10^6\)), where \(a_{i,j}\) is the number of cards of the \(j\)-th suit that the \(i\)-th player currently has.The last line contains \(4\) integers \(b_1, b_2, b_3, b_4\) (\(0 \le b_j \le 10^6\)), where \(b_j\) is the number of cards of the \(j\)-th suit Monocarp has to deal yet.Additional constraint on the input: it is possible to deal all of the remaining cards so that every player has the same number of cards.
|
Print \(n\) integers. The \(i\)-th of them should be the maximum number of points the \(i\)-th player can get among all possible ways to deal the remaining cards.
|
Input: 2 3 1 1 1 1 1 1 1 2 2 0 0 | Output: 1 0
|
Master
| 4 | 1,745 | 655 | 162 | 18 |
|
400 |
C
|
400C
|
C. Inna and Huge Candy Matrix
| 1,500 |
implementation; math
|
Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns — from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (xk, yk).The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like. Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!
|
The first line of the input contains fix integers n, m, x, y, z, p (1 ≤ n, m ≤ 109; 0 ≤ x, y, z ≤ 109; 1 ≤ p ≤ 105).Each of the following p lines contains two integers xk, yk (1 ≤ xk ≤ n; 1 ≤ yk ≤ m) — the initial coordinates of the k-th candy. Two candies can lie on the same cell.
|
For each of the p candies, print on a single line its space-separated new coordinates.
|
Just for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix:QWER REWQ ASDF -> FDSAZXCV VCXZ
|
Input: 3 3 3 1 1 91 11 21 32 12 22 33 13 23 3 | Output: 1 31 21 12 32 22 13 33 23 1
|
Medium
| 2 | 1,178 | 282 | 86 | 4 |
1,969 |
A
|
1969A
|
A. Two Friends
| 800 |
constructive algorithms; implementation; math
|
Monocarp wants to throw a party. He has \(n\) friends, and he wants to have at least \(2\) of them at his party.The \(i\)-th friend's best friend is \(p_i\). All \(p_i\) are distinct, and for every \(i \in [1, n]\), \(p_i \ne i\).Monocarp can send invitations to friends. The \(i\)-th friend comes to the party if both the \(i\)-th friend and the \(p_i\)-th friend receive an invitation (note that the \(p_i\)-th friend doesn't have to actually come to the party). Each invitation is sent to exactly one of the friends.For example, if \(p = [3, 1, 2, 5, 4]\), and Monocarp sends invitations to the friends \([1, 2, 4, 5]\), then the friends \([2, 4, 5]\) will come to the party. The friend \(1\) won't come since his best friend didn't receive an invitation; the friend \(3\) won't come since he didn't receive an invitation.Calculate the minimum number of invitations Monocarp has to send so that at least \(2\) friends come to the party.
|
The first line contains one integer \(t\) (\(1 \le t \le 5000\)) — the number of test cases.Each test case consists of two lines: the first line contains one integer \(n\) (\(2 \le n \le 50\)) — the number of friends; the second line contains \(n\) integers \(p_1, p_2, \dots, p_n\) (\(1 \le p_i \le n\); \(p_i \ne i\); all \(p_i\) are distinct).
|
Print one integer — the minimum number of invitations Monocarp has to send.
|
In the first testcase, Monocarp can send invitations to friends \(4\) and \(5\). Both of them will come to the party since they are each other's best friends, and both of them have invitations.In the second testcase, Monocarp can send invitations to friends \(1, 2\) and \(3\), for example. Then friends \(1\) and \(2\) will attend: friend \(1\) and his best friend \(2\) have invitations, friend \(2\) and his best friend \(3\) have invitations. Friend \(3\) won't attend since his friend \(4\) doesn't have an invitation. It's impossible to send invitations to fewer than \(3\) friends in such a way that at least \(2\) come.In the third testcase, Monocarp can send invitations to both friends \(1\) and \(2\), and both of them will attend.
|
Input: 353 1 2 5 442 3 4 122 1 | Output: 2 3 2
|
Beginner
| 3 | 939 | 346 | 75 | 19 |
1,091 |
E
|
1091E
|
E. New Year and the Acquaintance Estimation
| 2,400 |
binary search; data structures; graphs; greedy; implementation; math; sortings
|
Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if \(a\) is a friend of \(b\), then \(b\) is also a friend of \(a\). Each user thus has a non-negative amount of friends.This morning, somebody anonymously sent Bob the following link: graph realization problem and Bob wants to know who that was. In order to do that, he first needs to know how the social network looks like. He investigated the profile of every other person on the network and noted down the number of his friends. However, he neglected to note down the number of his friends. Help him find out how many friends he has. Since there may be many possible answers, print all of them.
|
The first line contains one integer \(n\) (\(1 \leq n \leq 5 \cdot 10^5\)), the number of people on the network excluding Bob. The second line contains \(n\) numbers \(a_1,a_2, \dots, a_n\) (\(0 \leq a_i \leq n\)), with \(a_i\) being the number of people that person \(i\) is a friend of.
|
Print all possible values of \(a_{n+1}\) — the amount of people that Bob can be friend of, in increasing order.If no solution exists, output \(-1\).
|
In the first test case, the only solution is that everyone is friends with everyone. That is why Bob should have \(3\) friends.In the second test case, there are three possible solutions (apart from symmetries): \(a\) is friend of \(b\), \(c\) is friend of \(d\), and Bob has no friends, or \(a\) is a friend of \(b\) and both \(c\) and \(d\) are friends with Bob, or Bob is friends of everyone. The third case is impossible to solve, as the second person needs to be a friend with everybody, but the first one is a complete stranger.
|
Input: 33 3 3 | Output: 3
|
Expert
| 7 | 728 | 288 | 148 | 10 |
1,375 |
B
|
1375B
|
B. Neighbor Grid
| 1,200 |
constructive algorithms; greedy
|
You are given a grid with \(n\) rows and \(m\) columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number \(k > 0\) written on it, then exactly \(k\) of its neighboring cells have a number greater than \(0\) written on them. Note that if the number in the cell is \(0\), there is no such restriction on neighboring cells.You are allowed to take any number in the grid and increase it by \(1\). You may apply this operation as many times as you want, to any numbers you want. Perform some operations (possibly zero) to make the grid good, or say that it is impossible. If there are multiple possible answers, you may find any of them.Two cells are considered to be neighboring if they have a common edge.
|
The input consists of multiple test cases. The first line contains an integer \(t\) (\(1 \le t \le 5000\)) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers \(n\) and \(m\) (\(2 \le n, m \le 300\)) — the number of rows and columns, respectively.The following \(n\) lines contain \(m\) integers each, the \(j\)-th element in the \(i\)-th line \(a_{i, j}\) is the number written in the \(j\)-th cell of the \(i\)-th row (\(0 \le a_{i, j} \le 10^9\)).It is guaranteed that the sum of \(n \cdot m\) over all test cases does not exceed \(10^5\).
|
If it is impossible to obtain a good grid, print a single line containing ""NO"".Otherwise, print a single line containing ""YES"", followed by \(n\) lines each containing \(m\) integers, which describe the final state of the grid. This final grid should be obtainable from the initial one by applying some operations (possibly zero).If there are multiple possible answers, you may print any of them.
|
In the first test case, we can obtain the resulting grid by increasing the number in row \(2\), column \(3\) once. Both of the cells that contain \(1\) have exactly one neighbor that is greater than zero, so the grid is good. Many other solutions exist, such as the grid $$$\(0\;1\;0\;0\)\( \)\(0\;2\;1\;0\)\( \)\(0\;0\;0\;0\)$$$ All of them are accepted as valid answers.In the second test case, it is impossible to make the grid good.In the third test case, notice that no cell has a number greater than zero on it, so the grid is automatically good.
|
Input: 5 3 4 0 0 0 0 0 1 0 0 0 0 0 0 2 2 3 0 0 0 2 2 0 0 0 0 2 3 0 0 0 0 4 0 4 4 0 0 0 0 0 2 0 1 0 0 0 0 0 0 0 0 | Output: YES 0 0 0 0 0 1 1 0 0 0 0 0 NO YES 0 0 0 0 NO YES 0 1 0 0 1 4 2 1 0 2 0 0 1 3 1 0
|
Easy
| 2 | 802 | 615 | 400 | 13 |
1,155 |
F
|
1155F
|
F. Delivery Oligopoly
| 2,800 |
brute force; dp; graphs
|
The whole delivery market of Berland is controlled by two rival companies: BerEx and BerPS. They both provide fast and reliable delivery services across all the cities of Berland.The map of Berland can be represented as an undirected graph. The cities are vertices and the roads are edges between them. Each pair of cities has no more than one road between them. Each road connects different cities.BerEx and BerPS are so competitive that for each pair of cities \((v, u)\) they have set up their paths from \(v\) to \(u\) in such a way that these two paths don't share a single road. It is guaranteed that it was possible.Now Berland government decided to cut down the road maintenance cost by abandoning some roads. Obviously, they want to maintain as little roads as possible. However, they don't want to break the entire delivery system. So BerEx and BerPS should still be able to have their paths between every pair of cities non-intersecting.What is the minimal number of roads Berland government can maintain?More formally, given a 2-edge connected undirected graph, what is the minimum number of edges that can be left in it so that the resulting graph is also 2-edge connected?
|
The first line contains two integers \(n\) and \(m\) (\(3 \le n \le 14\), \(n \le m \le \frac{n(n - 1)}{2}\)) — the number of cities and the number of roads between them.Each of the next \(m\) lines contains two integers \(v\) and \(u\) (\(1 \le v, u \le n\), \(v \ne u\)) — the cities connected by the next road. It is guaranteed that each pair of cities has no more than one road between them. It is guaranteed that each pair of cities have at least two paths between them that don't share a single road.
|
The first line should contain a single integer \(k\) — the minimum number of roads Berland government can maintain so that BerEx and BerPS are still able to have their paths between every pair of cities non-intersecting.The next \(k\) lines should contain the list of roads which are being maintained. Each line of form ""\(v~u\)"", where \(v\) and \(u\) are cities connected by the next road.If there are multiple lists of minimum size, print any of them. The order of roads in the list doesn't matter.
|
Here are graphs from the examples, red edges are the maintained ones.
|
Input: 3 3 1 2 2 3 3 1 | Output: 3 1 3 3 2 1 2
|
Master
| 3 | 1,186 | 506 | 503 | 11 |
1,343 |
F
|
1343F
|
F. Restore the Permutation by Sorted Segments
| 2,400 |
brute force; constructive algorithms; data structures; greedy; implementation
|
We guessed a permutation \(p\) consisting of \(n\) integers. The permutation of length \(n\) is the array of length \(n\) where each element from \(1\) to \(n\) appears exactly once. This permutation is a secret for you.For each position \(r\) from \(2\) to \(n\) we chose some other index \(l\) (\(l < r\)) and gave you the segment \(p_l, p_{l + 1}, \dots, p_r\) in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly \(n-1\) segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order.For example, if the secret permutation is \(p=[3, 1, 4, 6, 2, 5]\) then the possible given set of segments can be: \([2, 5, 6]\) \([4, 6]\) \([1, 3, 4]\) \([1, 3]\) \([1, 2, 4, 6]\) Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists).You have to answer \(t\) independent test cases.
|
The first line of the input contains one integer \(t\) (\(1 \le t \le 100\)) — the number of test cases. Then \(t\) test cases follow.The first line of the test case contains one integer \(n\) (\(2 \le n \le 200\)) — the length of the permutation.The next \(n-1\) lines describe given segments.The \(i\)-th line contains the description of the \(i\)-th segment. The line starts with the integer \(k_i\) (\(2 \le k_i \le n\)) — the length of the \(i\)-th segment. Then \(k_i\) integers follow. All integers in a line are distinct, sorted in ascending order, between \(1\) and \(n\), inclusive.It is guaranteed that the required \(p\) exists for each test case.It is also guaranteed that the sum of \(n\) over all test cases does not exceed \(200\) (\(\sum n \le 200\)).
|
For each test case, print the answer: \(n\) integers \(p_1, p_2, \dots, p_n\) (\(1 \le p_i \le n\), all \(p_i\) should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input).
|
Input: 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 | Output: 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1
|
Expert
| 5 | 1,086 | 768 | 219 | 13 |
|
2,061 |
H2
|
2061H2
|
H2. Kevin and Stones (Hard Version)
| 3,500 |
flows; graphs
|
This is the hard version of the problem. The difference between the versions is that in this version, you need to output a valid sequence of operations if one exists. You can hack only if you solved all versions of this problem. Kevin has an undirected graph with \(n\) vertices and \(m\) edges. Initially, some vertices contain stones, which Kevin wants to move to new positions. Kevin can perform the following operation: For each stone at \(u_i\), select a neighboring vertex \(v_i\). Simultaneously move each stone from \(u_i\) to its corresponding \(v_i\). At any time, each vertex can contain at most one stone.Determine whether a valid sequence of operations exists that moves the stones from the initial state to the target state. Output a valid sequence of operations with no more than \(2n\) moves if one exists. It can be proven that if a valid sequence exists, a valid sequence with no more than \(2n\) moves exists.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 1000\)). The description of the test cases follows. The first line of each test case contains two integers \(n\) and \(m\) (\(1\leq n \leq 2000\), \(0\leq m \leq \min(\frac{n(n-1)}{2}, 10^4)\)) — the number of vertices and edges in the graph.The second line contains a binary string \(s\) consisting of '0' and '1'. The \(i\)-th bit of \(s\) indicates the number of stones on the \(i\)-th vertex in the initial state.The third line contains a binary string \(t\) consisting of '0' and '1'. The \(i\)-th bit of \(t\) indicates the number of stones on the \(i\)-th vertex in the target state.Each of the next \(m\) lines contains two integers \(u\) and \(v\) (\(1\leq u, v \leq n\)) — an undirected edge between the \(u\)-th vertex and the \(v\)-th vertex.It is guaranteed that the graph is simple. There are no self-loops and parallel edges in the graph.It is guaranteed that the numbers of '1' in \(s\) and \(t\) are the same.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2000\). It is guaranteed that the sum of \(m\) over all test cases does not exceed \(10^4\).
|
For each test case, on the first line, output ""Yes"" or ""No"" to indicate whether a valid sequence of operations exists.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.If a valid sequence of operations exists, output a single integer \(k\) (\(0 \leq k \leq 2n\)) on the second line, representing the number of operations. Suppose there are \(c\) stones in the initial state. The next \(k + 1\) lines should each contain distinct \(c\) integers, representing the positions of the stones before the operations and after each operation. These positions should satisfy the following: The positions of the stones in the first line match the initial state from the input, in any order. The positions of the stones in the last line match the target state from the input, in any order. For all \(i\) (\(1\leq i\leq k\)) and \(j\) (\(1\leq j\leq c\)), ensure that the \(j\)-th integer in the \(i\)-th line and the \(j\)-th integer in the \((i+1)\)-th line correspond to adjacent vertices in the graph. In other words, the stone is moved from its previous position to the next. If there are multiple solutions, print any of them.
|
Input: 42 110011 211 1111011001010011010111001 22 33 44 55 66 77 88 99 1010 1111 13 21101011 22 33 21111111 22 3 | Output: Yes 1 1 2 Yes 6 1 2 4 5 8 10 2 3 5 6 9 11 3 2 6 7 10 1 4 3 7 8 11 2 5 2 8 9 1 3 6 3 7 8 2 4 7 2 8 9 3 5 No Yes 0 1 2 3
|
Master
| 2 | 928 | 1,205 | 1,234 | 20 |
|
671 |
B
|
671B
|
B. Robin Hood
| 2,000 |
binary search; greedy
|
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people. After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too. Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer.
|
The first line of the input contains two integers n and k (1 ≤ n ≤ 500 000, 0 ≤ k ≤ 109) — the number of citizens in Kekoland and the number of days left till Robin Hood's retirement.The second line contains n integers, the i-th of them is ci (1 ≤ ci ≤ 109) — initial wealth of the i-th person.
|
Print a single line containing the difference between richest and poorest peoples wealth.
|
Lets look at how wealth changes through day in the first sample. [1, 1, 4, 2] [2, 1, 3, 2] or [1, 2, 3, 2] So the answer is 3 - 1 = 2In second sample wealth will remain the same for each person.
|
Input: 4 11 1 4 2 | Output: 2
|
Hard
| 2 | 1,032 | 294 | 89 | 6 |
1,715 |
A
|
1715A
|
A. Crossmarket
| 800 |
constructive algorithms; greedy; math
|
Stanley and Megan decided to shop in the ""Crossmarket"" grocery store, which can be represented as a matrix with \(n\) rows and \(m\) columns. Stanley and Megan can move to an adjacent cell using \(1\) unit of power. Two cells are considered adjacent if they share an edge. To speed up the shopping process, Megan brought her portals with her, and she leaves one in each cell she visits (if there is no portal yet). If a person (Stanley or Megan) is in a cell with a portal, that person can use \(1\) unit of power to teleport to any other cell with a portal, including Megan's starting cell.They decided to split up: Stanley will go from the upper-left cell (cell with coordinates \((1, 1)\)) to the lower-right cell (cell with coordinates \((n, m)\)), whilst Megan needs to get from the lower-left cell (cell with coordinates \((n, 1)\)) to the upper-right cell (cell with coordinates \((1, m)\)).What is the minimum total energy needed for them both to do that?Note that they can choose the time they move. Time does not affect energy.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 1000\)). Description of the test cases follows.The only line in the test case contains two integers \(n\) and \(m\) (\(1 \le n, m \le 10^5\)).
|
For each test case print a single integer on a new line – the answer.
|
In the first test case they can stick to the following plan: Megan (red circle) moves to the cell \((7, 3)\). Then she goes to the cell \((1, 3)\), and Stanley (blue circle) does the same. Stanley uses the portal in that cell (cells with portals are grey) to get to the cell \((7, 3)\). Then he moves to his destination — cell \((7, 5)\). Megan also finishes her route and goes to the cell \((1, 5)\). The total energy spent is \((2 + 6) + (2 + 1 + 2) + (2)= 15\), which is our final answer.
|
Input: 77 55 71 1100000 10000057 2281 55 1 | Output: 15 15 0 299998 340 5 5
|
Beginner
| 3 | 1,039 | 252 | 69 | 17 |
1,530 |
C
|
1530C
|
C. Pursuit
| 1,200 |
binary search; brute force; greedy; sortings
|
You and your friend Ilya are participating in an individual programming contest consisting of multiple stages. A contestant can get between \(0\) and \(100\) points, inclusive, for each stage, independently of other contestants.Points received by contestants in different stages are used for forming overall contest results. Suppose that \(k\) stages of the contest are completed. For each contestant, \(k - \lfloor \frac{k}{4} \rfloor\) stages with the highest scores are selected, and these scores are added up. This sum is the overall result of the contestant. (Here \(\lfloor t \rfloor\) denotes rounding \(t\) down.)For example, suppose \(9\) stages are completed, and your scores are \(50, 30, 50, 50, 100, 10, 30, 100, 50\). First, \(7\) stages with the highest scores are chosen — for example, all stages except for the \(2\)-nd and the \(6\)-th can be chosen. Then your overall result is equal to \(50 + 50 + 50 + 100 + 30 + 100 + 50 = 430\).As of now, \(n\) stages are completed, and you know the points you and Ilya got for these stages. However, it is unknown how many more stages will be held. You wonder what the smallest number of additional stages is, after which your result might become greater than or equal to Ilya's result, at least in theory. Find this number!
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 1000\)). Description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^5\)) — the number of completed stages.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le 100\)) — your points for the completed stages.The third line contains \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(0 \le b_i \le 100\)) — Ilya's points for the completed stages.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
|
For each test case print a single integer — the smallest number of additional stages required for your result to be able to become greater than or equal to Ilya's result.If your result is already not less than Ilya's result, print \(0\).
|
In the first test case, you have scored \(100\) points for the first stage, while Ilya has scored \(0\). Thus, your overall result (\(100\)) is already not less than Ilya's result (\(0\)).In the second test case, you have scored \(0\) points for the first stage, while Ilya has scored \(100\). A single stage with an opposite result is enough for both your and Ilya's overall scores to become equal to \(100\).In the third test case, your overall result is \(30 + 40 + 50 = 120\), while Ilya's result is \(100 + 100 + 100 = 300\). After three additional stages your result might become equal to \(420\), while Ilya's result might become equal to \(400\).In the fourth test case, your overall result after four additional stages might become equal to \(470\), while Ilya's result might become equal to \(400\). Three stages are not enough.
|
Input: 5 1 100 0 1 0 100 4 20 30 40 50 100 100 100 100 4 10 20 30 40 100 100 100 100 7 7 59 62 52 27 31 55 33 35 50 98 83 80 64 | Output: 0 1 3 4 2
|
Easy
| 4 | 1,282 | 621 | 237 | 15 |
1,827 |
D
|
1827D
|
D. Two Centroids
| 2,800 |
data structures; dfs and similar; greedy; trees
|
You are given a tree (an undirected connected acyclic graph) which initially only contains vertex \(1\). There will be several queries to the given tree. In the \(i\)-th query, vertex \(i + 1\) will appear and be connected to vertex \(p_i\) (\(1 \le p_i \le i\)). After each query, please find out the least number of operations required to make the current tree has two centroids. In one operation, you can add one vertex and one edge to the tree such that it remains a tree.A vertex is called a centroid if its removal splits the tree into subtrees with at most \(\lfloor \frac{n}{2} \rfloor\) vertices each, with \(n\) as the number of vertices of the tree. For example, the centroid of the following tree is \(3\) because the biggest subtree after removing the centroid has \(2\) vertices. In the next tree, vertex \(1\) and \(2\) are both centroids.
|
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\) (\(2 \le n \le 5 \cdot 10^{5}\)) — the number of nodes of the final tree.The second line of each test case contains \(n - 1\) integers \(p_1, p_2, \ldots, p_{n - 1}\) (\(1 \le p_i \le i\)) — the index of the vertex that is connected to vertex \(i + 1\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5 \cdot 10^{5}\).
|
For each test case, output \(n - 1\) integers. The \(i\)-th integer is the answer to the \(i\)-th query — the least number of operations required to make the current tree have two centroids.We can show that an answer always exists.
|
The illustrations below are of the fourth example test case.After the third query: The tree already has vertices \(2\) and \(3\) as centroids, so no operations are needed.After the fourth query: Adding vertex \(x\) to the tree makes vertices \(2\) and \(3\) centroids. Only one operation is needed.After the fifth query: Adding vertex \(x\) and \(y\) to the tree makes vertices \(5\) and \(2\) centroids. Two operations are needed.After the sixth query: Adding vertex \(x\), \(y\), and \(z\) to the tree makes vertices \(5\) and \(2\) centroids. Three operations are needed.
|
Input: 52131 141 2 371 2 3 2 5 2101 2 2 4 5 5 7 8 9 | Output: 0 0 1 0 1 0 0 1 0 1 2 3 0 1 2 1 0 1 0 1 2
|
Master
| 4 | 854 | 573 | 231 | 18 |
626 |
A
|
626A
|
A. Robot Sequence
| 1,000 |
brute force; implementation
|
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.
|
The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands.The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.
|
Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.
|
In the first case, the entire source code works, as well as the ""RL"" substring in the second and third characters.Note that, in the third case, the substring ""LR"" appears three times, and is therefore counted three times to the total result.
|
Input: 6URLLDR | Output: 2
|
Beginner
| 2 | 433 | 199 | 119 | 6 |
103 |
B
|
103B
|
B. Cthulhu
| 1,500 |
dfs and similar; dsu; graphs
|
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.It is guaranteed that the graph contains no multiple edges and self-loops.
|
The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ ).Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
|
Print ""NO"", if the graph is not Cthulhu and ""FHTAGN!"" if it is.
|
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).A rooted tree is a tree where one vertex is selected to be the root.
|
Input: 6 66 36 45 12 51 45 4 | Output: FHTAGN!
|
Medium
| 3 | 1,019 | 379 | 67 | 1 |
1,168 |
D
|
1168D
|
D. Anagram Paths
| 3,000 |
dp; implementation; trees
|
Toad Ilya has a rooted binary tree with vertex \(1\) being the root. A tree is a connected graph without cycles. A tree is rooted if one vertex is selected and called the root. A vertex \(u\) is a child of a vertex \(v\) if \(u\) and \(v\) are connected by an edge and \(v\) is closer to the root than \(u\). A leaf is a non-root vertex that has no children.In the tree Ilya has each vertex has at most two children, and each edge has some character written on it. The character can be a lowercase English letter or the question mark '?'.Ilya will \(q\) times update the tree a bit. Each update will replace exactly one character on some edge. After each update Ilya needs to find if the tree is anagrammable and if yes, find its anagramnity for each letter. Well, that's difficult to explain, but we'll try.To start with, a string \(a\) is an anagram of a string \(b\) if it is possible to rearrange letters in \(a\) (without changing the letters itself) so that it becomes \(b\). For example, the string ""fortyfive"" is an anagram of the string ""overfifty"", but the string ""aabb"" is not an anagram of the string ""bbba"".Consider a path from the root of the tree to a leaf. The characters on the edges on this path form a string, we say that this string is associated with this leaf. The tree is anagrammable if and only if it is possible to replace each question mark with a lowercase English letter so that for all pair of leaves the associated strings for these leaves are anagrams of each other.If the tree is anagrammable, then its anagramnity for the letter \(c\) is the maximum possible number of letters \(c\) in a string associated with some leaf in a valid replacement of all question marks.Please after each update find if the tree is anagrammable and if yes, find the \(\sum{f(c) \cdot ind(c)}\) for all letters \(c\), where \(f(c)\) is the anagramnity for the letter \(c\), and \(ind(x)\) is the index of this letter in the alphabet (\(ind(\)""a""\() = 1\), \(ind(\)""b""\() = 2\), ..., \(ind(\)""z""\() = 26\)).
|
The first line of input contains two integers \(n\) and \(q\) (\(2 \leq n \leq 150\,000\), \(1 \leq q \leq 150\,000\)) — the number of vertices in the tree and the number of queries.The next \(n-1\) lines describe the initial tree. The \(i\)-th of them contains an integer \(p_i\) and a character \(c_i\) (\(1 \leq p_i \leq i\), \(c_i\) is a lowercase English letter or the question mark '?') describing an edge between vertices \(p_i\) and \(i+1\) with character \(c_i\) written on it.The root of this tree is the vertex \(1\), and each vertex has at most two children.The next \(q\) lines describe the queries. The \(i\)-th of them contains two integers \(v\) and \(c\) (\(2 \leq v \leq n\), \(c\) is a lowercase English letter or the question mark '?'), meaning that updated character on the edge between \(p_{v-1}\) to \(v\) is \(c\). The updated character can be the same as was written before.
|
Output \(q\) lines. In the \(i\)-th of them print ""Fou"" if the tree is not anagrammable after the first \(i\) updates.Otherwise output ""Shi"" and the \(\sum{f(c) \cdot ind(c)}\) for all letters \(c\).
|
In the first example after the first query, for each character, you can set all edges equal to that character, and you will get \(1\) such character on each path, so the answer is \(1 \cdot (1+2+\ldots+26) = 351\).In the first example after the second query, you know that all paths should be an anagram of ""a"", so all paths should be ""a"", so the answer is \(1 \cdot 1 = 1\).In the first example after the third query, you have two paths with strings ""a"" and ""b"", but these strings are not anagrams, so the answer is ""Fou"".In the first example after the fourth query, you know that all paths should be ""b"", so the answer is \(1 \cdot 2 = 2\).In the second example after the first query, you know that \(f(\)'a'\() = 2\) and \(f(c) = 1\) for all other characters, so the answer is \(1 \cdot (2 + 3 + \ldots + 26) + 2 = 352\).In the second example after the second query, you know that each path should contain one 'a' and one 'b', so the answer is \(1 \cdot 1 + 1 \cdot 2 = 3\).
|
Input: 3 4 1 ? 1 ? 2 ? 2 a 3 b 2 b | Output: Shi 351 Shi 1 Fou Shi 2
|
Master
| 3 | 2,032 | 899 | 203 | 11 |
526 |
G
|
526G
|
G. Spiders Evil Plan
| 3,300 |
greedy; trees
|
Spiders are Om Nom's old enemies. They love eating candies as much as he does and that's why they keep trying to keep the monster away from his favorite candies. They came up with an evil plan to trap Om Nom. Let's consider a rope structure consisting of n nodes and n - 1 ropes connecting the nodes. The structure is connected, thus, the ropes and the nodes form a tree. Each rope of the formed structure is associated with its length. A candy is tied to node x of the structure. Om Nom really wants to eat this candy.The y spiders are trying to stop him from doing it. They decided to entangle the candy and some part of the structure into a web, thus attaching the candy to as large as possible part of the rope structure. Each spider can use his web to cover all ropes on the path between two arbitrary nodes a and b. Thus, y spiders can cover the set of ropes which is a union of y paths in the given tree. These y paths can arbitrarily intersect each other. The spiders want the following conditions to be hold: the node containing the candy is adjacent to at least one rope covered with a web the ropes covered with the web form a connected structure (what's the idea of covering with a web the ropes that are not connected with the candy?) the total length of the ropes covered with web is as large as possible The spiders haven't yet decided to what node of the structure they will tie the candy and how many spiders will cover the structure with web, so they asked you to help them. Help them calculate the optimal plan for multiple values of x and y.
|
The first line contains numbers n and q (1 ≤ n, q ≤ 105) — the number of nodes in the structure and the number of questions that the spiders want to ask you.The next n - 1 lines determine the rope structure. The i-th line contains three integers ui, vi, li (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ li ≤ 1000), showing that there is a rope of length li between nodes ui and vi.Next q lines describe the spiders' questions. As they want you to answer their question online, they encoded their messages in a special manner.Each of the next q lines contains two numbers xi, yi. In the first question of the spiders x = x1, y = y1.To calculate values x and y in the spiders' i-th (2 ≤ i ≤ q) question, you need to use the following formulas:where Ansi - 1 is the total length of the ropes covered by a web in the answer for the (i - 1)-th question.The following inequality holds: 1 ≤ xi, yi ≤ n.
|
For each question of the spiders print on a separate line a single integer Ansi — the total length of the ropes covered with web in the optimal plan.
|
Input: 6 31 2 22 3 23 4 24 6 13 5 103 12 51 1 | Output: 141317
|
Master
| 2 | 1,561 | 879 | 149 | 5 |
|
1,183 |
D
|
1183D
|
D. Candy Box (easy version)
| 1,400 |
greedy; sortings
|
This problem is actually a subproblem of problem G from the same contest.There are \(n\) candies in a candy box. The type of the \(i\)-th candy is \(a_i\) (\(1 \le a_i \le n\)).You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type \(1\) and two candies of type \(2\) is bad). It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.Your task is to find out the maximum possible size of the single gift you can prepare using the candies you have.You have to answer \(q\) independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
|
The first line of the input contains one integer \(q\) (\(1 \le q \le 2 \cdot 10^5\)) — the number of queries. Each query is represented by two lines.The first line of each query contains one integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) — the number of candies.The second line of each query contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le n\)), where \(a_i\) is the type of the \(i\)-th candy in the box.It is guaranteed that the sum of \(n\) over all queries does not exceed \(2 \cdot 10^5\).
|
For each query print one integer — the maximum possible size of the single gift you can compose using candies you got in this query with the restriction described in the problem statement.
|
In the first query, you can prepare a gift with two candies of type \(8\) and one candy of type \(5\), totalling to \(3\) candies.Note that this is not the only possible solution — taking two candies of type \(4\) and one candy of type \(6\) is also valid.
|
Input: 3 8 1 4 8 4 5 6 3 8 16 2 1 3 3 4 3 4 4 1 3 2 2 2 4 1 1 9 2 2 4 4 4 7 7 7 7 | Output: 3 10 9
|
Easy
| 2 | 856 | 511 | 188 | 11 |
575 |
E
|
575E
|
E. Spectator Riots
| 2,800 |
geometry
|
It’s riot time on football stadium Ramacana! Raging fans have entered the field and the police find themselves in a difficult situation. The field can be represented as a square in the coordinate system defined by two diagonal vertices in (0,0) and (105, 105). The sides of that square are also considered to be inside the field, everything else is outside.In the beginning, there are N fans on the field. For each fan we are given his speed, an integer vi as well as his integer coordinates (xi, yi). A fan with those coordinates might move and after one second he might be at any point (xi + p, yi + q) where 0 ≤ |p| + |q| ≤ vi. p, q are both integers.Points that go outside of the square that represents the field are excluded and all others have equal probability of being the location of that specific fan after one second.Andrej, a young and promising police officer, has sent a flying drone to take a photo of the riot from above. The drone’s camera works like this: It selects three points with integer coordinates such that there is a chance of a fan appearing there after one second. They must not be collinear or the camera won’t work. It is guaranteed that not all of the initial positions of fans will be on the same line. Camera focuses those points and creates a circle that passes through those three points. A photo is taken after one second (one second after the initial state). Everything that is on the circle or inside it at the moment of taking the photo (one second after focusing the points) will be on the photo. Your goal is to select those three points so that the expected number of fans seen on the photo is maximized. If there are more such selections, select those three points that give the circle with largest radius among them. If there are still more suitable selections, any one of them will be accepted. If your answer follows conditions above and radius of circle you return is smaller then the optimal one by 0.01, your output will be considered as correct.No test will have optimal radius bigger than 1010.
|
The first line contains the number of fans on the field, N. The next N lines contain three integers: xi ,yi, vi. They are the x-coordinate, y-coordinate and speed of fan i at the beginning of the one second interval considered in the task. 3 ≤ N ≤ 105 0 ≤ xi, yi ≤ 105 0 ≤ vi ≤ 1000 All numbers are integers
|
You need to output the three points that camera needs to select. Print them in three lines, with every line containing the x-coordinate, then y-coordinate, separated by a single space. The order of points does not matter.
|
Input: 31 1 11 1 11 2 1 | Output: 2 22 11 0
|
Master
| 1 | 2,046 | 307 | 221 | 5 |
|
884 |
F
|
884F
|
F. Anti-Palindromize
| 2,500 |
flows; graphs; greedy
|
A string a of length m is called antipalindromic iff m is even, and for each i (1 ≤ i ≤ m) ai ≠ am - i + 1.Ivan has a string s consisting of n lowercase Latin letters; n is even. He wants to form some string t that will be an antipalindromic permutation of s. Also Ivan has denoted the beauty of index i as bi, and the beauty of t as the sum of bi among all indices i such that si = ti.Help Ivan to determine maximum possible beauty of t he can get.
|
The first line contains one integer n (2 ≤ n ≤ 100, n is even) — the number of characters in s.The second line contains the string s itself. It consists of only lowercase Latin letters, and it is guaranteed that its letters can be reordered to form an antipalindromic string.The third line contains n integer numbers b1, b2, ..., bn (1 ≤ bi ≤ 100), where bi is the beauty of index i.
|
Print one number — the maximum possible beauty of t.
|
Input: 8abacabac1 1 1 1 1 1 1 1 | Output: 8
|
Expert
| 3 | 449 | 383 | 52 | 8 |
|
246 |
A
|
246A
|
A. Buggy Sorting
| 900 |
constructive algorithms; greedy; sortings
|
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of n integers a1, a2, ..., an in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of the program gets number n and array a.loop integer variable i from 1 to n - 1 loop integer variable j from i to n - 1 if (aj > aj + 1), then swap the values of elements aj and aj + 1But Valera could have made a mistake, because he hasn't yet fully learned the sorting algorithm. If Valera made a mistake in his program, you need to give a counter-example that makes his program work improperly (that is, the example that makes the program sort the array not in the non-decreasing order). If such example for the given value of n doesn't exist, print -1.
|
You've got a single integer n (1 ≤ n ≤ 50) — the size of the sorted array.
|
Print n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the counter-example, for which Valera's algorithm won't work correctly. If the counter-example that meets the described conditions is impossible to give, print -1.If there are several counter-examples, consisting of n numbers, you are allowed to print any of them.
|
Input: 1 | Output: -1
|
Beginner
| 3 | 873 | 74 | 330 | 2 |
|
1,425 |
E
|
1425E
|
E. Excitation of Atoms
| 2,200 |
greedy; implementation
|
Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it.There are \(N\) atoms numbered from \(1\) to \(N\). These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom \(i\) requires \(D_i\) energy. When atom \(i\) is excited, it will give \(A_i\) energy. You can excite any number of atoms (including zero).These atoms also form a peculiar one-way bond. For each \(i\), \((1 \le i < N)\), if atom \(i\) is excited, atom \(E_i\) will also be excited at no cost. Initially, \(E_i\) = \(i+1\). Note that atom \(N\) cannot form a bond to any atom.Mr. Chanek must change exactly \(K\) bonds. Exactly \(K\) times, Mr. Chanek chooses an atom \(i\), \((1 \le i < N)\) and changes \(E_i\) to a different value other than \(i\) and the current \(E_i\). Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve!note: You must first change exactly \(K\) bonds before you can start exciting atoms.
|
The first line contains two integers \(N\) \(K\) \((4 \le N \le 10^5, 0 \le K < N)\), the number of atoms, and the number of bonds that must be changed.The second line contains \(N\) integers \(A_i\) \((1 \le A_i \le 10^6)\), which denotes the energy given by atom \(i\) when on excited state.The third line contains \(N\) integers \(D_i\) \((1 \le D_i \le 10^6)\), which denotes the energy needed to excite atom \(i\).
|
A line with an integer that denotes the maximum number of energy that Mr. Chanek can get.
|
An optimal solution to change \(E_5\) to 1 and then excite atom 5 with energy 1. It will cause atoms 1, 2, 3, 4, 5 be excited. The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10) - 1 = 35.Another possible way is to change \(E_3\) to 1 and then exciting atom 3 (which will excite atom 1, 2, 3) and exciting atom 4 (which will excite atom 4, 5, 6). The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10 + 2) - (6 + 7) = 25 which is not optimal.
|
Input: 6 1 5 6 7 8 10 2 3 5 6 7 1 10 | Output: 35
|
Hard
| 2 | 1,115 | 419 | 89 | 14 |
2,010 |
C2
|
2010C2
|
C2. Message Transmission Error (hard version)
| 1,700 |
hashing; string suffix structures; strings; two pointers
|
This is a more difficult version of the problem. It differs from the easy one only by the constraints.At the Berland State University, the local network between servers does not always operate without errors. When transmitting two identical messages consecutively, an error may occur, resulting in the two messages merging into one. In this merging, the end of the first message coincides with the beginning of the second. Of course, the merging can only occur at identical characters. The length of the merging must be a positive number less than the length of the message text.For example, when transmitting two messages ""abrakadabra"" consecutively, it is possible that it will be transmitted with the described type of error, resulting in a message like ""abrakadabrabrakadabra"" or ""abrakadabrakadabra' (in the first case, the merging occurred at one character, and in the second case, at four).Given the received message t, determine if it is possible that this is the result of an error of the described type in the operation of the local network, and if so, determine a possible value of s.A situation where two messages completely overlap each other should not be considered an error. For example, if the received message is ""abcd"", it should be considered that there is no error in it. Similarly, simply appending one message after another is not a sign of an error. For instance, if the received message is ""abcabc"", it should also be considered that there is no error in it.
|
The input consists of a single non-empty string t, consisting of lowercase letters of the Latin alphabet. The length of the string t does not exceed 4·105 characters.
|
If the message t cannot contain an error, output ""NO"" (without quotes) in a single line of output.Otherwise, in the first line, output ""YES"" (without quotes), and in the next line, output the string s — a possible message that could have led to the error. If there are multiple possible answers, any of them is acceptable.
|
In the second example, a suitable answer could also be the string ""acacaca"".
|
Input: abrakadabrabrakadabra | Output: YESabrakadabra
|
Medium
| 4 | 1,492 | 166 | 326 | 20 |
979 |
B
|
979B
|
B. Treasure Hunt
| 1,800 |
greedy
|
After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of \(7\) because its subribbon a appears \(7\) times, and the ribbon abcdabc has the beauty of \(2\) because its subribbon abc appears twice.The rules are simple. The game will have \(n\) turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after \(n\) turns wins the treasure.Could you find out who is going to be the winner if they all play optimally?
|
The first line contains an integer \(n\) (\(0 \leq n \leq 10^{9}\)) — the number of turns.Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than \(10^{5}\) uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors.
|
Print the name of the winner (""Kuro"", ""Shiro"" or ""Katie""). If there are at least two cats that share the maximum beauty, print ""Draw"".
|
In the first example, after \(3\) turns, Kuro can change his ribbon into ooooo, which has the beauty of \(5\), while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most \(4\), for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is \(9\) and the number of turn is \(15\), everyone can change their ribbons in some way to reach the maximal beauty of \(9\) by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw.
|
Input: 3KurooShiroKatie | Output: Kuro
|
Medium
| 1 | 1,520 | 454 | 142 | 9 |
982 |
A
|
982A
|
A. Row
| 1,200 |
brute force; constructive algorithms
|
You're given a row with \(n\) chairs. We call a seating of people ""maximal"" if the two following conditions hold: There are no neighbors adjacent to anyone seated. It's impossible to seat one more person without violating the first rule. The seating is given as a string consisting of zeros and ones (\(0\) means that the corresponding seat is empty, \(1\) — occupied). The goal is to determine whether this seating is ""maximal"".Note that the first and last seats are not adjacent (if \(n \ne 2\)).
|
The first line contains a single integer \(n\) (\(1 \leq n \leq 1000\)) — the number of chairs.The next line contains a string of \(n\) characters, each of them is either zero or one, describing the seating.
|
Output ""Yes"" (without quotation marks) if the seating is ""maximal"". Otherwise print ""No"".You are allowed to print letters in whatever case you'd like (uppercase or lowercase).
|
In sample case one the given seating is maximal.In sample case two the person at chair three has a neighbour to the right.In sample case three it is possible to seat yet another person into chair three.
|
Input: 3101 | Output: Yes
|
Easy
| 2 | 502 | 207 | 181 | 9 |
1,619 |
C
|
1619C
|
C. Wrong Addition
| 1,200 |
implementation
|
Tanya is learning how to add numbers, but so far she is not doing it correctly. She is adding two numbers \(a\) and \(b\) using the following algorithm: If one of the numbers is shorter than the other, Tanya adds leading zeros so that the numbers are the same length. The numbers are processed from right to left (that is, from the least significant digits to the most significant). In the first step, she adds the last digit of \(a\) to the last digit of \(b\) and writes their sum in the answer. At each next step, she performs the same operation on each pair of digits in the same place and writes the result to the left side of the answer. For example, the numbers \(a = 17236\) and \(b = 3465\) Tanya adds up as follows:$$$\( \large{ \begin{array}{r} + \begin{array}{r} 17236\\ 03465\\ \end{array} \\ \hline \begin{array}{r} 1106911 \end{array} \end{array}} \)\( calculates the sum of \)6 + 5 = 11\( and writes \)11\( in the answer. calculates the sum of \)3 + 6 = 9\( and writes the result to the left side of the answer to get \)911\(. calculates the sum of \)2 + 4 = 6\( and writes the result to the left side of the answer to get \)6911\(. calculates the sum of \)7 + 3 = 10\(, and writes the result to the left side of the answer to get \)106911\(. calculates the sum of \)1 + 0 = 1\( and writes the result to the left side of the answer and get \)1106911\(. As a result, she gets \)1106911\(.You are given two positive integers \)a\( and \)s\(. Find the number \)b\( such that by adding \)a\( and \)b\( as described above, Tanya will get \)s\(. Or determine that no suitable \)b$$$ exists.
|
The first line of input data contains an integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.Each test case consists of a single line containing two positive integers \(a\) and \(s\) (\(1 \le a \lt s \le 10^{18}\)) separated by a space.
|
For each test case print the answer on a separate line.If the solution exists, print a single positive integer \(b\). The answer must be written without leading zeros. If multiple answers exist, print any of them.If no suitable number \(b\) exists, output -1.
|
The first test case is explained in the main part of the statement.In the third test case, we cannot choose \(b\) that satisfies the problem statement.
|
Input: 6 17236 1106911 1 5 108 112 12345 1023412 1 11 1 20 | Output: 3465 4 -1 90007 10 -1
|
Easy
| 1 | 1,600 | 248 | 259 | 16 |
1,029 |
F
|
1029F
|
F. Multicolored Markers
| 2,000 |
binary search; brute force; math; number theory
|
There is an infinite board of square tiles. Initially all tiles are white.Vova has a red marker and a blue marker. Red marker can color \(a\) tiles. Blue marker can color \(b\) tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be exactly \(a\) red tiles and exactly \(b\) blue tiles across the board.Vova wants to color such a set of tiles that: they would form a rectangle, consisting of exactly \(a+b\) colored tiles; all tiles of at least one color would also form a rectangle. Here are some examples of correct colorings: Here are some examples of incorrect colorings: Among all correct colorings Vova wants to choose the one with the minimal perimeter. What is the minimal perimeter Vova can obtain?It is guaranteed that there exists at least one correct coloring.
|
A single line contains two integers \(a\) and \(b\) (\(1 \le a, b \le 10^{14}\)) — the number of tiles red marker should color and the number of tiles blue marker should color, respectively.
|
Print a single integer — the minimal perimeter of a colored rectangle Vova can obtain by coloring exactly \(a\) tiles red and exactly \(b\) tiles blue.It is guaranteed that there exists at least one correct coloring.
|
The first four examples correspond to the first picture of the statement.Note that for there exist multiple correct colorings for all of the examples.In the first example you can also make a rectangle with sides \(1\) and \(8\), though its perimeter will be \(18\) which is greater than \(8\).In the second example you can make the same resulting rectangle with sides \(3\) and \(4\), but red tiles will form the rectangle with sides \(1\) and \(3\) and blue tiles will form the rectangle with sides \(3\) and \(3\).
|
Input: 4 4 | Output: 12
|
Hard
| 4 | 864 | 190 | 216 | 10 |
607 |
B
|
607B
|
B. Zuma
| 1,900 |
dp
|
Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.
|
The first line of input contains a single integer n (1 ≤ n ≤ 500) — the number of gemstones.The second line contains n space-separated integers, the i-th of which is ci (1 ≤ ci ≤ n) — the color of the i-th gemstone in a line.
|
Print a single integer — the minimum number of seconds needed to destroy the entire line.
|
In the first sample, Genos can destroy the entire line in one second.In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.
|
Input: 31 2 1 | Output: 1
|
Hard
| 1 | 808 | 225 | 89 | 6 |
1,906 |
I
|
1906I
|
I. Contingency Plan 2
| 2,900 |
graph matchings
|
You are working as a manager in The ICPC Company. In the company building, there are \(N\) computers (numbered from \(1\) to \(N\)). There are \(N - 1\) cables, numbered from \(1\) to \(N - 1\), that connect all the computers into a single network. Cable \(i\) connects computer \(U_i\) and \(V_i\). Each cable can be set into emergency mode, where cable \(i\) only transfers data from computer \(U_i\) to computer \(V_i\), but not the other way around. During a disaster, it is mandatory for all cables to be in emergency mode.Through your research, you discover a new way to determine the vulnerability of a network. You want to add zero or more new cables to the current network such that it is not vulnerable during a disaster. Your network is not vulnerable if and only if there is exactly one permutation of \(1\) to \(N\) such that \(u\) appears before \(v\) in the permutation for all cables that connect computer \(u\) and \(v\). In other words, it should have exactly one topological order.The following illustration shows examples of not vulnerable networks and vulnerable networks. For the not vulnerable networks, the only permutation that satisfies the requirement for the networks on the left and on the right are \([1, 2, 3]\) and \([3, 1, 2]\), respectively. Meanwhile, for the vulnerable networks, there are \(2\) permutations that satisfy the requirement for the network on the left: \([1, 2, 3]\) and \([3, 1, 2]\); while there is no permutation that satisfies the requirement for the network on the right.You are interested in the minimum number of new cables that should be added to the current network such that it is not vulnerable during a disaster. Furthermore, you want to know, which pairs of computers should be connected by using the minimum number of cables. If there are several ways to connect, you can connect in any way of your choice. Under the given constraints, it can be proven that there exists a way to make the network not vulnerable.
|
The first line consists of an integer \(N\) (\(2 \leq N \leq 100\,000\)).Each of the next \(N - 1\) lines consists of two integers \(U_i\) \(V_i\) (\(1 \leq U_i, V_i \leq N\)). The input edges form a tree.
|
The first line consists of an integer, representing the minimum number of new cables that should be added to the current network such that it is no longer vulnerable during a disaster. Denote this number as \(K\) and the new cables are numbered from \(1\) to \(K\).If \(K\) is not \(0\), then output \(K\) lines. Each of the next \(K\) lines consists of two integers \(A_i\) \(B_i\), representing the computers that are connected by the new cable \(i\). During a disaster, new cable \(i\) only transfers data from computer \(A_i\) to computer \(B_i\), but not the other way around. If there exist several solutions, you can output any of them.
|
Explanation for the sample input/output #3The following illustration shows the original network and the new network with the added cables during a disaster. The only permutation that satisfies the requirement is \([1, 2, 3, 4, 5]\).
|
Input: 3 1 2 3 2 | Output: 1 3 1
|
Master
| 1 | 1,976 | 205 | 643 | 19 |
542 |
A
|
542A
|
A. Place Your Ad Here
| 2,400 |
data structures; sortings
|
Ivan Anatolyevich's agency is starting to become famous in the town. They have already ordered and made n TV commercial videos. Each video is made in a special way: the colors and the soundtrack are adjusted to the time of the day and the viewers' mood. That's why the i-th video can only be shown within the time range of [li, ri] (it is not necessary to use the whole segment but the broadcast time should be within this segment).Now it's time to choose a TV channel to broadcast the commercial. Overall, there are m TV channels broadcasting in the city, the j-th one has cj viewers, and is ready to sell time [aj, bj] to broadcast the commercial.Ivan Anatolyevich is facing a hard choice: he has to choose exactly one video i and exactly one TV channel j to broadcast this video and also a time range to broadcast [x, y]. At that the time range should be chosen so that it is both within range [li, ri] and within range [aj, bj].Let's define the efficiency of the broadcast as value (y - x)·cj — the total sum of time that all the viewers of the TV channel are going to spend watching the commercial. Help Ivan Anatolyevich choose the broadcast with the maximum efficiency!
|
The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of commercial videos and channels, respectively.Each of the following n lines contains two integers li, ri (0 ≤ li ≤ ri ≤ 109) — the segment of time when it is possible to show the corresponding video.Each of the following m lines contains three integers aj, bj, cj (0 ≤ aj ≤ bj ≤ 109, 1 ≤ cj ≤ 109), characterizing the TV channel.
|
In the first line print an integer — the maximum possible efficiency of the broadcast. If there is no correct way to get a strictly positive efficiency, print a zero.If the maximum efficiency is strictly positive, in the second line also print the number of the video i (1 ≤ i ≤ n) and the number of the TV channel j (1 ≤ j ≤ m) in the most effective broadcast.If there are multiple optimal answers, you can print any of them.
|
In the first sample test the most optimal solution is to show the second commercial using the first TV channel at time [2, 4]. The efficiency of such solution is equal to (4 - 2)·2 = 4.In the second sample test Ivan Anatolievich's wish does not meet the options of the TV channel, the segments do not intersect, so the answer is zero.
|
Input: 2 37 91 42 8 20 4 18 9 3 | Output: 42 1
|
Expert
| 2 | 1,176 | 408 | 426 | 5 |
457 |
F
|
457F
|
F. An easy problem about trees
| 3,200 |
dp; games; greedy; trees
|
Pieguy and Piegirl are playing a game. They have a rooted binary tree, that has a property that each node is either a leaf or has exactly two children. Each leaf has a number associated with it.On his/her turn a player can choose any two leafs that share their immediate parent, remove them, and associate either of their values with their parent, that now became a leaf (the player decides which of the two values to associate). The game ends when only one node (the one that was the root of the tree) is left.Pieguy goes first, and his goal is to maximize the value that will be associated with the root when the game ends. Piegirl wants to minimize that value. Assuming that both players are playing optimally, what number will be associated with the root when the game ends?
|
First line contains a single integer t (1 ≤ t ≤ 100) — number of test cases. Then t test cases follow. Each test case begins with an empty line, followed by a line with a single integer n (1 ≤ n ≤ 250), followed by n lines describing n nodes of the tree. Each of those n lines either contains a non-negative number ai, indicating a leaf node with value ai (0 ≤ ai ≤ 1000) associated with it, or - 1 followed by integers l and r, indicating a non-leaf node with children l and r (0 ≤ l, r ≤ n - 1). Nodes are numbered from 0 to n - 1. The root is always node 0.
|
For each test case print one line with one integer on it — the number that will be associated with the root when the game ends.
|
Input: 43-1 1 21055-1 1 2-1 3 4105207-1 1 2-1 3 4-1 5 6123411-1 1 2-1 3 4-1 5 6-1 7 8157-1 9 1078911 | Output: 101048
|
Master
| 4 | 778 | 560 | 127 | 4 |
|
1,139 |
E
|
1139E
|
E. Maximize Mex
| 2,400 |
flows; graph matchings; graphs
|
There are \(n\) students and \(m\) clubs in a college. The clubs are numbered from \(1\) to \(m\). Each student has a potential \(p_i\) and is a member of the club with index \(c_i\). Initially, each student is a member of exactly one club. A technical fest starts in the college, and it will run for the next \(d\) days. There is a coding competition every day in the technical fest. Every day, in the morning, exactly one student of the college leaves their club. Once a student leaves their club, they will never join any club again. Every day, in the afternoon, the director of the college will select one student from each club (in case some club has no members, nobody is selected from that club) to form a team for this day's coding competition. The strength of a team is the mex of potentials of the students in the team. The director wants to know the maximum possible strength of the team for each of the coming \(d\) days. Thus, every day the director chooses such team, that the team strength is maximized.The mex of the multiset \(S\) is the smallest non-negative integer that is not present in \(S\). For example, the mex of the \(\{0, 1, 1, 2, 4, 5, 9\}\) is \(3\), the mex of \(\{1, 2, 3\}\) is \(0\) and the mex of \(\varnothing\) (empty set) is \(0\).
|
The first line contains two integers \(n\) and \(m\) (\(1 \leq m \leq n \leq 5000\)), the number of students and the number of clubs in college.The second line contains \(n\) integers \(p_1, p_2, \ldots, p_n\) (\(0 \leq p_i < 5000\)), where \(p_i\) is the potential of the \(i\)-th student.The third line contains \(n\) integers \(c_1, c_2, \ldots, c_n\) (\(1 \leq c_i \leq m\)), which means that \(i\)-th student is initially a member of the club with index \(c_i\).The fourth line contains an integer \(d\) (\(1 \leq d \leq n\)), number of days for which the director wants to know the maximum possible strength of the team. Each of the next \(d\) lines contains an integer \(k_i\) (\(1 \leq k_i \leq n\)), which means that \(k_i\)-th student lefts their club on the \(i\)-th day. It is guaranteed, that the \(k_i\)-th student has not left their club earlier.
|
For each of the \(d\) days, print the maximum possible strength of the team on that day.
|
Consider the first example:On the first day, student \(3\) leaves their club. Now, the remaining students are \(1\), \(2\), \(4\) and \(5\). We can select students \(1\), \(2\) and \(4\) to get maximum possible strength, which is \(3\). Note, that we can't select students \(1\), \(2\) and \(5\), as students \(2\) and \(5\) belong to the same club. Also, we can't select students \(1\), \(3\) and \(4\), since student \(3\) has left their club.On the second day, student \(2\) leaves their club. Now, the remaining students are \(1\), \(4\) and \(5\). We can select students \(1\), \(4\) and \(5\) to get maximum possible strength, which is \(1\).On the third day, the remaining students are \(1\) and \(5\). We can select students \(1\) and \(5\) to get maximum possible strength, which is \(1\).On the fourth day, the remaining student is \(1\). We can select student \(1\) to get maximum possible strength, which is \(1\). On the fifth day, no club has students and so the maximum possible strength is \(0\).
|
Input: 5 3 0 1 2 2 0 1 2 2 3 2 5 3 2 4 5 1 | Output: 3 1 1 1 0
|
Expert
| 3 | 1,269 | 861 | 88 | 11 |
2,011 |
B
|
2011B
|
B. Shuffle
| 0 |
*special
|
Yes, this is another one of those constructive permutation problems.You are given an integer \(n\). You have to construct a permutation \(p\) of size \(n\), i. e. an array of \(n\) integers, where every integer from \(1\) to \(n\) appears exactly once.Every pair of adjacent elements in the permutation (\(p_i\) and \(p_{i+1}\)) must meet the following condition: if one of them is divisible by the other, the condition \(p_i < p_{i+1}\) must hold; otherwise, the condition \(p_i > p_{i+1}\) must hold.
|
The first line contains one integer \(t\) (\(1 \le t \le 99\)) — the number of test cases.Each test case consists of one line, containing one integer \(n\) (\(2 \le n \le 100\)).
|
For each test case, print the answer as follows: if no permutation of size \(n\) meeting the conditions from the statement exists, print \(-1\); otherwise, print \(n\) distinct integers from \(1\) to \(n\) — the required permutation. If there are mutliple answers, print any of them.
|
Input: 2510 | Output: 1 5 2 4 3 1 2 10 9 7 4 8 3 6 5
|
Beginner
| 1 | 502 | 178 | 283 | 20 |
|
2,022 |
D1
|
2022D1
|
D1. Asesino (Easy Version)
| 1,900 |
binary search; brute force; constructive algorithms; implementation; interactive
|
This is the easy version of the problem. In this version, you can ask at most \(n+69\) questions. You can make hacks only if both versions of the problem are solved.This is an interactive problem.It is a tradition in Mexico's national IOI trainings to play the game ""Asesino"", which is similar to ""Among Us"" or ""Mafia"".Today, \(n\) players, numbered from \(1\) to \(n\), will play ""Asesino"" with the following three roles: Knight: a Knight is someone who always tells the truth. Knave: a Knave is someone who always lies. Impostor: an Impostor is someone everybody thinks is a Knight, but is secretly a Knave. Each player will be assigned a role in the game. There will be exactly one Impostor but there can be any (possible zero) number of Knights and Knaves.As the game moderator, you have accidentally forgotten the roles of everyone, but you need to determine the player who is the Impostor.To determine the Impostor, you will ask some questions. In each question, you will pick two players \(i\) and \(j\) (\(1 \leq i, j \leq n\); \(i \neq j\)) and ask if player \(i\) thinks that player \(j\) is a Knight. The results of the question is shown in the table below. KnightKnaveImpostorKnightYesNoYesKnaveNoYesNoImpostorNoYes— The response of the cell in row \(a\) and column \(b\) is the result of asking a question when \(i\) has role \(a\) and \(j\) has row \(b\). For example, the ""Yes"" in the top right cell belongs to row ""Knight"" and column ""Impostor"", so it is the response when \(i\) is a Knight and \(j\) is an Impostor. Find the Impostor in at most \(n + 69\) questions.Note: the grader is adaptive: the roles of the players are not fixed in the beginning and may change depending on your questions. However, it is guaranteed that there exists an assignment of roles that is consistent with all previously asked questions under the constraints of this problem.
|
The first line of input contains a single integer \(t\) (\(1 \leq t \leq 10^3\)) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(3 \le n \le 10^5\)) — the number of people playing the game.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
|
Note that the example test cases do not represent an optimal strategy for asking questions and are only shown for the sake of demonstrating the interaction format. Specifically, we cannot determine which player is the Impostor from the questions asked in the examples.In the first test case of the example, players at indices \(2\) and \(6\) are Knights, players at indices \(1\), \(3\), \(5\), and \(7\) are Knaves, and the Impostor is at index \(4\). The following is an explanation of the questions asked: In the first query, player \(i\) is a Knave and player \(j\) is a Knave. The answer is ""yes"" since Knaves always lie. In the second query, player \(i\) is a Knave and player \(j\) is a Knight. The answer is ""no"" since Knaves always lie. In the third query, player \(i\) is a Knight and player \(j\) is a Knave. The answer is ""no"" since Knights always tell the truth. In the fourth query, player \(i\) is a Knight and player \(j\) is a Knight. The answer is ""yes"" since Knights always tell the truth. In the fifth query, player \(i\) is a Impostor and player \(j\) is a Knave. The answer is ""yes"" since the Impostor always lies. In the sixth query, player \(i\) is a Impostor and player \(j\) is a Knight. The answer is ""no"" since the Impostor always lies. In the seventh query, player \(i\) is a Knave and player \(j\) is a Impostor. The answer is ""no"" since Knaves always lie and Knaves thinks that the Impostor is a Knight. In the eighth query, player \(i\) is a Knight and player \(j\) is a Impostor. The answer is ""yes"" since Knights always tell the truth and Knights think that the Impostor is a Knight.
|
Input: 2 7 1 0 0 1 1 0 0 1 4 0 1 1 1 | Output: ? 1 3 ? 7 6 ? 2 5 ? 6 2 ? 4 5 ? 4 6 ? 1 4 ? 2 4 ! 4 ? 1 2 ? 2 3 ? 3 4 ? 4 1 ! 3
|
Hard
| 5 | 1,887 | 363 | 0 | 20 |
|
1,797 |
E
|
1797E
|
E. Li Hua and Array
| 2,300 |
brute force; data structures; dsu; math; number theory; two pointers
|
Li Hua wants to solve a problem about \(\varphi\) — Euler's totient function. Please recall that \(\varphi(x)=\sum\limits_{i=1}^x[\gcd(i,x)=1]\).\(^{\dagger,\ddagger}\)He has a sequence \(a_1,a_2,\cdots,a_n\) and he wants to perform \(m\) operations: ""1 \(l\) \(r\)"" (\(1\le l\le r\le n\)) — for each \(x\in[l,r]\), change \(a_x\) into \(\varphi(a_x)\). ""2 \(l\) \(r\)"" (\(1\le l\le r\le n\)) — find out the minimum changes needed to make sure \(a_l=a_{l+1}=\cdots=a_r\). In each change, he chooses one \(x\in[l,r]\), change \(a_x\) into \(\varphi(a_x)\). Each operation of this type is independent, which means the array doesn't actually change. Suppose you were Li Hua, please solve this problem.\(^\dagger\) \(\gcd(x,y)\) denotes the greatest common divisor (GCD) of integers \(x\) and \(y\). \(^\ddagger\) The notation \([\textrm{cond}]\) equals \(1\) if the condition \(\textrm{cond}\) is true, and \(0\) otherwise.
|
The first line contains two integers \(n\) and \(m\) (\(1\le n,m\le 10^{5}\)) — the number of elements in the array and the number of operations to process, respectively.The second line contains \(n\) integers \(a_{1},a_{2},\cdots ,a_{n}\) (\(1\le a_{i}\le 5\cdot 10^{6}\)) — the elements of the array.Next \(m\) lines, each line contains three integers \(t_{i},l_{i},r_{i}\) (\(t_i\in\{1,2\},1\le l_i\le r_i\le n\)) — the \(i\)-th operation.
|
For each ""2 \(l\) \(r\)"", output the answer in an separate line.
|
Denote \(\varphi^k(x)=\begin{cases}x,&k=0\\\varphi(\varphi^{k-1}(x)),&k > 0\end{cases}\).At first, \(a=[8,1,6,3,7]\).To make sure \(a_1=a_2=a_3=a_4=a_5\), we can change \(a\) to \(a'=[\varphi^3(8),\varphi^0(1),\varphi^2(6),\varphi^2(3),\varphi^3(7)]=[1,1,1,1,1]\), using \(3+0+2+2+3=10\) changes.To make sure \(a_3=a_4\), we can change \(a\) to \(a'=[\varphi^0(8),\varphi^0(1),\varphi^1(6),\varphi^1(3),\varphi^0(7)]=[8,1,2,2,7]\), using \(0+0+1+1+0=2\) changes.After ""1 \(1\) \(3\)"", \(a\) is changed to \(a=[\varphi^1(8),\varphi^1(1),\varphi^1(6),\varphi^0(3),\varphi^0(7)]=[4,1,2,3,7]\).To make sure \(a_3=a_4\), we can change \(a\) to \(a'=[\varphi^0(4),\varphi^0(1),\varphi^0(2),\varphi^1(3),\varphi^0(7)]=[4,1,2,2,7]\), using \(0+0+0+1+0=1\) change.
|
Input: 5 4 8 1 6 3 7 2 1 5 2 3 4 1 1 3 2 3 4 | Output: 10 2 1
|
Expert
| 6 | 924 | 442 | 66 | 17 |
379 |
A
|
379A
|
A. New Year Candles
| 1,000 |
implementation
|
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like any other new candle.Now Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number.
|
The single line contains two integers, a and b (1 ≤ a ≤ 1000; 2 ≤ b ≤ 1000).
|
Print a single integer — the number of hours Vasily can light up the room for.
|
Consider the first sample. For the first four hours Vasily lights up new candles, then he uses four burned out candles to make two new ones and lights them up. When these candles go out (stop burning), Vasily can make another candle. Overall, Vasily can light up the room for 7 hours.
|
Input: 4 2 | Output: 7
|
Beginner
| 1 | 466 | 76 | 78 | 3 |
110 |
A
|
110A
|
A. Nearly Lucky Number
| 800 |
implementation
|
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number n is a nearly lucky number.
|
The only line contains an integer n (1 ≤ n ≤ 1018).Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
|
Print on the single line ""YES"" if n is a nearly lucky number. Otherwise, print ""NO"" (without the quotes).
|
In the first sample there are 3 lucky digits (first one and last two), so the answer is ""NO"".In the second sample there are 7 lucky digits, 7 is lucky number, so the answer is ""YES"".In the third sample there are no lucky digits, so the answer is ""NO"".
|
Input: 40047 | Output: NO
|
Beginner
| 1 | 402 | 202 | 109 | 1 |
105 |
E
|
105E
|
E. Lift and Throw
| 2,500 |
brute force
|
You are given a straight half-line divided into segments of unit length, which we will call positions. The positions are numbered by positive integers that start with 1 from the end of half-line, i. e. 1, 2, 3 and so on. The distance between the positions is the absolute difference between the respective numbers. Laharl, Etna and Flonne occupy some positions on the half-line and they want to get to the position with the largest possible number. They are originally placed in different positions. Each of the characters can perform each of the following actions no more than once: Move a certain distance. Grab another character and lift him above the head. Throw the lifted character a certain distance. Each character has a movement range parameter. They can only move to free positions, assuming that distance between those positions doesn't exceed the movement range. One character can lift another character if the distance between the two characters equals 1, and no one already holds that another character. We can assume that the lifted character moves to the same position as the person who has lifted him, and the position in which he stood before becomes free. A lifted character cannot perform any actions and the character that holds him cannot walk. Also, each character has a throwing range parameter. It is the distance at which this character can throw the one lifted above his head. He can only throw a character to a free position, and only when there is a lifted character. We accept the situation when one person grabs another one who in his turn has the third character in his hands. This forms a ""column"" of three characters. For example, Laharl can hold Etna while Etna holds Flonne. In this case, Etna and the Flonne cannot perform any actions, and Laharl can only throw Etna (together with Flonne) at some distance. Laharl, Etna and Flonne perform actions in any order. They perform actions in turns, that is no two of them can do actions at the same time.Determine the maximum number of position at least one of the characters can reach. That is, such maximal number x so that one of the characters can reach position x.
|
The first line contains three integers: Laharl's position, his movement range and throwing range. The second and the third lines describe Etna's and Flonne's parameters correspondingly in the similar form. It is guaranteed that the three characters occupy distinct positions. All numbers in the input are between 1 and 10, inclusive.
|
Print a single number — the maximum ordinal number of position which either Laharl, Etna or Flonne can reach.
|
Let us explain how to reach position 15 in the sample.Initially Laharl occupies position 9, Etna — position 4 and Flonne — position 2.First Laharl moves to position 6.Then Flonne moves to position 5 and grabs Etna.Laharl grabs Flonne and throws to position 9.Flonne throws Etna to position 12.Etna moves to position 15.
|
Input: 9 3 34 3 12 3 3 | Output: 15
|
Expert
| 1 | 2,152 | 333 | 109 | 1 |
474 |
E
|
474E
|
E. Pillars
| 2,000 |
binary search; data structures; dp; sortings; trees
|
Marmot found a row with n pillars. The i-th pillar has the height of hi meters. Starting from one pillar i1, Marmot wants to jump on the pillars i2, ..., ik. (1 ≤ i1 < i2 < ... < ik ≤ n). From a pillar i Marmot can jump on a pillar j only if i < j and |hi - hj| ≥ d, where |x| is the absolute value of the number x.Now Marmot is asking you find out a jump sequence with maximal length and print it.
|
The first line contains two integers n and d (1 ≤ n ≤ 105, 0 ≤ d ≤ 109).The second line contains n numbers h1, h2, ..., hn (1 ≤ hi ≤ 1015).
|
The first line should contain one integer k, the maximal length of a jump sequence.The second line should contain k integers i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n), representing the pillars' indices from the maximal length jump sequence.If there is more than one maximal length jump sequence, print any.
|
In the first example Marmot chooses the pillars 1, 2, 3, 5 with the heights 1, 3, 6, 4. Another jump sequence of length 4 is 1, 2, 4, 5.
|
Input: 5 21 3 6 7 4 | Output: 41 2 3 5
|
Hard
| 5 | 398 | 139 | 309 | 4 |
1,800 |
E1
|
1800E1
|
E1. Unforgivable Curse (easy version)
| 1,400 |
brute force; constructive algorithms; dsu; graphs; greedy; strings
|
This is an easy version of the problem. In this version, \(k\) is always \(3\).The chief wizard of the Wizengamot once caught the evil wizard Drahyrt, but the evil wizard has returned and wants revenge on the chief wizard. So he stole spell \(s\) from his student Harry.The spell — is a \(n\)-length string of lowercase Latin letters.Drahyrt wants to replace spell with an unforgivable curse — string \(t\).Drahyrt, using ancient magic, can swap letters at a distance \(k\) or \(k+1\) in spell as many times as he wants. In this version of the problem, you can swap letters at a distance of \(3\) or \(4\). In other words, Drahyrt can change letters in positions \(i\) and \(j\) in spell \(s\) if \(|i-j|=3\) or \(|i-j|=4\).For example, if \(s = \) ""talant"" and \(t = \) ""atltna"", Drahyrt can act as follows: swap the letters at positions \(1\) and \(4\) to get spell ""aaltnt"". swap the letters at positions \(2\) and \(6\) to get spell ""atltna"". You are given spells \(s\) and \(t\). Can Drahyrt change spell \(s\) to \(t\)?
|
The first line of input gives a single integer \(T\) (\(1 \le T \le 10^4\)) — the number of test cases in the test.Descriptions of the test cases are follow.The first line contains two integers \(n, k\) (\(1 \le n \le 2 \cdot 10^5\), \(k = 3\)) — the length spells and the number \(k\) such that Drahyrt can change letters in a spell at a distance \(k\) or \(k+1\).The second line gives spell \(s\) — a string of length \(n\) consisting of lowercase Latin letters.The third line gives spell \(t\) — a string of length \(n\) consisting of lowercase Latin letters.It is guaranteed that the sum of \(n\) values over all test cases does not exceed \(2 \cdot 10^5\). Note that there is no limit on the sum of \(k\) values over all test cases.
|
For each test case, output on a separate line ""YES"" if Drahyrt can change spell \(s\) to \(t\) and ""NO"" otherwise.You can output the answer in any case (for example, lines ""yEs"", ""yes"", ""Yes"" and ""YES"" will be recognized as positive answer).
|
The first example is explained in the condition.In the second example we can proceed as follows: Swap the letters at positions \(2\) and \(5\) (distance \(3\)), then we get the spell ""aaacbba"". Swap the letters at positions \(4\) and \(7\) (distance \(3\)), then you get the spell ""aaaabbc"". In the third example, we can show that it is impossible to get the string \(t\) from the string \(s\) by swapping the letters at a distance of \(3\) or \(4\).In the fourth example, for example, the following sequence of transformations is appropriate: ""accio"" \(\rightarrow\) ""aocic"" \(\rightarrow\) ""cocia"" \(\rightarrow\) ""iocca"" \(\rightarrow\) ""aocci"" \(\rightarrow\) ""aicco"" \(\rightarrow\) ""cicao"" In the fifth example, you can show that it is impossible to get the string \(s\) from the string \(t\).In the sixth example, it is enough to swap the two outermost letters.
|
Input: 76 3talantatltna7 3abacabaaaaabbc12 3abracadabraaavadakedavra5 3acciocicao5 3lumosmolus4 3uwjttwju4 3kvpxvxpk | Output: YES YES NO YES NO YES NO
|
Easy
| 6 | 1,033 | 737 | 253 | 18 |
940 |
B
|
940B
|
B. Our Tanya is Crying Out Loud
| 1,400 |
dp; greedy
|
Right now she actually isn't. But she will be, if you don't solve this problem.You are given integers n, k, A and B. There is a number x, which is initially equal to n. You are allowed to perform two types of operations: Subtract 1 from x. This operation costs you A coins. Divide x by k. Can be performed only if x is divisible by k. This operation costs you B coins. What is the minimum amount of coins you have to pay to make x equal to 1?
|
The first line contains a single integer n (1 ≤ n ≤ 2·109).The second line contains a single integer k (1 ≤ k ≤ 2·109).The third line contains a single integer A (1 ≤ A ≤ 2·109).The fourth line contains a single integer B (1 ≤ B ≤ 2·109).
|
Output a single integer — the minimum amount of coins you have to pay to make x equal to 1.
|
In the first testcase, the optimal strategy is as follows: Subtract 1 from x (9 → 8) paying 3 coins. Divide x by 2 (8 → 4) paying 1 coin. Divide x by 2 (4 → 2) paying 1 coin. Divide x by 2 (2 → 1) paying 1 coin. The total cost is 6 coins.In the second test case the optimal strategy is to subtract 1 from x 4 times paying 8 coins in total.
|
Input: 9231 | Output: 6
|
Easy
| 2 | 442 | 238 | 91 | 9 |
780 |
B
|
780B
|
B. The Meeting Place Cannot Be Changed
| 1,600 |
binary search
|
The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north.You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.
|
The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends.The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters.The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second.
|
Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if holds.
|
In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds.
|
Input: 37 1 31 2 1 | Output: 2.000000000000
|
Medium
| 1 | 567 | 325 | 307 | 7 |
1,228 |
F
|
1228F
|
F. One Node is Gone
| 2,500 |
constructive algorithms; implementation; trees
|
You have an integer \(n\). Let's define following tree generation as McDic's generation: Make a complete and full binary tree of \(2^{n} - 1\) vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes. Select a non-root vertex \(v\) from that binary tree. Remove \(v\) from tree and make new edges between \(v\)'s parent and \(v\)'s direct children. If \(v\) has no children, then no new edges will be made. You have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree.
|
The first line contains integer \(n\) (\(2 \le n \le 17\)).The \(i\)-th of the next \(2^{n} - 3\) lines contains two integers \(a_{i}\) and \(b_{i}\) (\(1 \le a_{i} \lt b_{i} \le 2^{n} - 2\)) — meaning there is an edge between \(a_{i}\) and \(b_{i}\). It is guaranteed that the given edges form a tree.
|
Print two lines.In the first line, print a single integer — the number of answers. If given tree cannot be made by McDic's generation, then print \(0\).In the second line, print all possible answers in ascending order, separated by spaces. If the given tree cannot be made by McDic's generation, then don't print anything.
|
In the first example, \(3\) is the only possible answer. In the second example, there are \(2\) possible answers. In the third example, the tree can't be generated by McDic's generation.
|
Input: 4 1 2 1 3 2 4 2 5 3 6 3 13 3 14 4 7 4 8 5 9 5 10 6 11 6 12 | Output: 1 3
|
Expert
| 3 | 684 | 302 | 322 | 12 |
1,709 |
B
|
1709B
|
B. Also Try Minecraft
| 900 |
data structures; dp; implementation
|
You are beta testing the new secret Terraria update. This update will add quests to the game!Simply, the world map can be represented as an array of length \(n\), where the \(i\)-th column of the world has height \(a_i\).There are \(m\) quests you have to test. The \(j\)-th of them is represented by two integers \(s_j\) and \(t_j\). In this quest, you have to go from the column \(s_j\) to the column \(t_j\). At the start of the quest, you are appearing at the column \(s_j\).In one move, you can go from the column \(x\) to the column \(x-1\) or to the column \(x+1\). In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height \(p\) to the column with the height \(q\), then you get some amount of fall damage. If the height \(p\) is greater than the height \(q\), you get \(p - q\) fall damage, otherwise you fly up and get \(0\) damage.For each of the given quests, determine the minimum amount of fall damage you can get during this quest.
|
The first line of the input contains two integers \(n\) and \(m\) (\(2 \le n \le 10^5; 1 \le m \le 10^5\)) — the number of columns in the world and the number of quests you have to test, respectively.The second line of the input contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^9\)), where \(a_i\) is the height of the \(i\)-th column of the world.The next \(m\) lines describe quests. The \(j\)-th of them contains two integers \(s_j\) and \(t_j\) (\(1 \le s_j, t_j \le n; s_j \ne t_j\)), which means you have to move from the column \(s_j\) to the column \(t_j\) during the \(j\)-th quest.Note that \(s_j\) can be greater than \(t_j\).
|
Print \(m\) integers. The \(j\)-th of them should be the minimum amount of fall damage you can get during the \(j\)-th quest completion.
|
Input: 7 6 10 8 9 6 8 12 7 1 2 1 7 4 6 7 1 3 5 4 2 | Output: 2 10 0 7 3 1
|
Beginner
| 3 | 1,134 | 658 | 136 | 17 |
|
175 |
D
|
175D
|
D. Plane of Tanks: Duel
| 2,400 |
brute force; dp; math; probabilities
|
Vasya plays the Plane of Tanks.Tanks are described with the following attributes: the number of hit points; the interval between two gun shots (the time required to recharge the gun); the probability that the gun shot will not pierce armor of the enemy tank; the damage to the enemy's tank. The gun damage is described with a segment [l, r], where l and r are integer numbers. The potential gun damage x is chosen with equal probability among all integer numbers of the segment [l, r]. If the shot pierces the armor of an enemy's tank then the enemy loses x hit points. If the number of hit points becomes non-positive then the enemy tank is considered destroyed. It is possible that the shot does not pierce the armor of a tank. In this case the number of hit points doesn't change. The probability that the armor will not be pierced is considered as the shooting tank attribute and does not depend on players' behavior.The victory is near and there is only one enemy tank left. Vasya is ready for the battle — one more battle between the Good and the Evil is inevitable! Two enemies saw each other and each of them fired a shot at the same moment... The last battle has begun! Help Vasya to determine what is the probability that he will win the battle by destroying the enemy tank? If both tanks are destroyed (after simultaneous shots), then Vasya is considered a winner. You can assume that each player fires a shot just after the gun recharge and each tank has infinite number of ammo.
|
The first line contains five integer numbers separated with spaces describing Vasya's tank: the number of hit points hp (10 ≤ hp ≤ 200), the interval between two shots dt (1 ≤ dt ≤ 30), gun damage segment l and r (10 ≤ l ≤ r ≤ 100), the probability that the enemy's tank armor will not be pierced p (0 ≤ p ≤ 100) (percents).The second line describes the tank of Vasya's enemy in the same format.
|
Print the only number with absolute or relative error no more than 10 - 4 — probability of Vasya's victory.
|
In the first example both tanks are destroyed at once after the second shot. The probability of destroying the enemy tank is 1.In the second example Vasya's enemy tank fires the second shot before Vasya's tank, but has no time for the third shot. In order to destroy Vasya's tank it is necessary to fire two shots with damage 50. The probability of that event is = . Otherwise, Vasya wins.In the third example Vasya's enemy tank fires three shots with probability of armor piercing 0.5. In order to destroy Vasya's tank it is necessary that at least 2 of 3 shots pierce the armor of Vasya's tank. The probability of this event is 0.5.
|
Input: 100 3 50 50 0100 3 50 50 0 | Output: 1.000000
|
Expert
| 4 | 1,491 | 395 | 107 | 1 |
175 |
C
|
175C
|
C. Geometry Horse
| 1,600 |
greedy; implementation; sortings; two pointers
|
Vasya plays the Geometry Horse.The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value. There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.
|
The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types.Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes. The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces.Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
|
Print the only number — the maximum number of points Vasya can get.
|
In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.
|
Input: 15 1023 6 | Output: 70
|
Medium
| 4 | 917 | 666 | 67 | 1 |
568 |
C
|
568C
|
C. New Language
| 2,600 |
2-sat; greedy
|
Living in Byteland was good enough to begin with, but the good king decided to please his subjects and to introduce a national language. He gathered the best of wise men, and sent an expedition to faraway countries, so that they would find out all about how a language should be designed.After some time, the wise men returned from the trip even wiser. They locked up for six months in the dining room, after which they said to the king: ""there are a lot of different languages, but almost all of them have letters that are divided into vowels and consonants; in a word, vowels and consonants must be combined correctly.""There are very many rules, all of them have exceptions, but our language will be deprived of such defects! We propose to introduce a set of formal rules of combining vowels and consonants, and include in the language all the words that satisfy them.The rules of composing words are: The letters are divided into vowels and consonants in some certain way; All words have a length of exactly n; There are m rules of the form (pos1, t1, pos2, t2). Each rule is: if the position pos1 has a letter of type t1, then the position pos2 has a letter of type t2.You are given some string s of length n, it is not necessarily a correct word of the new language. Among all the words of the language that lexicographically not smaller than the string s, find the minimal one in lexicographic order.
|
The first line contains a single line consisting of letters 'V' (Vowel) and 'C' (Consonant), determining which letters are vowels and which letters are consonants. The length of this string l is the size of the alphabet of the new language (1 ≤ l ≤ 26). The first l letters of the English alphabet are used as the letters of the alphabet of the new language. If the i-th character of the string equals to 'V', then the corresponding letter is a vowel, otherwise it is a consonant.The second line contains two integers n, m (1 ≤ n ≤ 200, 0 ≤ m ≤ 4n(n - 1)) — the number of letters in a single word and the number of rules, correspondingly.Next m lines describe m rules of the language in the following format: pos1, t1, pos2, t2 (1 ≤ pos1, pos2 ≤ n, pos1 ≠ pos2, 'V', 'C' }).The last line contains string s of length n, consisting of the first l small letters of the English alphabet.It is guaranteed that no two rules are the same.
|
Print a smallest word of a language that is lexicographically not smaller than s. If such words does not exist (for example, if the language has no words at all), print ""-1"" (without the quotes).
|
In the first test word ""aa"" is not a word of the language, but word ""ab"" is.In the second test out of all four possibilities only word ""bb"" is not a word of a language, but all other words are lexicographically less, so there is no answer.In the third test, due to the last rule, ""abac"" doesn't belong to the language (""a"" is a vowel, ""c"" is a consonant). The only word with prefix ""ab"" that meets the given rules is ""abaa"". But it is less than ""abac"", so the answer will be ""acaa""
|
Input: VC2 11 V 2 Caa | Output: ab
|
Expert
| 2 | 1,408 | 931 | 197 | 5 |
2,095 |
B
|
2095B
|
B. Plinko
| 0 |
*special; games; interactive
|
Can you win 10 times?
|
The only line contains the text ""\(\texttt{Game}~x\)"", where \(x\) is an integer between \(1\) and \(10\) (inclusive) — the number of the current round of the game.
|
Output a single integer representing the number of the column you want to drop into.
|
Input: Game 1 | Output:
|
Beginner
| 3 | 21 | 166 | 84 | 20 |
|
1,205 |
A
|
1205A
|
A. Almost Equal
| 1,200 |
constructive algorithms; greedy; math
|
You are given integer \(n\). You have to arrange numbers from \(1\) to \(2n\), using each of them exactly once, on the circle, so that the following condition would be satisfied:For every \(n\) consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard \(2n\) numbers differ not more than by \(1\).For example, choose \(n = 3\). On the left you can see an example of a valid arrangement: \(1 + 4 + 5 = 10\), \(4 + 5 + 2 = 11\), \(5 + 2 + 3 = 10\), \(2 + 3 + 6 = 11\), \(3 + 6 + 1 = 10\), \(6 + 1 + 4 = 11\), any two numbers differ by at most \(1\). On the right you can see an invalid arrangement: for example, \(5 + 1 + 6 = 12\), and \(3 + 2 + 4 = 9\), \(9\) and \(12\) differ more than by \(1\).
|
The first and the only line contain one integer \(n\) (\(1 \le n \le 10^5\)).
|
If there is no solution, output ""NO"" in the first line. If there is a solution, output ""YES"" in the first line. In the second line output \(2n\) numbers — numbers from \(1\) to \(2n\) in the order they will stay in the circle. Each number should appear only once. If there are several solutions, you can output any of them.
|
Example from the statement is shown for the first example. It can be proved that there is no solution in the second example.
|
Input: 3 | Output: YES 1 4 5 2 3 6
|
Easy
| 3 | 749 | 77 | 327 | 12 |
859 |
F
|
859F
|
F. Ordering T-Shirts
| 2,800 |
greedy
|
It's another Start[c]up, and that means there are T-shirts to order. In order to make sure T-shirts are shipped as soon as possible, we've decided that this year we're going to order all of the necessary T-shirts before the actual competition. The top C contestants are going to be awarded T-shirts, but we obviously don't know which contestants that will be. The plan is to get the T-Shirt sizes of all contestants before the actual competition, and then order enough T-shirts so that no matter who is in the top C we'll have T-shirts available in order to award them.In order to get the T-shirt sizes of the contestants, we will send out a survey. The survey will allow contestants to either specify a single desired T-shirt size, or two adjacent T-shirt sizes. If a contestant specifies two sizes, it means that they can be awarded either size.As you can probably tell, this plan could require ordering a lot of unnecessary T-shirts. We'd like your help to determine the minimum number of T-shirts we'll need to order to ensure that we'll be able to award T-shirts no matter the outcome of the competition.
|
Input will begin with two integers N and C (1 ≤ N ≤ 2·105, 1 ≤ C), the number of T-shirt sizes and number of T-shirts to be awarded, respectively.Following this is a line with 2·N - 1 integers, s1 through s2·N - 1 (0 ≤ si ≤ 108). For odd i, si indicates the number of contestants desiring T-shirt size ((i + 1) / 2). For even i, si indicates the number of contestants okay receiving either of T-shirt sizes (i / 2) and (i / 2 + 1). C will not exceed the total number of contestants.
|
Print the minimum number of T-shirts we need to buy.
|
In the first example, we can buy 100 of each size.
|
Input: 2 200100 250 100 | Output: 200
|
Master
| 1 | 1,109 | 482 | 52 | 8 |
1,103 |
C
|
1103C
|
C. Johnny Solving
| 2,700 |
constructive algorithms; dfs and similar; graphs; math
|
Today is tuesday, that means there is a dispute in JOHNNY SOLVING team again: they try to understand who is Johnny and who is Solving. That's why guys asked Umnik to help them. Umnik gave guys a connected graph with \(n\) vertices without loops and multiedges, such that a degree of any vertex is at least \(3\), and also he gave a number \(1 \leq k \leq n\). Because Johnny is not too smart, he promised to find a simple path with length at least \(\frac{n}{k}\) in the graph. In reply, Solving promised to find \(k\) simple by vertices cycles with representatives, such that: Length of each cycle is at least \(3\). Length of each cycle is not divisible by \(3\). In each cycle must be a representative - vertex, which belongs only to this cycle among all printed cycles. You need to help guys resolve the dispute, for that you need to find a solution for Johnny: a simple path with length at least \(\frac{n}{k}\) (\(n\) is not necessarily divided by \(k\)), or solution for Solving: \(k\) cycles that satisfy all the conditions above. If there is no any solution - print \(-1\).
|
The first line contains three integers \(n\), \(m\) and \(k\) (\(1 \leq k \leq n \leq 2.5 \cdot 10^5, 1 \leq m \leq 5 \cdot 10^5\))Next \(m\) lines describe edges of the graph in format \(v\), \(u\) (\(1 \leq v, u \leq n\)). It's guaranteed that \(v \neq u\) and all \(m\) pairs are distinct.It's guaranteed that a degree of each vertex is at least \(3\).
|
Print PATH in the first line, if you solve problem for Johnny. In the second line print the number of vertices in the path \(c\) (\(c \geq \frac{n}{k}\)). And in the third line print vertices describing the path in route order.Print CYCLES in the first line, if you solve problem for Solving. In the following lines describe exactly \(k\) cycles in the following format: in the first line print the size of the cycle \(c\) (\(c \geq 3\)). In the second line print the cycle in route order. Also, the first vertex in the cycle must be a representative.Print \(-1\) if there is no any solution. The total amount of printed numbers in the output must be at most \(10^6\). It's guaranteed, that if exists any solution then there is a correct output satisfies this restriction.
|
Input: 4 6 2 1 2 1 3 1 4 2 3 2 4 3 4 | Output: PATH 4 1 2 3 4
|
Master
| 4 | 1,082 | 355 | 772 | 11 |
|
381 |
A
|
381A
|
A. Sereja and Dima
| 800 |
greedy; implementation; two pointers
|
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.
|
The first line contains integer n (1 ≤ n ≤ 1000) — the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000.
|
On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game.
|
In the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5.
|
Input: 44 1 2 10 | Output: 12 5
|
Beginner
| 3 | 721 | 229 | 184 | 3 |
425 |
C
|
425C
|
C. Sereja and Two Sequences
| 2,300 |
data structures; dp
|
Sereja has two sequences a1, a2, ..., an and b1, b2, ..., bm, consisting of integers. One day Sereja got bored and he decided two play with them. The rules of the game was very simple. Sereja makes several moves, in one move he can perform one of the following actions: Choose several (at least one) first elements of sequence a (non-empty prefix of a), choose several (at least one) first elements of sequence b (non-empty prefix of b); the element of sequence a with the maximum index among the chosen ones must be equal to the element of sequence b with the maximum index among the chosen ones; remove the chosen elements from the sequences. Remove all elements of both sequences. The first action is worth e energy units and adds one dollar to Sereja's electronic account. The second action is worth the number of energy units equal to the number of elements Sereja removed from the sequences before performing this action. After Sereja performed the second action, he gets all the money that he earned on his electronic account during the game.Initially Sereja has s energy units and no money on his account. What maximum number of money can Sereja get? Note, the amount of Seraja's energy mustn't be negative at any time moment.
|
The first line contains integers n, m, s, e (1 ≤ n, m ≤ 105; 1 ≤ s ≤ 3·105; 103 ≤ e ≤ 104). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). The third line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 105).
|
Print a single integer — maximum number of money in dollars that Sereja can get.
|
Input: 5 5 100000 10001 2 3 4 53 2 4 5 1 | Output: 3
|
Expert
| 2 | 1,234 | 226 | 80 | 4 |
|
863 |
G
|
863G
|
G. Graphic Settings
| 3,200 |
Recently Ivan bought a new computer. Excited, he unpacked it and installed his favourite game. With his old computer Ivan had to choose the worst possible graphic settings (because otherwise the framerate would be really low), but now he wants to check, maybe his new computer can perform well even with the best possible graphics?There are m graphics parameters in the game. i-th parameter can be set to any positive integer from 1 to ai, and initially is set to bi (bi ≤ ai). So there are different combinations of parameters. Ivan can increase or decrease any of these parameters by 1; after that the game will be restarted with new parameters (and Ivan will have the opportunity to check chosen combination of parameters).Ivan wants to try all p possible combinations. Also he wants to return to the initial settings after trying all combinations, because he thinks that initial settings can be somehow best suited for his hardware. But Ivan doesn't really want to make a lot of restarts.So he wants you to tell the following: If there exists a way to make exactly p changes (each change either decreases or increases some parameter by 1) to try all possible combinations and return to initial combination, then Ivan wants to know this way. Otherwise, if there exists a way to make exactly p - 1 changes to try all possible combinations (including the initial one), then Ivan wants to know this way. Help Ivan by showing him the way to change parameters!
|
The first line of input contains one integer number m (1 ≤ m ≤ 6).The second line contains m integer numbers a1, a2, ..., am (2 ≤ ai ≤ 1000). It is guaranteed that .The third line contains m integer numbers b1, b2, ..., bm (1 ≤ bi ≤ ai).
|
If there is a way to make exactly p changes (each change either decreases or increases some parameter by 1) to try all possible combinations and return to initial combination, then output Cycle in the first line. Then p lines must follow, each desribing a change. The line must be either inc x (increase parameter x by 1) or dec x (decrease it).Otherwise, if there is a way to make exactly p - 1 changes to try all possible combinations (including the initial one), then output Path in the first line. Then p - 1 lines must follow, each describing the change the same way as mentioned above.Otherwise, output No.
|
Input: 131 | Output: Pathinc 1inc 1
|
Master
| 0 | 1,458 | 237 | 612 | 8 |
||
1,437 |
D
|
1437D
|
D. Minimal Height Tree
| 1,600 |
graphs; greedy; shortest paths; trees
|
Monocarp had a tree which consisted of \(n\) vertices and was rooted at vertex \(1\). He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:a = [] # the order in which vertices were processedq = Queue()q.put(1) # place the root at the end of the queuewhile not q.empty(): k = q.pop() # retrieve the first vertex from the queue a.append(k) # append k to the end of the sequence in which vertices were visited for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order q.put(y)Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.Monocarp knows that there are many trees (in the general case) with the same visiting order \(a\), so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex \(1\) is \(0\), since it's the root, and the depth of all root's children are \(1\).Help Monocarp to find any tree with given visiting order \(a\) and minimum height.
|
The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases.The first line of each test case contains a single integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) — the number of vertices in the tree.The second line of each test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le n\); \(a_i \neq a_j\); \(a_1 = 1\)) — the order in which the vertices were visited by the BFS algorithm.It's guaranteed that the total sum of \(n\) over test cases doesn't exceed \(2 \cdot 10^5\).
|
For each test case print the minimum possible height of a tree with the given visiting order \(a\).
|
In the first test case, there is only one tree with the given visiting order: In the second test case, there is only one tree with the given visiting order as well: In the third test case, an optimal tree with the given visiting order is shown below:
|
Input: 3 4 1 4 3 2 2 1 2 3 1 2 3 | Output: 3 1 1
|
Medium
| 4 | 1,555 | 526 | 99 | 14 |
595 |
A
|
595A
|
A. Vitaly and Night
| 800 |
constructive algorithms; implementation
|
One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2·m from left to right, then the j-th flat of the i-th floor has windows 2·j - 1 and 2·j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.
|
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100) — the number of floors in the house and the number of flats on each floor respectively.Next n lines describe the floors from top to bottom and contain 2·m characters each. If the i-th window of the given floor has lights on, then the i-th character of this line is '1', otherwise it is '0'.
|
Print a single integer — the number of flats that have lights on in at least one window, that is, the flats where, according to Vitaly, people aren't sleeping.
|
In the first test case the house has two floors, two flats on each floor. That is, in total there are 4 flats. The light isn't on only on the second floor in the left flat. That is, in both rooms of the flat the light is off.In the second test case the house has one floor and the first floor has three flats. The light is on in the leftmost flat (in both windows) and in the middle flat (in one window). In the right flat the light is off.
|
Input: 2 20 0 0 11 0 1 1 | Output: 3
|
Beginner
| 2 | 893 | 365 | 159 | 5 |
744 |
D
|
744D
|
D. Hongcow Draws a Circle
| 3,200 |
geometry
|
Hongcow really likes the color red. Hongcow doesn't like the color blue.Hongcow is standing in an infinite field where there are n red points and m blue points.Hongcow wants to draw a circle in the field such that this circle contains at least one red point, and no blue points. Points that line exactly on the boundary of the circle can be counted as either inside or outside.Compute the radius of the largest circle that satisfies this condition. If this circle can have arbitrarily large size, print - 1. Otherwise, your answer will be accepted if it has relative or absolute error at most 10 - 4.
|
The first line of the input will contain two integers n, m (1 ≤ n, m ≤ 1, 000).The next n lines will contain two integers xi, yi (1 ≤ xi, yi ≤ 104). This denotes the coordinates of a red point.The next m lines will contain two integers xi, yi (1 ≤ xi, yi ≤ 104). This denotes the coordinates of a blue point.No two points will have the same coordinates.
|
Print - 1 if the circle can have arbitrary size. Otherwise, print a floating point number representing the largest radius circle that satisfies the conditions. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
|
This is a picture of the first sample This is a picture of the second sample
|
Input: 2 52 33 41 11 44 24 72 5 | Output: 3.5355338827
|
Master
| 1 | 600 | 353 | 390 | 7 |
1,566 |
E
|
1566E
|
E. Buds Re-hanging
| 2,000 |
constructive algorithms; dfs and similar; dp; greedy; trees
|
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex \(v\) (different from root) is the previous to \(v\) vertex on the shortest path from the root to the vertex \(v\). Children of the vertex \(v\) are all vertices for which \(v\) is the parent.A vertex is a leaf if it has no children. We call a vertex a bud, if the following three conditions are satisfied: it is not a root, it has at least one child, and all its children are leaves. You are given a rooted tree with \(n\) vertices. The vertex \(1\) is the root. In one operation you can choose any bud with all its children (they are leaves) and re-hang them to any other vertex of the tree. By doing that you delete the edge connecting the bud and its parent and add an edge between the bud and the chosen vertex of the tree. The chosen vertex cannot be the bud itself or any of its children. All children of the bud stay connected to the bud.What is the minimum number of leaves it is possible to get if you can make any number of the above-mentioned operations (possibly zero)?
|
The input consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) — the number of the vertices in the given tree.Each of the next \(n-1\) lines contains two integers \(u\) and \(v\) (\(1 \le u, v \le n\), \(u \neq v\)) meaning that there is an edge between vertices \(u\) and \(v\) in the tree.It is guaranteed that the given graph is a tree.It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(2 \cdot 10^5\).
|
For each test case print a single integer — the minimal number of leaves that is possible to get after some operations.
|
In the first test case the tree looks as follows: Firstly you can choose a bud vertex \(4\) and re-hang it to vertex \(3\). After that you can choose a bud vertex \(2\) and re-hang it to vertex \(7\). As a result, you will have the following tree with \(2\) leaves: It can be proved that it is the minimal number of leaves possible to get.In the second test case the tree looks as follows: You can choose a bud vertex \(3\) and re-hang it to vertex \(5\). As a result, you will have the following tree with \(2\) leaves: It can be proved that it is the minimal number of leaves possible to get.
|
Input: 5 7 1 2 1 3 1 4 2 5 2 6 4 7 6 1 2 1 3 2 4 2 5 3 6 2 1 2 7 7 3 1 5 1 3 4 6 4 7 2 1 6 2 1 2 3 4 5 3 4 3 6 | Output: 2 2 1 2 1
|
Hard
| 5 | 1,101 | 642 | 119 | 15 |
1,411 |
A
|
1411A
|
A. In-game Chat
| 800 |
implementation
|
You have been assigned to develop a filter for bad messages in the in-game chat. A message is a string \(S\) of length \(n\), consisting of lowercase English letters and characters ')'. The message is bad if the number of characters ')' at the end of the string strictly greater than the number of remaining characters. For example, the string "")bc)))"" has three parentheses at the end, three remaining characters, and is not considered bad.
|
The first line contains the number of test cases \(t\) (\(1 \leq t \leq 100\)). Description of the \(t\) test cases follows.The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 100\)). The second line of each test case contains a string \(S\) of length \(n\), consisting of lowercase English letters and characters ')'.
|
For each of \(t\) test cases, print ""Yes"" if the string is bad. Otherwise, print ""No"".You can print each letter in any case (upper or lower).
|
Input: 5 2 )) 12 gl))hf)))))) 9 gege))))) 14 )aa))b)))))))) 1 ) | Output: Yes No Yes Yes Yes
|
Beginner
| 1 | 443 | 342 | 145 | 14 |
|
32 |
E
|
32E
|
E. Hide-and-Seek
| 2,400 |
geometry; implementation
|
Victor and Peter are playing hide-and-seek. Peter has hidden, and Victor is to find him. In the room where they are playing, there is only one non-transparent wall and one double-sided mirror. Victor and Peter are points with coordinates (xv, yv) and (xp, yp) respectively. The wall is a segment joining points with coordinates (xw, 1, yw, 1) and (xw, 2, yw, 2), the mirror — a segment joining points (xm, 1, ym, 1) and (xm, 2, ym, 2).If an obstacle has a common point with a line of vision, it's considered, that the boys can't see each other with this line of vision. If the mirror has a common point with the line of vision, it's considered, that the boys can see each other in the mirror, i.e. reflection takes place. The reflection process is governed by laws of physics — the angle of incidence is equal to the angle of reflection. The incident ray is in the same half-plane as the reflected ray, relative to the mirror. I.e. to see each other Victor and Peter should be to the same side of the line, containing the mirror (see example 1). If the line of vision is parallel to the mirror, reflection doesn't take place, and the mirror isn't regarded as an obstacle (see example 4).Victor got interested if he can see Peter, while standing at the same spot. Help him solve this problem.
|
The first line contains two numbers xv and yv — coordinates of Victor.The second line contains two numbers xp and yp — coordinates of Peter.The third line contains 4 numbers xw, 1, yw, 1, xw, 2, yw, 2 — coordinates of the wall.The forth line contains 4 numbers xm, 1, ym, 1, xm, 2, ym, 2 — coordinates of the mirror.All the coordinates are integer numbers, and don't exceed 104 in absolute value. It's guaranteed, that the segments don't have common points, Victor and Peter are not on any of the segments, coordinates of Victor and Peter aren't the same, the segments don't degenerate into points.
|
Output YES, if Victor can see Peter without leaving the initial spot. Otherwise output NO.
|
Input: -1 31 30 2 0 40 0 0 1 | Output: NO
|
Expert
| 2 | 1,291 | 598 | 90 | 0 |
|
1,895 |
E
|
1895E
|
E. Infinite Card Game
| 2,300 |
binary search; brute force; data structures; dfs and similar; dp; dsu; games; graphs; greedy; sortings; two pointers
|
Monocarp and Bicarp are playing a card game. Each card has two parameters: an attack value and a defence value. A card \(s\) beats another card \(t\) if the attack of \(s\) is strictly greater than the defence of \(t\).Monocarp has \(n\) cards, the \(i\)-th of them has an attack value of \(\mathit{ax}_i\) and a defence value of \(\mathit{ay}_i\). Bicarp has \(m\) cards, the \(j\)-th of them has an attack value of \(\mathit{bx}_j\) and a defence value of \(\mathit{by}_j\).On the first move, Monocarp chooses one of his cards and plays it. Bicarp has to respond with his own card that beats that card. After that, Monocarp has to respond with a card that beats Bicarp's card. After that, it's Bicarp's turn, and so forth.After a card is beaten, it returns to the hand of the player who played it. It implies that each player always has the same set of cards to play as at the start of the game. The game ends when the current player has no cards that beat the card which their opponent just played, and the current player loses.If the game lasts for \(100^{500}\) moves, it's declared a draw.Both Monocarp and Bicarp play optimally. That is, if a player has a winning strategy regardless of his opponent's moves, he plays for a win. Otherwise, if he has a drawing strategy, he plays for a draw.You are asked to calculate three values: the number of Monocarp's starting moves that result in a win for Monocarp; the number of Monocarp's starting moves that result in a draw; the number of Monocarp's starting moves that result in a win for Bicarp.
|
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.The first line of each test case contains an integer \(n\) (\(1 \le n \le 3 \cdot 10^5\)) — the number of cards Monocarp has.The second line contains \(n\) integers \(\mathit{ax}_1, \mathit{ax}_2, \dots, \mathit{ax}_n\) (\(1 \le \mathit{ax}_i \le 10^6\)) — the attack values of Monocarp's cards.The third line contains \(n\) integers \(\mathit{ay}_1, \mathit{ay}_2, \dots, \mathit{ay}_n\) (\(1 \le \mathit{ay}_i \le 10^6\)) — the defence values of Monocarp's cards.The fourth line contains a single integer \(m\) (\(1 \le m \le 3 \cdot 10^5\)) — the number of cards Bicarp has.The fifth line contains \(m\) integers \(\mathit{bx}_1, \mathit{bx}_2, \dots, \mathit{bx}_m\) (\(1 \le \mathit{bx}_j \le 10^6\)) — the attack values of Bicarp's cards.The sixth line contains \(m\) integers \(\mathit{by}_1, \mathit{by}_2, \dots, \mathit{by}_m\) (\(1 \le \mathit{by}_j \le 10^6\)) — the defence values of Bicarp's cards.Additional constraints on the input: the sum of \(n\) over all test cases doesn't exceed \(3 \cdot 10^5\), the sum of \(m\) over all test cases doesn't exceed \(3 \cdot 10^5\).
|
For each test case, print three integers: the number of Monocarp's starting moves that result in a win for Monocarp; the number of Monocarp's starting moves that result in a draw; the number of Monocarp's starting moves that result in a win for Bicarp.
|
Input: 338 7 47 1 1028 45 1098 8 5 5 5 4 4 1 42 7 5 2 8 9 7 1 9109 8 7 6 5 5 4 3 2 17 1 6 7 5 8 8 4 9 611051105 | Output: 1 1 1 2 4 3 0 1 0
|
Expert
| 11 | 1,548 | 1,185 | 252 | 18 |
|
111 |
D
|
111D
|
D. Petya and Coloring
| 2,300 |
combinatorics; dp
|
Little Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size n × m (n rows, m columns) in k colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number of distinct colors in both these parts should be the same. Help Petya to count these colorings.
|
The first line contains space-separated integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the board's vertical and horizontal sizes and the number of colors respectively.
|
Print the answer to the problem. As the answer can be quite a large number, you should print it modulo 109 + 7 (1000000007).
|
Input: 2 2 1 | Output: 1
|
Expert
| 2 | 416 | 173 | 124 | 1 |
|
2,047 |
A
|
2047A
|
A. Alyona and a Square Jigsaw Puzzle
| 800 |
implementation; math
|
Alyona assembles an unusual square Jigsaw Puzzle. She does so in \(n\) days in the following manner: On the first day, she starts by placing the central piece in the center of the table. On each day after the first one, she places a certain number of pieces around the central piece in clockwise order, always finishing each square layer completely before starting a new one. For example, she places the first \(14\) pieces in the following order: The colors denote the layers. The third layer is still unfinished. Alyona is happy if at the end of the day the assembled part of the puzzle does not have any started but unfinished layers. Given the number of pieces she assembles on each day, find the number of days Alyona is happy on.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 500\)). The description of the test cases follows. The first line contains a single integer \(n\) (\(1 \le n \le 100\)), the number of days.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 100\), \(a_1 = 1\)), where \(a_i\) is the number of pieces Alyona assembles on the \(i\)-th day.It is guaranteed in each test case that at the end of the \(n\) days, there are no unfinished layers.
|
For each test case, print a single integer: the number of days when Alyona is happy.
|
In the first test case, in the only day Alyona finishes the only layer.In the second test case, on the first day, Alyona finishes the first layer, and on the second day, she finishes the second layer.In the third test case, she finishes the second layer in a few days.In the fourth test case, she finishes the second layer and immediately starts the next one on the same day, therefore, she is not happy on that day. She is only happy on the first and last days.In the fifth test case, Alyona is happy on the first, fourth, and last days.
|
Input: 51121 851 3 2 1 271 2 1 10 2 7 2141 10 10 100 1 1 10 1 10 2 10 2 10 1 | Output: 1 2 2 2 3
|
Beginner
| 2 | 735 | 530 | 84 | 20 |
582 |
A
|
582A
|
A. GCD Table
| 1,700 |
constructive algorithms; greedy; number theory
|
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
|
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
|
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
|
Input: 42 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2 | Output: 4 3 6 2
|
Medium
| 3 | 412 | 377 | 151 | 5 |
|
665 |
A
|
665A
|
A. Buses Between Cities
| 1,600 |
implementation
|
Buses run between the cities A and B, the first one is at 05:00 AM and the last one departs not later than at 11:59 PM. A bus from the city A departs every a minutes and arrives to the city B in a ta minutes, and a bus from the city B departs every b minutes and arrives to the city A in a tb minutes.The driver Simion wants to make his job diverse, so he counts the buses going towards him. Simion doesn't count the buses he meet at the start and finish.You know the time when Simion departed from the city A to the city B. Calculate the number of buses Simion will meet to be sure in his counting.
|
The first line contains two integers a, ta (1 ≤ a, ta ≤ 120) — the frequency of the buses from the city A to the city B and the travel time. Both values are given in minutes.The second line contains two integers b, tb (1 ≤ b, tb ≤ 120) — the frequency of the buses from the city B to the city A and the travel time. Both values are given in minutes.The last line contains the departure time of Simion from the city A in the format hh:mm. It is guaranteed that there are a bus from the city A at that time. Note that the hours and the minutes are given with exactly two digits.
|
Print the only integer z — the number of buses Simion will meet on the way. Note that you should not count the encounters in cities A and B.
|
In the first example Simion departs form the city A at 05:20 AM and arrives to the city B at 05:50 AM. He will meet the first 5 buses from the city B that departed in the period [05:00 AM - 05:40 AM]. Also Simion will meet a bus in the city B at 05:50 AM, but he will not count it.Also note that the first encounter will be between 05:26 AM and 05:27 AM (if we suggest that the buses are go with the sustained speed).
|
Input: 10 3010 3505:20 | Output: 5
|
Medium
| 1 | 599 | 576 | 140 | 6 |
1,219 |
C
|
1219C
|
C. Periodic integer number
| 1,700 |
implementation; strings
|
Alice became interested in periods of integer numbers. We say positive \(X\) integer number is periodic with length \(L\) if there exists positive integer number \(P\) with \(L\) digits such that \(X\) can be written as \(PPPP…P\). For example:\(X = 123123123\) is periodic number with length \(L = 3\) and \(L = 9\)\(X = 42424242\) is periodic number with length \(L = 2,L = 4\) and \(L = 8\)\(X = 12345\) is periodic number with length \(L = 5\)For given positive period length \(L\) and positive integer number \(A\), Alice wants to find smallest integer number \(X\) strictly greater than \(A\) that is periodic with length L.
|
First line contains one positive integer number \(L \ (1 \leq L \leq 10^5)\) representing length of the period. Second line contains one positive integer number \(A \ (1 \leq A \leq 10^{100 000})\).
|
One positive integer number representing smallest positive number that is periodic with length \(L\) and is greater than \(A\).
|
In first example 124124 is the smallest number greater than 123456 that can be written with period L = 3 (P = 124).In the second example 100100 is the smallest number greater than 12345 with period L = 3 (P=100)
|
Input: 3 123456 | Output: 124124
|
Medium
| 2 | 630 | 198 | 127 | 12 |
742 |
A
|
742A
|
A. Arpa’s hard exam and Mehrdad’s naive cheat
| 1,000 |
implementation; math; number theory
|
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do.Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n. Mehrdad has become quite confused and wants you to help him. Please help, although it's a naive cheat.
|
The single line of input contains one integer n (0 ≤ n ≤ 109).
|
Print single integer — the last digit of 1378n.
|
In the first example, last digit of 13781 = 1378 is 8.In the second example, last digit of 13782 = 1378·1378 = 1898884 is 4.
|
Input: 1 | Output: 8
|
Beginner
| 3 | 338 | 62 | 47 | 7 |
488 |
B
|
488B
|
B. Candy Boxes
| 1,900 |
brute force; constructive algorithms; math
|
There is an old tradition of keeping 4 boxes of candies in the house in Cyberland. The numbers of candies are special if their arithmetic mean, their median and their range are all equal. By definition, for a set {x1, x2, x3, x4} (x1 ≤ x2 ≤ x3 ≤ x4) arithmetic mean is , median is and range is x4 - x1. The arithmetic mean and median are not necessary integer. It is well-known that if those three numbers are same, boxes will create a ""debugging field"" and codes in the field will have no bugs.For example, 1, 1, 3, 3 is the example of 4 numbers meeting the condition because their mean, median and range are all equal to 2.Jeff has 4 special boxes of candies. However, something bad has happened! Some of the boxes could have been lost and now there are only n (0 ≤ n ≤ 4) boxes remaining. The i-th remaining box contains ai candies.Now Jeff wants to know: is there a possible way to find the number of candies of the 4 - n missing boxes, meeting the condition above (the mean, median and range are equal)?
|
The first line of input contains an only integer n (0 ≤ n ≤ 4).The next n lines contain integers ai, denoting the number of candies in the i-th box (1 ≤ ai ≤ 500).
|
In the first output line, print ""YES"" if a solution exists, or print ""NO"" if there is no solution.If a solution exists, you should output 4 - n more lines, each line containing an integer b, denoting the number of candies in a missing box.All your numbers b must satisfy inequality 1 ≤ b ≤ 106. It is guaranteed that if there exists a positive integer solution, you can always find such b's meeting the condition. If there are multiple answers, you are allowed to print any of them.Given numbers ai may follow in any order in the input, not necessary in non-decreasing.ai may have stood at any positions in the original set, not necessary on lowest n first positions.
|
For the first sample, the numbers of candies in 4 boxes can be 1, 1, 3, 3. The arithmetic mean, the median and the range of them are all 2.For the second sample, it's impossible to find the missing number of candies.In the third example no box has been lost and numbers satisfy the condition.You may output b in any order.
|
Input: 211 | Output: YES33
|
Hard
| 3 | 1,010 | 163 | 671 | 4 |
499 |
A
|
499A
|
A. Watching a movie
| 1,000 |
greedy; implementation
|
You have decided to watch the best moments of some movie. There are two buttons on your player: Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie. Skip exactly x minutes of the movie (x is some fixed positive integer). If the player is now at the t-th minute of the movie, then as a result of pressing this button, it proceeds to the minute (t + x). Initially the movie is turned on in the player on the first minute, and you want to watch exactly n best moments of the movie, the i-th best moment starts at the li-th minute and ends at the ri-th minute (more formally, the i-th best moment consists of minutes: li, li + 1, ..., ri). Determine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?
|
The first line contains two space-separated integers n, x (1 ≤ n ≤ 50, 1 ≤ x ≤ 105) — the number of the best moments of the movie and the value of x for the second button.The following n lines contain the descriptions of the best moments of the movie, the i-th line of the description contains two integers separated by a space li, ri (1 ≤ li ≤ ri ≤ 105).It is guaranteed that for all integers i from 2 to n the following condition holds: ri - 1 < li.
|
Output a single number — the answer to the problem.
|
In the first sample, the player was initially standing on the first minute. As the minutes from the 1-st to the 4-th one don't contain interesting moments, we press the second button. Now we can not press the second button and skip 3 more minutes, because some of them contain interesting moments. Therefore, we watch the movie from the 4-th to the 6-th minute, after that the current time is 7. Similarly, we again skip 3 minutes and then watch from the 10-th to the 12-th minute of the movie. In total, we watch 6 minutes of the movie.In the second sample, the movie is very interesting, so you'll have to watch all 100000 minutes of the movie.
|
Input: 2 35 610 12 | Output: 6
|
Beginner
| 2 | 882 | 451 | 51 | 4 |
2,003 |
E2
|
2003E2
|
E2. Turtle and Inversions (Hard Version)
| 2,700 |
brute force; data structures; divide and conquer; dp; greedy; math; two pointers
|
This is a hard version of this problem. The differences between the versions are the constraint on \(m\) and \(r_i < l_{i + 1}\) holds for each \(i\) from \(1\) to \(m - 1\) in the easy version. You can make hacks only if both versions of the problem are solved.Turtle gives you \(m\) intervals \([l_1, r_1], [l_2, r_2], \ldots, [l_m, r_m]\). He thinks that a permutation \(p\) is interesting if there exists an integer \(k_i\) for every interval (\(l_i \le k_i < r_i\)), and if he lets \(a_i = \max\limits_{j = l_i}^{k_i} p_j, b_i = \min\limits_{j = k_i + 1}^{r_i} p_j\) for every integer \(i\) from \(1\) to \(m\), the following condition holds:$$$\(\max\limits_{i = 1}^m a_i < \min\limits_{i = 1}^m b_i\)\(Turtle wants you to calculate the maximum number of inversions of all interesting permutations of length \)n\(, or tell him if there is no interesting permutation.An inversion of a permutation \)p\( is a pair of integers \)(i, j)\( (\)1 \le i < j \le n\() such that \)p_i > p_j$$$.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^3\)). The description of the test cases follows.The first line of each test case contains two integers \(n, m\) (\(2 \le n \le 5 \cdot 10^3, 0 \le m \le 5 \cdot 10^3\)) — the length of the permutation and the number of intervals.The \(i\)-th of the following \(m\) lines contains two integers \(l_i, r_i\) (\(1 \le l_i < r_i \le n\)) — the \(i\)-th interval. Note that there may exist identical intervals (i.e., there may exist two different indices \(i, j\) such that \(l_i = l_j\) and \(r_i = r_j\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5 \cdot 10^3\) and the sum of \(m\) over all test cases does not exceed \(5 \cdot 10^3\).
|
For each test case, if there is no interesting permutation, output a single integer \(-1\).Otherwise, output a single integer — the maximum number of inversions.
|
In the third test case, the interesting permutation with the maximum number of inversions is \([5, 2, 4, 3, 1]\).In the fourth test case, the interesting permutation with the maximum number of inversions is \([4, 3, 8, 7, 6, 2, 1, 5]\). In this case, we can let \([k_1, k_2, k_3] = [2, 2, 7]\).In the fifth and the sixth test case, it can be proven that there is no interesting permutation.In the seventh test case, the interesting permutation with the maximum number of inversions is \([4, 7, 6, 3, 2, 1, 5]\). In this case, we can let \([k_1, k_2, k_3, k_4] = [1, 6, 1, 6]\).In the eighth test case, the interesting permutation with the maximum number of inversions is \([4, 7, 3, 6, 2, 5, 1]\).
|
Input: 82 02 11 25 12 48 31 42 57 87 21 44 77 31 21 73 77 41 34 71 34 77 31 23 45 6 | Output: 1 0 8 18 -1 -1 15 15
|
Master
| 7 | 990 | 781 | 161 | 20 |
220 |
C
|
220C
|
C. Little Elephant and Shifts
| 2,100 |
data structures
|
The Little Elephant has two permutations a and b of length n, consisting of numbers from 1 to n, inclusive. Let's denote the i-th (1 ≤ i ≤ n) element of the permutation a as ai, the j-th (1 ≤ j ≤ n) element of the permutation b — as bj.The distance between permutations a and b is the minimum absolute value of the difference between the positions of the occurrences of some number in a and in b. More formally, it's such minimum |i - j|, that ai = bj.A cyclic shift number i (1 ≤ i ≤ n) of permutation b consisting from n elements is a permutation bibi + 1... bnb1b2... bi - 1. Overall a permutation has n cyclic shifts.The Little Elephant wonders, for all cyclic shifts of permutation b, what is the distance between the cyclic shift and permutation a?
|
The first line contains a single integer n (1 ≤ n ≤ 105) — the size of the permutations. The second line contains permutation a as n distinct numbers from 1 to n, inclusive. The numbers are separated with single spaces. The third line contains permutation b in the same format.
|
In n lines print n integers — the answers for cyclic shifts. Print the answers to the shifts in the order of the shifts' numeration in permutation b, that is, first for the 1-st cyclic shift, then for the 2-nd, and so on.
|
Input: 21 22 1 | Output: 10
|
Hard
| 1 | 754 | 277 | 221 | 2 |
|
1,381 |
A1
|
1381A1
|
A1. Prefix Flip (Easy Version)
| 1,300 |
constructive algorithms; data structures; strings
|
This is the easy version of the problem. The difference between the versions is the constraint on \(n\) and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings \(a\) and \(b\) of length \(n\) (a binary string is a string consisting of symbols \(0\) and \(1\)). In an operation, you select a prefix of \(a\), and simultaneously invert the bits in the prefix (\(0\) changes to \(1\) and \(1\) changes to \(0\)) and reverse the order of the bits in the prefix.For example, if \(a=001011\) and you select the prefix of length \(3\), it becomes \(011011\). Then if you select the entire string, it becomes \(001001\).Your task is to transform the string \(a\) into \(b\) in at most \(3n\) operations. It can be proved that it is always possible.
|
The first line contains a single integer \(t\) (\(1\le t\le 1000\)) — the number of test cases. Next \(3t\) lines contain descriptions of test cases.The first line of each test case contains a single integer \(n\) (\(1\le n\le 1000\)) — the length of the binary strings.The next two lines contain two binary strings \(a\) and \(b\) of length \(n\).It is guaranteed that the sum of \(n\) across all test cases does not exceed \(1000\).
|
For each test case, output an integer \(k\) (\(0\le k\le 3n\)), followed by \(k\) integers \(p_1,\ldots,p_k\) (\(1\le p_i\le n\)). Here \(k\) is the number of operations you use and \(p_i\) is the length of the prefix you flip in the \(i\)-th operation.
|
In the first test case, we have \(01\to 11\to 00\to 10\).In the second test case, we have \(01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100\).In the third test case, the strings are already the same. Another solution is to flip the prefix of length \(2\), which will leave \(a\) unchanged.
|
Input: 5 2 01 10 5 01011 11100 2 01 01 10 0110011011 1000110100 1 0 1 | Output: 3 1 2 1 6 5 2 5 3 1 2 0 9 4 1 2 10 4 1 2 1 5 1 1
|
Easy
| 3 | 818 | 434 | 253 | 13 |
1,912 |
D
|
1912D
|
D. Divisibility Test
| 1,900 |
math
|
Daisy has recently learned divisibility rules for integers and she is fascinated by them. One of the tests she learned is a divisibility test by 3. You can find a sum of all digits of a decimal number and check if the resulting sum is divisible by 3. Moreover, the resulting sum of digits is congruent modulo 3 to the original number — the remainder modulo 3 is preserved. For example, \(75 \equiv 7 + 5 \pmod 3\). Daisy is specifically interested in such remainder preserving divisibility tests.There are more examples like that that she learned for decimal integers (integers base 10): To test divisibility modulo 11, find an alternating sum of digits. Counting digits from the last (least significant) digit, add digits on odd positions (the last, 3rd to the last, etc) and subtract digits on even positions (2nd to the last, 4th to the last, etc) to get the sum that is congruent modulo 11 to the original number. For example, \(123 \equiv 1 - 2 + 3 \pmod {11}\). To test divisibility modulo 4, keep the last two digits. Their value is congruent modulo 4 to the original number. For example, \(876543 \equiv 43 \pmod 4\). To test divisibility modulo 7, find an alternating sum of groups of three digits. For example, \(4389328 \equiv 4 - 389 + 328 \pmod 7\). Similar tests can be found in other bases. For example, to test divisibility modulo 5 for octal numbers (base 8), find an alternating sum of groups of two digits. For example, \(1234_8 \equiv -12_8 + 34_8 \pmod 5\).Daisy wants to find such rules for a given base \(b\). She is interested in three kinds of divisibility rules: Kind 1 — take the last \(k\) digits of an integer in base \(b\). Kind 2 — take a sum of groups of \(k\) digits of an integer in base \(b\). Kind 3 — take an alternating sum of groups of \(k\) digits of an integer in base \(b\). It is not always possible to find such a divisibility rule. For example, in base 10 there is no such test for divisibility modulo 6, even though different approaches to testing divisibility by 6 exist.Given base \(b\) and modulo \(n\), Daisy wants to know the smallest group size \(k\) for which such a divisibility test exits.
|
There are several tests in the input. The first line of the input contains an integer \(t\) — the number of tests. The next \(t\) lines describe the tests.Each test consists of a line with two integers \(b\) and \(n\) — the base and the modulo (\(b, n \ge 2\)). The sum of all \(b\) values in the input does not exceed \(10^6\), and the sum of all \(n\) values in the input does not exceed \(10^6\).
|
Write \(t\) lines — a line for each test in the input. On a line for a test write a single integer \(0\) if the divisibility test for a given \(b\) and \(n\) does not exist. Otherwise, write two integers \(a\) and \(k\), where \(a\) is the kind of the divisibility test (1, 2, or 3) and \(k\) is the number of digits in a group for the test, such that \(k\) is the lowest among all possible divisiblity tests for the given \(b\) and \(n\).
|
Input: 610 310 1110 410 78 510 6 | Output: 2 1 3 1 1 2 3 3 3 2 0
|
Hard
| 1 | 2,144 | 399 | 439 | 19 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.