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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17 |
C
|
17C
|
C. Balance
| 2,500 |
dp
|
Nick likes strings very much, he likes to rotate them, sort them, rearrange characters within a string... Once he wrote a random string of characters a, b, c on a piece of paper and began to perform the following operations: to take two adjacent characters and replace the second character with the first one, to take two adjacent characters and replace the first character with the second one To understand these actions better, let's take a look at a string «abc». All of the following strings can be obtained by performing one of the described operations on «abc»: «bbc», «abb», «acc». Let's denote the frequency of a character for each of the characters a, b and c as the number of occurrences of this character in the string. For example, for string «abc»: |a| = 1, |b| = 1, |c| = 1, and for string «bbc»: |a| = 0, |b| = 2, |c| = 1. While performing the described operations, Nick sometimes got balanced strings. Let's say that a string is balanced, if the frequencies of each character differ by at most 1. That is - 1 ≤ |a| - |b| ≤ 1, - 1 ≤ |a| - |c| ≤ 1 и - 1 ≤ |b| - |c| ≤ 1. Would you help Nick find the number of different balanced strings that can be obtained by performing the operations described above, perhaps multiple times, on the given string s. This number should be calculated modulo 51123987.
|
The first line contains integer n (1 ≤ n ≤ 150) — the length of the given string s. Next line contains the given string s. The initial string can be balanced as well, in this case it should be counted too. The given string s consists only of characters a, b and c.
|
Output the only number — the number of different balanced strings that can be obtained by performing the described operations, perhaps multiple times, on the given string s, modulo 51123987.
|
In the first sample it is possible to get 51 different strings through the described operations, but only 7 of them are balanced: «abca», «bbca», «bcca», «bcaa», «abcc», «abbc», «aabc». In the second sample: «abbc», «aabc», «abcc». In the third sample there is only one balanced string — «ab» itself.
|
Input: 4abca | Output: 7
|
Expert
| 1 | 1,314 | 264 | 190 | 0 |
1,142 |
C
|
1142C
|
C. U2
| 2,400 |
geometry
|
Recently Vasya learned that, given two points with different \(x\) coordinates, you can draw through them exactly one parabola with equation of type \(y = x^2 + bx + c\), where \(b\) and \(c\) are reals. Let's call such a parabola an \(U\)-shaped one.Vasya drew several distinct points with integer coordinates on a plane and then drew an \(U\)-shaped parabola through each pair of the points that have different \(x\) coordinates. The picture became somewhat messy, but Vasya still wants to count how many of the parabolas drawn don't have any drawn point inside their internal area. Help Vasya.The internal area of an \(U\)-shaped parabola is the part of the plane that lies strictly above the parabola when the \(y\) axis is directed upwards.
|
The first line contains a single integer \(n\) (\(1 \le n \le 100\,000\)) — the number of points.The next \(n\) lines describe the points, the \(i\)-th of them contains two integers \(x_i\) and \(y_i\) — the coordinates of the \(i\)-th point. It is guaranteed that all points are distinct and that the coordinates do not exceed \(10^6\) by absolute value.
|
In the only line print a single integer — the number of \(U\)-shaped parabolas that pass through at least two of the given points and do not contain any of the given points inside their internal area (excluding the parabola itself).
|
On the pictures below all \(U\)-shaped parabolas that pass through at least two given points are drawn for each of the examples. The \(U\)-shaped parabolas that do not have any given point inside their internal area are drawn in red. The first example. The second example.
|
Input: 3 -1 0 0 2 1 0 | Output: 2
|
Expert
| 1 | 745 | 355 | 232 | 11 |
1,946 |
F
|
1946F
|
F. Nobody is needed
| 2,500 |
2-sat; data structures; dfs and similar; dp
|
Oleg received a permutation \(a\) of length \(n\) as a birthday present.Oleg's friend Nechipor asks Oleg \(q\) questions, each question is characterized by two numbers \(l\) and \(r\), in response to the question Oleg must say the number of sets of indices \((t_1, t_2, \ldots, t_k)\) of any length \(k \ge 1\) such that: \(l \le t_i \le r\) for each \(i\) from \(1\) to \(k\). \(t_i < t_{i+1}\) for each \(i\) from \(1\) to \(k-1\). \(a_{t_{i+1}}\) is divisible by \(a_{t_i}\) for each \(i\) from \(1\) to \(k-1\). Help Oleg and answer all of Nechipor's questions.
|
Each test consists of several sets of input data. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of sets of input data. The description of the sets of input data follows.The first line of each set of input data contains two integers \(n\) and \(q\) (\(1 \le n, q \le 10^6\)) — the length of the permutation and the number of Nechipor's questions.The second line of each set of input data contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le n\)) — the permutation \(a\) itself.In each of the next \(q\) lines of each set of input data, there are two integers \(l\) and \(r\) (\(1 \le l \le r \le n\)) — the next question of Nechipor.It is guaranteed that the sum of the values of \(n\) and the sum of the values of \(q\) over all test cases does not exceed \(10^6\).
|
For each set of input data, output the answers to all of Nechipor's questions.
|
All suitable arrays in the first set of input data: (\(1\)), (\(2\)), (\(3\)), (\(4\)), (\(5\)), (\(6\)), (\(7\)), (\(8\)), (\(1, 3\)), (\(1, 6\)), (\(1, 7\)), (\(1, 6, 7\)), (\(2, 3\)), (\(2, 4\)), (\(2, 5\)), (\(2, 6\)), (\(2, 7\)), (\(2, 8\)), (\(2, 6, 7\)), (\(6, 7\)).All suitable arrays in the fourth set of input data: (\(1\)), (\(2\)), (\(3\)), (\(4\)), (\(5\)), (\(6\)), (\(7\)), (\(8\)), (\(1, 2\)), (\(1, 3\)), (\(1, 4\)), (\(1, 5\)), (\(1, 6\)), (\(1, 7\)), (\(1, 8\)), (\(1, 2, 4\)), (\(1, 2, 6\)), (\(1, 2, 8\)), (\(1, 2, 4, 8\)), (\(1, 3, 6\)), (\(1, 4, 8\)), (\(2, 4\)), (\(2, 6\)), (\(2, 8\)), (\(2, 4, 8\)), (\(3, 6\)), (\(4, 8\)).
|
Input: 48 82 1 6 3 5 4 8 71 82 81 71 61 35 84 42 31 111 13 33 2 11 21 32 38 11 2 3 4 5 6 7 81 8 | Output: 20 15 18 12 5 5 1 3 1 2 3 2 27
|
Expert
| 4 | 565 | 816 | 78 | 19 |
1,910 |
D
|
1910D
|
D. Remove and Add
| 1,800 |
*special; greedy
|
You are given an array \(a_1, a_2, \dots, a_n\), consisting of \(n\) integers.You goal is to make is strictly increasing. To achieve that, you perform each of the following operations exactly once: first, remove any element; second, select any number of elements (possibly, none or all \(n-1\)) and add \(1\) to them. Note that you are not allowed to rearrange the elements of the array.For the resulting array \(a'\), \(a'_1 < a'_2 < \dots < a'_{n-1}\) should hold. Determine if it's possible to achieve that.
|
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\) (\(2 \le n \le 2 \cdot 10^5\)) — the number of elements of the array.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^6\)).The sum of \(n\) over all testcases doesn't exceed \(2 \cdot 10^5\).
|
For each testcase, print YES if it's possible to remove one element and add \(1\) to some elements (possibly, none or all), so that the array becomes strictly increasing. Otherwise, print NO.
|
In the first testcase, you can remove the third element and add \(1\) to the second and the last element. \(a'\) will become \([4, 5, 6]\), which is strictly increasing.In the second testcase, there is no way to perform the operations, so that the result is strictly increasing.In the third testcase, you can remove either of the elements.In the fourth testcase, you are already given a strictly increasing array, but you still have to remove an element. The result \(a'\) can be \([1, 3]\), for example.
|
Input: 844 4 1 554 4 1 5 5210 531 2 332 1 141 1 1 141 3 1 251 1 3 3 1 | Output: YES NO YES YES YES NO YES YES
|
Medium
| 2 | 510 | 387 | 191 | 19 |
180 |
E
|
180E
|
E. Cubes
| 1,800 |
binary search; dp; two pointers
|
Let's imagine that you're playing the following simple computer game. The screen displays n lined-up cubes. Each cube is painted one of m colors. You are allowed to delete not more than k cubes (that do not necessarily go one after another). After that, the remaining cubes join together (so that the gaps are closed) and the system counts the score. The number of points you score equals to the length of the maximum sequence of cubes of the same color that follow consecutively. Write a program that determines the maximum possible number of points you can score.Remember, you may delete no more than k any cubes. It is allowed not to delete cubes at all.
|
The first line contains three integers n, m and k (1 ≤ n ≤ 2·105, 1 ≤ m ≤ 105, 0 ≤ k < n). The second line contains n integers from 1 to m — the numbers of cube colors. The numbers of colors are separated by single spaces.
|
Print the maximum possible number of points you can score.
|
In the first sample you should delete the fifth and the sixth cubes.In the second sample you should delete the fourth and the seventh cubes.In the third sample you shouldn't delete any cubes.
|
Input: 10 3 21 2 1 1 3 2 1 1 2 2 | Output: 4
|
Medium
| 3 | 657 | 222 | 58 | 1 |
534 |
C
|
534C
|
C. Polycarpus' Dice
| 1,600 |
math
|
Polycarp has n dice d1, d2, ..., dn. The i-th dice shows numbers from 1 to di. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d1, d2, ..., dn. However, she finds it enough to make a series of statements of the following type: dice i couldn't show number r. For example, if Polycarp had two six-faced dice and the total sum is A = 11, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).For each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is A.
|
The first line contains two integers n, A (1 ≤ n ≤ 2·105, n ≤ A ≤ s) — the number of dice and the sum of shown values where s = d1 + d2 + ... + dn.The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 106), where di is the maximum value that the i-th dice can show.
|
Print n integers b1, b2, ..., bn, where bi is the number of values for which it is guaranteed that the i-th dice couldn't show them.
|
In the first sample from the statement A equal to 8 could be obtained in the only case when both the first and the second dice show 4. Correspondingly, both dice couldn't show values 1, 2 or 3.In the second sample from the statement A equal to 3 could be obtained when the single dice shows 3. Correspondingly, it couldn't show 1, 2, 4 or 5.In the third sample from the statement A equal to 3 could be obtained when one dice shows 1 and the other dice shows 2. That's why the first dice doesn't have any values it couldn't show and the second dice couldn't show 3.
|
Input: 2 84 4 | Output: 3 3
|
Medium
| 1 | 774 | 273 | 132 | 5 |
1,687 |
B
|
1687B
|
B. Railway System
| 1,700 |
constructive algorithms; graphs; greedy; interactive; sortings
|
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of \(n\) stations with \(m\) bidirectional tracks connecting them. The \(i\)-th track has length \(l_i\) (\(1\le l_i\le 10^6\)). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than \(2m\) queries. The input of the simulator is a string \(s\) of length \(m\), consisting of characters 0 and/or 1. The simulator will assume the \(i\)-th track functional if \(s_i=\) 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
|
The first and only line of input contains two integers \(n,m\) (\(2 \leq n \leq 200\), \(1\le m \le 500\)) — the number of stations and tracks.
|
Here is the graph of the example, satisfying \(l_i=i\).
|
Input: 5 4 0 5 9 7 | Output: ? 0000 ? 1110 ? 1111 ? 1101 ! 7
|
Medium
| 5 | 1,489 | 143 | 0 | 16 |
|
1,201 |
E2
|
1201E2
|
E2. Knightmare (hard)
| 3,000 |
graphs; interactive; shortest paths
|
This is an interactive problem.Alice and Bob are playing a game on the chessboard of size \(n \times m\) where \(n\) and \(m\) are even. The rows are numbered from \(1\) to \(n\) and the columns are numbered from \(1\) to \(m\). There are two knights on the chessboard. A white one initially is on the position \((x_1, y_1)\), while the black one is on the position \((x_2, y_2)\). Alice will choose one of the knights to play with, and Bob will use the other one.The Alice and Bob will play in turns and whoever controls the white knight starts the game. During a turn, the player must move their knight adhering the chess rules. That is, if the knight is currently on the position \((x, y)\), it can be moved to any of those positions (as long as they are inside the chessboard): \((x+1, y+2)\), \((x+1, y-2)\), \((x-1, y+2)\), \((x-1, y-2)\),\((x+2, y+1)\), \((x+2, y-1)\), \((x-2, y+1)\), \((x-2, y-1)\). We all know that knights are strongest in the middle of the board. Both knight have a single position they want to reach: the owner of the white knight wins if it captures the black knight or if the white knight is at \((n/2, m/2)\) and this position is not under attack of the black knight at this moment; The owner of the black knight wins if it captures the white knight or if the black knight is at \((n/2+1, m/2)\) and this position is not under attack of the white knight at this moment. Formally, the player who captures the other knight wins. The player who is at its target square (\((n/2, m/2)\) for white, \((n/2+1, m/2)\) for black) and this position is not under opponent's attack, also wins.A position is under attack of a knight if it can move into this position. Capturing a knight means that a player moves their knight to the cell where the opponent's knight is.If Alice made \(350\) moves and nobody won, the game is a draw.Alice is unsure in her chess skills, so she asks you for a help. Choose a knight and win the game for her. It can be shown, that Alice always has a winning strategy.
|
In the first example, the white knight can reach it's target square in one move.In the second example black knight wins, no matter what white knight moves.
|
Input: 8 8 2 3 1 8 | Output: WHITE 4 4
|
Master
| 3 | 2,017 | 0 | 0 | 12 |
||
1,082 |
F
|
1082F
|
F. Speed Dial
| 2,800 |
dp; strings; trees
|
Polycarp's phone book contains \(n\) phone numbers, each of them is described by \(s_i\) — the number itself and \(m_i\) — the number of times Polycarp dials it in daily.Polycarp has just bought a brand new phone with an amazing speed dial feature! More precisely, \(k\) buttons on it can have a number assigned to it (not necessary from the phone book). To enter some number Polycarp can press one of these \(k\) buttons and then finish the number using usual digit buttons (entering a number with only digit buttons is also possible).Speed dial button can only be used when no digits are entered. No button can have its number reassigned.What is the minimal total number of digit number presses Polycarp can achieve after he assigns numbers to speed dial buttons and enters each of the numbers from his phone book the given number of times in an optimal way?
|
The first line contains two integers \(n\) and \(k\) (\(1 \le n \le 500\), \(1 \le k \le 10\)) — the amount of numbers in Polycarp's phone book and the number of speed dial buttons his new phone has.The \(i\)-th of the next \(n\) lines contain a string \(s_i\) and an integer \(m_i\) \((1 \le m_i \le 500)\), where \(s_i\) is a non-empty string of digits from \(0\) to \(9\) inclusive (the \(i\)-th number), and \(m_i\) is the amount of times it will be dialed, respectively.It is guaranteed that the total length of all phone numbers will not exceed \(500\).
|
Print a single integer — the minimal total number of digit number presses Polycarp can achieve after he assigns numbers to speed dial buttons and enters each of the numbers from his phone book the given number of times in an optimal way.
|
The only speed dial button in the first example should have ""0001"" on it. The total number of digit button presses will be \(0 \cdot 5\) for the first number + \(3 \cdot 4\) for the second + \(2 \cdot 1\) for the third. \(14\) in total.The only speed dial button in the second example should have ""00"" on it. The total number of digit button presses will be \(2 \cdot 5\) for the first number + \(1 \cdot 6\) for the second + \(2 \cdot 1\) for the third. \(18\) in total.
|
Input: 3 1 0001 5 001 4 01 1 | Output: 14
|
Master
| 3 | 860 | 559 | 237 | 10 |
1,149 |
A
|
1149A
|
A. Prefix Sum Primes
| 1,200 |
constructive algorithms; greedy; math; number theory
|
We're giving away nice huge bags containing number tiles! A bag we want to present to you contains \(n\) tiles. Each of them has a single number written on it — either \(1\) or \(2\).However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in any order you wish. We will then compute the sums of all prefixes in the sequence, and then count how many of these sums are prime numbers. If you want to keep the prize, you will need to maximize the number of primes you get.Can you win the prize? Hurry up, the bags are waiting!
|
The first line of the input contains a single integer \(n\) (\(1 \leq n \leq 200\,000\)) — the number of number tiles in the bag. The following line contains \(n\) space-separated integers \(a_1, a_2, \dots, a_n\) (\(a_i \in \{1, 2\}\)) — the values written on the tiles.
|
Output a permutation \(b_1, b_2, \dots, b_n\) of the input sequence \((a_1, a_2, \dots, a_n)\) maximizing the number of the prefix sums being prime numbers. If there are multiple optimal permutations, output any.
|
The first solution produces the prefix sums \(1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, \mathbf{\color{blue}{7}}\) (four primes constructed), while the prefix sums in the second solution are \(1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, 6, \mathbf{\color{blue}{7}}, 8, 10, \mathbf{\color{blue}{11}}\) (five primes). Primes are marked bold and blue. In each of these cases, the number of produced primes is maximum possible.
|
Input: 5 1 2 1 2 1 | Output: 1 1 1 2 2
|
Easy
| 4 | 609 | 271 | 212 | 11 |
1,342 |
B
|
1342B
|
B. Binary Period
| 1,100 |
constructive algorithms; strings
|
Let's say string \(s\) has period \(k\) if \(s_i = s_{i + k}\) for all \(i\) from \(1\) to \(|s| - k\) (\(|s|\) means length of string \(s\)) and \(k\) is the minimum positive integer with this property.Some examples of a period: for \(s\)=""0101"" the period is \(k=2\), for \(s\)=""0000"" the period is \(k=1\), for \(s\)=""010"" the period is \(k=2\), for \(s\)=""0011"" the period is \(k=4\).You are given string \(t\) consisting only of 0's and 1's and you need to find such string \(s\) that: String \(s\) consists only of 0's and 1's; The length of \(s\) doesn't exceed \(2 \cdot |t|\); String \(t\) is a subsequence of string \(s\); String \(s\) has smallest possible period among all strings that meet conditions 1—3. Let us recall that \(t\) is a subsequence of \(s\) if \(t\) can be derived from \(s\) by deleting zero or more elements (any) without changing the order of the remaining elements. For example, \(t\)=""011"" is a subsequence of \(s\)=""10101"".
|
The first line contains single integer \(T\) (\(1 \le T \le 100\)) — the number of test cases.Next \(T\) lines contain test cases — one per line. Each line contains string \(t\) (\(1 \le |t| \le 100\)) consisting only of 0's and 1's.
|
Print one string for each test case — string \(s\) you needed to find. If there are multiple solutions print any one of them.
|
In the first and second test cases, \(s = t\) since it's already one of the optimal solutions. Answers have periods equal to \(1\) and \(2\), respectively.In the third test case, there are shorter optimal solutions, but it's okay since we don't need to minimize the string \(s\). String \(s\) has period equal to \(1\).
|
Input: 4 00 01 111 110 | Output: 00 01 11111 1010
|
Easy
| 2 | 970 | 233 | 125 | 13 |
11 |
E
|
11E
|
E. Forward, march!
| 2,800 |
binary search; dp; greedy
|
Jack has become a soldier now. Unfortunately, he has trouble with the drill. Instead of marching beginning with the left foot and then changing legs with each step, as ordered, he keeps repeating a sequence of steps, in which he sometimes makes the wrong steps or — horror of horrors! — stops for a while. For example, if Jack uses the sequence 'right, left, break', when the sergeant yells: 'Left! Right! Left! Right! Left! Right!', Jack first makes a step with the right foot, then one with the left foot, then he is confused and stops for a moment, then again - this time according to the order - starts with the right foot, then uses the left foot, then - to the sergeant's irritation - he stops to catch his breath, to incorrectly start with the right foot again... Marching this way, Jack will make the step that he is supposed to in the given moment in only one third of cases.When the officers convinced him he should do something about it, Jack decided to modify the basic sequence of steps that he repeats. However, in order not to get too tired, he has decided that the only thing he'll do is adding any number of breaks in any positions of the original sequence (a break corresponds to stopping for the duration of one step). Of course, Jack can't make a step on the same foot twice in a row, if there is no pause between these steps. It is, however, not impossible that the sequence of steps he used so far is incorrect (it would explain a lot, actually).Help Private Jack! Given the sequence of steps he keeps repeating, calculate the maximal percentage of time that he can spend marching correctly after adding some breaks to his scheme.
|
The first line of input contains a sequence consisting only of characters 'L', 'R' and 'X', where 'L' corresponds to a step with the left foot, 'R' — with the right foot, and 'X' — to a break. The length of the sequence will not exceed 106.
|
Output the maximum percentage of time that Jack can spend marching correctly, rounded down to exactly six digits after the decimal point.
|
In the second example, if we add two breaks to receive LXXRXR, Jack will march: LXXRXRLXXRXRL... instead of LRLRLRLRLRLRL... and will make the correct step in half the cases. If we didn't add any breaks, the sequence would be incorrect — Jack can't step on his right foot twice in a row.
|
Input: X | Output: 0.000000
|
Master
| 3 | 1,652 | 240 | 137 | 0 |
1,669 |
D
|
1669D
|
D. Colorful Stamp
| 1,100 |
implementation
|
A row of \(n\) cells is given, all initially white. Using a stamp, you can stamp any two neighboring cells such that one becomes red and the other becomes blue. A stamp can be rotated, i.e. it can be used in both ways: as \(\color{blue}{\texttt{B}}\color{red}{\texttt{R}}\) and as \(\color{red}{\texttt{R}}\color{blue}{\texttt{B}}\).During use, the stamp must completely fit on the given \(n\) cells (it cannot be partially outside the cells). The stamp can be applied multiple times to the same cell. Each usage of the stamp recolors both cells that are under the stamp.For example, one possible sequence of stamps to make the picture \(\color{blue}{\texttt{B}}\color{red}{\texttt{R}}\color{blue}{\texttt{B}}\color{blue}{\texttt{B}}\texttt{W}\) could be \(\texttt{WWWWW} \to \texttt{WW}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\texttt{W} \to \color{brown}{\underline{\color{blue}{\texttt{B}}\color{red}{\texttt{R}}}}\color{red}{\texttt{R}}\color{blue}{\texttt{B}}\texttt{W} \to \color{blue}{\texttt{B}}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\color{blue}{\texttt{B}}\texttt{W}\). Here \(\texttt{W}\), \(\color{red}{\texttt{R}}\), and \(\color{blue}{\texttt{B}}\) represent a white, red, or blue cell, respectively, and the cells that the stamp is used on are marked with an underline.Given a final picture, is it possible to make it using the stamp zero or more times?
|
The first line contains an integer \(t\) (\(1 \leq t \leq 10^4\)) — the number of test cases.The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 10^5\)) — the length of the picture.The second line of each test case contains a string \(s\) — the picture you need to make. It is guaranteed that the length of \(s\) is \(n\) and that \(s\) only consists of the characters \(\texttt{W}\), \(\texttt{R}\), and \(\texttt{B}\), representing a white, red, or blue cell, respectively.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
|
Output \(t\) lines, each of which contains the answer to the corresponding test case. As an answer, output ""YES"" if it possible to make the picture using the stamp zero or more times, and ""NO"" otherwise.You can output the answer in any case (for example, the strings ""yEs"", ""yes"", ""Yes"" and ""YES"" will be recognized as a positive answer).
|
The first test case is explained in the statement.For the second, third, and fourth test cases, it is not possible to stamp a single cell, so the answer is ""NO"".For the fifth test case, you can use the stamp as follows: \(\texttt{WWW} \to \texttt{W}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}} \to \color{brown}{\underline{\color{blue}{\texttt{B}}\color{red}{\texttt{R}}}}\color{blue}{\texttt{B}}\).For the sixth test case, you can use the stamp as follows: \(\texttt{WWW} \to \texttt{W}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}} \to \color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\color{blue}{\texttt{B}}\).For the seventh test case, you don't need to use the stamp at all.
|
Input: 125BRBBW1B2WB2RW3BRB3RBB7WWWWWWW9RBWBWRRBW10BRBRBRBRRB12BBBRWWRRRWBR10BRBRBRBRBW5RBWBW | Output: YES NO NO NO YES YES YES NO YES NO YES NO
|
Easy
| 1 | 1,436 | 583 | 350 | 16 |
54 |
E
|
54E
|
E. Vacuum Сleaner
| 2,700 |
geometry
|
One winter evening the Hedgehog was relaxing at home in his cozy armchair and clicking through the TV channels. Stumbled on an issue of «TopShop», the Hedgehog was about to change the channel when all of a sudden he was stopped by an advertisement of a new wondrous invention.Actually, a vacuum cleaner was advertised there. It was called Marvellous Vacuum and it doesn't even need a human to operate it while it cleans! The vacuum cleaner can move around the flat on its own: it moves in some direction and if it hits an obstacle there, it automatically chooses a new direction. Sooner or later this vacuum cleaner will travel through all the room and clean it all. Having remembered how much time the Hedgehog spends every time on cleaning (surely, no less than a half of the day), he got eager to buy this wonder.However, the Hedgehog quickly understood that the cleaner has at least one weak point: it won't clean well in the room's corners because it often won't able to reach the corner due to its shape. To estimate how serious is this drawback in practice, the Hedgehog asked you to write for him the corresponding program.You will be given the cleaner's shape in the top view. We will consider only the cases when the vacuum cleaner is represented as a convex polygon. The room is some infinitely large rectangle. We consider one corner of this room and want to find such a rotation of the vacuum cleaner so that it, being pushed into this corner, will leave the minimum possible area in the corner uncovered.
|
The first line contains an integer N which represents the number of vertices of the vacuum cleaner's polygon (3 ≤ N ≤ 4·104). Then follow N lines each containing two numbers — the coordinates of a vertex of the polygon. All the coordinates are integer and their absolute values do not exceed 106.It is guaranteed that the given polygon is nondegenerate and convex (no three points lie on the same line). The polygon vertices are given in a clockwise or counter-clockwise direction.
|
Print the minimum possible uncovered area. The answer will be accepted if it is within 10 - 6 of absolute or relative error from the correct answer.
|
Input: 40 01 01 10 1 | Output: 0.00000000000000000000
|
Master
| 1 | 1,518 | 481 | 148 | 0 |
|
7 |
A
|
7A
|
A. Kalevitch and Chess
| 1,100 |
brute force; constructive algorithms
|
A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards.As before, the chessboard is a square-checkered board with the squares arranged in a 8 × 8 grid, each square is painted black or white. Kalevitch suggests that chessboards should be painted in the following manner: there should be chosen a horizontal or a vertical line of 8 squares (i.e. a row or a column), and painted black. Initially the whole chessboard is white, and it can be painted in the above described way one or more times. It is allowed to paint a square many times, but after the first time it does not change its colour any more and remains black. Kalevitch paints chessboards neatly, and it is impossible to judge by an individual square if it was painted with a vertical or a horizontal stroke.Kalevitch hopes that such chessboards will gain popularity, and he will be commissioned to paint chessboards, which will help him ensure a comfortable old age. The clients will inform him what chessboard they want to have, and the painter will paint a white chessboard meeting the client's requirements.It goes without saying that in such business one should economize on everything — for each commission he wants to know the minimum amount of strokes that he has to paint to fulfill the client's needs. You are asked to help Kalevitch with this task.
|
The input file contains 8 lines, each of the lines contains 8 characters. The given matrix describes the client's requirements, W character stands for a white square, and B character — for a square painted black.It is guaranteed that client's requirments can be fulfilled with a sequence of allowed strokes (vertical/column or horizontal/row).
|
Output the only number — the minimum amount of rows and columns that Kalevitch has to paint on the white chessboard to meet the client's requirements.
|
Input: WWWBWWBWBBBBBBBBWWWBWWBWWWWBWWBWWWWBWWBWWWWBWWBWWWWBWWBWWWWBWWBW | Output: 3
|
Easy
| 2 | 1,568 | 343 | 150 | 0 |
|
207 |
B2
|
207B2
|
B2. Military Trainings
| 1,900 |
The Smart Beaver from ABBYY started cooperating with the Ministry of Defence. Now they train soldiers to move armoured columns. The training involves testing a new type of tanks that can transmit information. To test the new type of tanks, the training has a special exercise, its essence is as follows.Initially, the column consists of n tanks sequentially numbered from 1 to n in the order of position in the column from its beginning to its end. During the whole exercise, exactly n messages must be transferred from the beginning of the column to its end.Transferring one message is as follows. The tank that goes first in the column transmits the message to some tank in the column. The tank which received the message sends it further down the column. The process is continued until the last tank receives the message. It is possible that not all tanks in the column will receive the message — it is important that the last tank in the column should receive the message.After the last tank (tank number n) receives the message, it moves to the beginning of the column and sends another message to the end of the column in the same manner. When the message reaches the last tank (tank number n - 1), that tank moves to the beginning of the column and sends the next message to the end of the column, and so on. Thus, the exercise is completed when the tanks in the column return to their original order, that is, immediately after tank number 1 moves to the beginning of the column.If the tanks were initially placed in the column in the order 1, 2, ..., n, then after the first message their order changes to n, 1, ..., n - 1, after the second message it changes to n - 1, n, 1, ..., n - 2, and so on.The tanks are constructed in a very peculiar way. The tank with number i is characterized by one integer ai, which is called the message receiving radius of this tank.Transferring a message between two tanks takes one second, however, not always one tank can transmit a message to another one. Let's consider two tanks in the column such that the first of them is the i-th in the column counting from the beginning, and the second one is the j-th in the column, and suppose the second tank has number x. Then the first tank can transmit a message to the second tank if i < j and i ≥ j - ax.The Ministry of Defense (and soon the Smart Beaver) faced the question of how to organize the training efficiently. The exercise should be finished as quickly as possible. We'll neglect the time that the tanks spend on moving along the column, since improving the tanks' speed is not a priority for this training.You are given the number of tanks, as well as the message receiving radii of all tanks. You must help the Smart Beaver and organize the transferring of messages in a way that makes the total transmission time of all messages as small as possible.
|
The first line contains integer n — the number of tanks in the column. Each of the next n lines contains one integer ai (1 ≤ ai ≤ 250000, 1 ≤ i ≤ n) — the message receiving radii of the tanks in the order from tank 1 to tank n (let us remind you that initially the tanks are located in the column in ascending order of their numbers).To get the full points for the first group of tests it is sufficient to solve the problem with 2 ≤ n ≤ 300.To get the full points for the second group of tests it is sufficient to solve the problem with 2 ≤ n ≤ 10000.To get the full points for the third group of tests it is sufficient to solve the problem with 2 ≤ n ≤ 250000.
|
Print a single integer — the minimum possible total time of transmitting the messages.Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
In the first sample the original order of tanks is 1, 2, 3. The first tank sends a message to the second one, then the second tank sends it to the third one — it takes two seconds. The third tank moves to the beginning of the column and the order of tanks now is 3, 1, 2. The third tank sends a message to the first one, then the first one sends it to the second one — it takes two more seconds. The second tank moves to the beginning and the order of the tanks is now 2, 3, 1. With this arrangement, the second tank can immediately send a message to the first one, since the message receiving radius of the first tank is large enough — it takes one second. Finally, the tanks return to their original order 1, 2, 3. In total, the exercise takes 5 seconds.In the second sample, all five tanks are the same and sending a single message takes two seconds, so in total the exercise takes 10 seconds.
|
Input: 3211 | Output: 5
|
Hard
| 0 | 2,856 | 661 | 233 | 2 |
|
1,534 |
H
|
1534H
|
H. Lost Nodes
| 3,500 |
constructive algorithms; dp; graphs; interactive; sortings; trees
|
This is an interactive problem.As he qualified for IOI this year, Little Ericyi was given a gift from all his friends: a tree of \(n\) nodes!On the flight to IOI Little Ericyi was very bored, so he decided to play a game with Little Yvonne with his new tree. First, Little Yvonne selects two (not necessarily different) nodes \(a\) and \(b\) on the tree (without telling Ericyi), and then gives him a hint \(f\) (which is some node on the path from \(a\) to \(b\)).Then, Little Ericyi is able to ask the following question repeatedly: If I rooted the tree at node \(r\) (Ericyi gets to choose \(r\)), what would be the Lowest Common Ancestor of \(a\) and \(b\)?Little Ericyi's goal is to find the nodes \(a\) and \(b\), and report them to Little Yvonne.However, Little Yvonne thought this game was too easy, so before he gives the hint \(f\) to Little Ericyi, he also wants him to first find the maximum number of queries required to determine \(a\) and \(b\) over all possibilities of \(a\), \(b\), and \(f\) assuming Little Ericyi plays optimally. Little Ericyi defines an optimal strategy as one that makes the minimum number of queries. Of course, once Little Ericyi replies with the maximum number of queries, Little Yvonne will only let him use that many queries in the game.The tree, \(a\), \(b\), and \(f\) are all fixed before the start of the game and do not change as queries are made.
|
Here is the the tree from the first sample interaction. Nodes \(a\) and \(b\) are highlighted. Notice that \(a\) and \(b\) can be output in any order.Additionally, here are the answers to querying every single node \(1,2,\ldots,n\) for your convenience: \(1\): \(1\) \(2\): \(2\) \(3\): \(2\) \(4\): \(4\)__________________________________________Here is the the tree from the second sample interaction. Again, nodes \(a\) and \(b\) are highlighted. Lastly, here are the answers to querying every single node \(1,2,\ldots,n\) (in example \(2\)) for your convenience: \(1\): \(1\) \(2\): \(4\) \(3\): \(1\) \(4\): \(4\) \(5\): \(4\)
|
Input: 4 3 2 2 1 2 4 1 1 2 2 | Output: 3 ? 1 ? 2 ? 3 ! 4 1
|
Master
| 6 | 1,396 | 0 | 0 | 15 |
||
1,672 |
H
|
1672H
|
H. Zigu Zagu
| 2,700 |
constructive algorithms; data structures; greedy
|
You have a binary string \(a\) of length \(n\) consisting only of digits \(0\) and \(1\). You are given \(q\) queries. In the \(i\)-th query, you are given two indices \(l\) and \(r\) such that \(1 \le l \le r \le n\). Let \(s=a[l,r]\). You are allowed to do the following operation on \(s\): Choose two indices \(x\) and \(y\) such that \(1 \le x \le y \le |s|\). Let \(t\) be the substring \(t = s[x, y]\). Then for all \(1 \le i \le |t| - 1\), the condition \(t_i \neq t_{i+1}\) has to hold. Note that \(x = y\) is always a valid substring. Delete the substring \(s[x, y]\) from \(s\). For each of the \(q\) queries, find the minimum number of operations needed to make \(s\) an empty string.Note that for a string \(s\), \(s[l,r]\) denotes the subsegment \(s_l,s_{l+1},\ldots,s_r\).
|
The first line contains two integers \(n\) and \(q\) (\(1 \le n, q \le 2 \cdot 10 ^ 5\)) — the length of the binary string \(a\) and the number of queries respectively.The second line contains a binary string \(a\) of length \(n\) (\(a_i \in \{0, 1\}\)).Each of the next \(q\) lines contains two integers \(l\) and \(r\) (\(1 \le l \le r \le n\)) — representing the substring of each query.
|
Print \(q\) lines, the \(i\)-th line representing the minimum number of operations needed for the \(i\)-th query.
|
In the first test case, The substring is \(\texttt{101}\), so we can do one operation to make the substring empty. The substring is \(\texttt{11011}\), so we can do one operation on \(s[2, 4]\) to make \(\texttt{11}\), then use two more operations to make the substring empty. The substring is \(\texttt{011}\), so we can do one operation on \(s[1, 2]\) to make \(\texttt{1}\), then use one more operation to make the substring empty.
|
Input: 5 3 11011 2 4 1 5 3 5 | Output: 1 3 2
|
Master
| 3 | 786 | 390 | 113 | 16 |
1,076 |
G
|
1076G
|
G. Array Game
| 3,000 |
data structures; games
|
Consider a following game between two players:There is an array \(b_1\), \(b_2\), ..., \(b_k\), consisting of positive integers. Initially a chip is placed into the first cell of the array, and \(b_1\) is decreased by \(1\). Players move in turns. Each turn the current player has to do the following: if the index of the cell where the chip is currently placed is \(x\), then he or she has to choose an index \(y \in [x, min(k, x + m)]\) such that \(b_y > 0\), move the chip to the cell \(y\) and decrease \(b_y\) by \(1\). If it's impossible to make a valid move, the current player loses the game.Your task is the following: you are given an array \(a\) consisting of \(n\) positive integers, and \(q\) queries to it. There are two types of queries: \(1\) \(l\) \(r\) \(d\) — for every \(i \in [l, r]\) increase \(a_i\) by \(d\); \(2\) \(l\) \(r\) — tell who is the winner of the game that is played on the subarray of \(a\) from index \(l\) to index \(r\) inclusive. Assume both players choose an optimal strategy.
|
The first line contains three integers \(n\), \(m\) and \(q\) (\(1 \le n, q \le 2 \cdot 10^5\), \(1 \le m \le 5\)) — the number of elements in \(a\), the parameter described in the game and the number of queries, respectively.The second line contains \(n\) integers \(a_1\), \(a_2\), ..., \(a_n\) (\(1 \le a_i \le 10^{12}\)) — the elements of array \(a\).Then \(q\) lines follow, each containing a query. There are two types of queries. The query of the first type is denoted by a line \(1\) \(l\) \(r\) \(d\) (\(1 \le l \le r \le n\), \(1 \le d \le 10^{12}\)) and means that for every \(i \in [l, r]\) you should increase \(a_i\) by \(d\). The query of the second type is denoted by a line \(2\) \(l\) \(r\) (\(1 \le l \le r \le n\)) and means that you have to determine who will win the game if it is played on the subarray of \(a\) from index \(l\) to index \(r\) (inclusive).There is at least one query of type \(2\).
|
For each query of type \(2\) print \(1\) if the first player wins in the corresponding game, or \(2\) if the second player wins.
|
Input: 5 2 4 1 2 3 4 5 1 3 5 6 2 2 5 1 1 2 3 2 1 5 | Output: 1 1
|
Master
| 2 | 1,018 | 921 | 128 | 10 |
|
1,044 |
A
|
1044A
|
A. The Tower is Going Home
| 1,700 |
binary search; two pointers
|
On a chessboard with a width of \(10^9\) and a height of \(10^9\), the rows are numbered from bottom to top from \(1\) to \(10^9\), and the columns are numbered from left to right from \(1\) to \(10^9\). Therefore, for each cell of the chessboard you can assign the coordinates \((x,y)\), where \(x\) is the column number and \(y\) is the row number.Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner — a cell with coordinates \((1,1)\). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely — on the upper side of the field (that is, in any cell that is in the row with number \(10^9\)).Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells: Vertical. Each of these is defined by one number \(x\). Such spells create an infinite blocking line between the columns \(x\) and \(x+1\). Horizontal. Each of these is defined by three numbers \(x_1\), \(x_2\), \(y\). Such spells create a blocking segment that passes through the top side of the cells, which are in the row \(y\) and in columns from \(x_1\) to \(x_2\) inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells. An example of a chessboard. Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell \((r_0,c_0)\) into the cell \((r_1,c_1)\) only under the condition that \(r_1 = r_0\) or \(c_1 = c_0\) and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
|
The first line contains two integers \(n\) and \(m\) (\(0 \le n,m \le 10^5\)) — the number of vertical and horizontal spells.Each of the following \(n\) lines contains one integer \(x\) (\(1 \le x < 10^9\)) — the description of the vertical spell. It will create a blocking line between the columns of \(x\) and \(x+1\).Each of the following \(m\) lines contains three integers \(x_1\), \(x_2\) and \(y\) (\(1 \le x_{1} \le x_{2} \le 10^9\), \(1 \le y < 10^9\)) — the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number \(y\), in columns from \(x_1\) to \(x_2\) inclusive.It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
|
In a single line print one integer — the minimum number of spells the rook needs to remove so it can get from the cell \((1,1)\) to at least one cell in the row with the number \(10^9\)
|
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell. Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home. In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell. Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home. In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them. Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home. In the fourth sample, we have no spells, which means that we do not need to remove anything.In the fifth example, we can remove the first vertical and third horizontal spells. Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
|
Input: 2 3681 5 61 9 42 4 2 | Output: 1
|
Medium
| 2 | 2,209 | 863 | 185 | 10 |
697 |
B
|
697B
|
B. Barnicle
| 1,400 |
brute force; implementation; math; strings
|
Barney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate. Barney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the distance value (it's a real number) on a napkin. The problem is that he wrote it in scientific notation. The scientific notation of some real number x is the notation of form AeB, where A is a real number and B is an integer and x = A × 10B is true. In our case A is between 0 and 9 and B is non-negative.Barney doesn't know anything about scientific notation (as well as anything scientific at all). So he asked you to tell him the distance value in usual decimal representation with minimal number of digits after the decimal point (and no decimal point if it is an integer). See the output format for better understanding.
|
The first and only line of input contains a single string of form a.deb where a, d and b are integers and e is usual character 'e' (0 ≤ a ≤ 9, 0 ≤ d < 10100, 0 ≤ b ≤ 100) — the scientific notation of the desired distance value.a and b contain no leading zeros and d contains no trailing zeros (but may be equal to 0). Also, b can not be non-zero if a is zero.
|
Print the only real number x (the desired distance value) in the only line in its decimal notation. Thus if x is an integer, print it's integer value without decimal part and decimal point and without leading zeroes. Otherwise print x in a form of p.q such that p is an integer that have no leading zeroes (but may be equal to zero), and q is an integer that have no trailing zeroes (and may not be equal to zero).
|
Input: 8.549e2 | Output: 854.9
|
Easy
| 4 | 935 | 359 | 414 | 6 |
|
354 |
D
|
354D
|
D. Transferring Pyramid
| 2,900 |
dp
|
Vasya and Petya are using an interesting data storing structure: a pyramid.The pyramid consists of n rows, the i-th row contains i cells. Each row is shifted half a cell to the left relative to the previous row. The cells are numbered by integers from 1 to as shown on the picture below.An example of a pyramid at n = 5 is: This data structure can perform operations of two types: Change the value of a specific cell. It is described by three integers: ""t i v"", where t = 1 (the type of operation), i — the number of the cell to change and v the value to assign to the cell. Change the value of some subpyramid. The picture shows a highlighted subpyramid with the top in cell 5. It is described by s + 2 numbers: ""t i v1 v2 ... vs"", where t = 2, i — the number of the top cell of the pyramid, s — the size of the subpyramid (the number of cells it has), vj — the value you should assign to the j-th cell of the subpyramid. Formally: a subpyramid with top at the i-th cell of the k-th row (the 5-th cell is the second cell of the third row) will contain cells from rows from k to n, the (k + p)-th row contains cells from the i-th to the (i + p)-th (0 ≤ p ≤ n - k).Vasya and Petya had two identical pyramids. Vasya changed some cells in his pyramid and he now wants to send his changes to Petya. For that, he wants to find a sequence of operations at which Petya can repeat all Vasya's changes. Among all possible sequences, Vasya has to pick the minimum one (the one that contains the fewest numbers).You have a pyramid of n rows with k changed cells. Find the sequence of operations which result in each of the k changed cells being changed by at least one operation. Among all the possible sequences pick the one that contains the fewest numbers.
|
The first line contains two integers n and k (1 ≤ n, k ≤ 105).The next k lines contain the coordinates of the modified cells ri and ci (1 ≤ ci ≤ ri ≤ n) — the row and the cell's number in the row. All cells are distinct.
|
Print a single number showing how many numbers the final sequence has.
|
One of the possible solutions of the first sample consists of two operations:2 4 v4 v7 v82 6 v6 v9 v10The picture shows the changed cells color-highlighted. The subpyramid used by the first operation is highlighted blue and the subpyramid used by the first operation is highlighted yellow:
|
Input: 4 53 13 34 14 34 4 | Output: 10
|
Master
| 1 | 1,752 | 220 | 70 | 3 |
2,041 |
K
|
2041K
|
K. Trophic Balance Species
| 3,100 |
binary search; brute force; dfs and similar; graphs
|
Image generated by ChatGPT 4o. In an interdisciplinary collaboration, an ecosystem scientist and a computer scientist join forces to analyze the structure of a complex ecosystem using computational methods. The ecosystem scientist models the ecosystem as a directed graph \(D = (V, A)\), where each species is represented by a node \(v \in V\), and each feeding relationship is represented as a directed edge \((x, y) \in A\) from prey \(x\) to predator \(y\). This graph structure allows them to simulate the flow of energy throughout the ecosystem from one species to another.Two essential features of the ecosystem are defined: Independent Trophic Group: A set \(S\) of animal species is classified as an independent trophic group if no species \(x \in S\) can reach another species \(y \in S\) (for some \(y \ne x\)) through a series of directed feeding relationships, meaning there is no directed path in \(D\) from \(x\) to \(y\). Trophic Balance Species: A species is termed a trophic balance species if it has a nearly equal number of species that affect it as directly or indirectly predators (species it can reach via a directed path in \(D\), excluding itself) and species that affect it as directly or indirectly prey (species that can reach it via a directed path in \(D\), excluding itself). Specifically, trophic balance species are those for which the absolute difference between the above two numbers is minimum among all species in the ecosystem. Consider an ecosystem with \(n = 4\) species and \(m = 3\) feeding relationships: Species 1: Grass (Node 1) Species 2: Rabbits (Node 2) Species 3: Foxes (Node 3) Species 4: Hawks (Node 4) The directed edges representing the feeding relationships are as follows: \((1, 2)\): Grass is eaten by Rabbits. \((2, 3)\): Rabbits are eaten by Foxes. \((2, 4)\): Rabbits are also eaten by Hawks. Now, consider the set \(S=\{3,4\}\) (Foxes and Hawks). There are no directed paths between Foxes (Node 3) and Hawks (Node 4); Foxes cannot reach Hawks, and Hawks cannot reach Foxes through any directed paths. Therefore, this set qualifies as an independent trophic group.Examination of Species Species 1 (Grass): Can reach: 3 (Rabbits, Foxes, and Hawks) Can be reached by: 0 (None) Absolute difference: \(|3 - 0| = 3\) Species 2 (Rabbits): Can reach: 2 (Foxes and Hawks) Can be reached by: 1 (Grass) Absolute difference: \(|2 - 1| = 1\) Species 3 (Foxes): Can reach: 0 (None) Can be reached by: 2 (Grass and Rabbits) Absolute difference: \(|0-2| = 2\) Species 4 (Hawks): Can reach: 0 (None) Can be reached by: 2 (Grass and Rabbits) Absolute difference: \(|0-2| = 2\) Among these species, Rabbits have the smallest absolute difference of \(1\), indicating that they are a trophic balance species within the ecosystem. It is known that any independent trophic group in the ecosystem has a size of at most \(k\). The task is to find the set of all trophic balance species in the ecosystem.
|
The first line contains exactly two integers \(n\) and \(m\), where \(n\) (resp. \(m\)) denotes the number of nodes (resp. edges) in the directed graph \(D\) induced by the investigated ecosystem. The nodes are numbered as \(1, 2, \ldots, n\). Then, \(m\) lines follow. The \(i\)-th line contains two integers \(x_i\) and \(y_i\) indicating a directed edge from node \(x_i\) to node \(y_i\). \(1 \le n \le 2 \times 10^5\) \(0 \le m \le \min\{ n(n-1), 4 \times 10^5\}\) \(k\) is not an input value, and it is guaranteed that \(1 \le k \le 16\) for each investigated ecosystem. For all \(i\) (\(1\le i\le m\)), \(1\le x_i, y_i\le n\) and \(x_i\neq y_i\). Each ordered pair \((x_i, y_i)\) appears at most once in the input.
|
Output on a single line the node identidiers of all trophic balance species in ascending order. For any two consecutive node identifiers, separate them by a space.
|
Input: 4 31 22 32 4 | Output: 2
|
Master
| 4 | 2,937 | 720 | 163 | 20 |
|
1,630 |
F
|
1630F
|
F. Making It Bipartite
| 3,400 |
flows; graph matchings; graphs; number theory
|
You are given an undirected graph of \(n\) vertices indexed from \(1\) to \(n\), where vertex \(i\) has a value \(a_i\) assigned to it and all values \(a_i\) are different. There is an edge between two vertices \(u\) and \(v\) if either \(a_u\) divides \(a_v\) or \(a_v\) divides \(a_u\).Find the minimum number of vertices to remove such that the remaining graph is bipartite, when you remove a vertex you remove all the edges incident to it.
|
The input consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 5\cdot10^4\)) — the number of vertices in the graph.The second line of each test case contains \(n\) integers, the \(i\)-th of them is the value \(a_i\) (\(1 \le a_i \le 5\cdot10^4\)) assigned to the \(i\)-th vertex, all values \(a_i\) are different.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5\cdot10^4\).
|
For each test case print a single integer — the minimum number of vertices to remove such that the remaining graph is bipartite.
|
In the first test case if we remove the vertices with values \(1\) and \(2\) we will obtain a bipartite graph, so the answer is \(2\), it is impossible to remove less than \(2\) vertices and still obtain a bipartite graph. BeforeAfter test case #1 In the second test case we do not have to remove any vertex because the graph is already bipartite, so the answer is \(0\). BeforeAfter test case #2 In the third test case we only have to remove the vertex with value \(12\), so the answer is \(1\). BeforeAfter test case #3 In the fourth test case we remove the vertices with values \(2\) and \(195\), so the answer is \(2\). BeforeAfter test case #4
|
Input: 448 4 2 1430 2 3 5512 4 6 2 31085 195 5 39 3 13 266 154 14 2 | Output: 2 0 1 2
|
Master
| 4 | 443 | 599 | 128 | 16 |
1,792 |
F2
|
1792F2
|
F2. Graph Coloring (hard version)
| 2,900 |
brute force; combinatorics; divide and conquer; dp; fft; graphs
|
The only difference between the easy and the hard version is the constraint on \(n\).You are given an undirected complete graph on \(n\) vertices. A complete graph is a graph where each pair of vertices is connected by an edge. You have to paint the edges of the graph into two colors, red and blue (each edge will have one color).A set of vertices \(S\) is red-connected if, for every pair of vertices \((v_1, v_2)\) such that \(v_1 \in S\) and \(v_2 \in S\), there exists a path from \(v_1\) to \(v_2\) that goes only through red edges and vertices from \(S\). Similarly, a set of vertices \(S\) is blue-connected if, for every pair of vertices \((v_1, v_2)\) such that \(v_1 \in S\) and \(v_2 \in S\), there exists a path from \(v_1\) to \(v_2\) that goes only through blue edges and vertices from \(S\).You have to paint the graph in such a way that: there is at least one red edge; there is at least one blue edge; for each set of vertices \(S\) such that \(|S| \ge 2\), \(S\) is either red-connected or blue-connected, but not both. Calculate the number of ways to paint the graph, and print it modulo \(998244353\).
|
The first (and only) line contains one integer \(n\) (\(3 \le n \le 5 \cdot 10^4\)).
|
Print one integer — the number of ways to paint the graph, taken modulo \(998244353\).
|
Input: 3 | Output: 6
|
Master
| 6 | 1,122 | 84 | 86 | 17 |
|
1,922 |
A
|
1922A
|
A. Tricky Template
| 800 |
constructive algorithms; implementation; strings
|
You are given an integer \(n\) and three strings \(a, b, c\), each consisting of \(n\) lowercase Latin letters.Let a template be a string \(t\) consisting of \(n\) lowercase and/or uppercase Latin letters. The string \(s\) matches the template \(t\) if the following conditions hold for all \(i\) from \(1\) to \(n\): if the \(i\)-th letter of the template is lowercase, then \(s_i\) must be the same as \(t_i\); if the \(i\)-th letter of the template is uppercase, then \(s_i\) must be different from the lowercase version of \(t_i\). For example, if there is a letter 'A' in the template, you cannot use the letter 'a' in the corresponding position of the string. Accordingly, the string doesn't match the template if the condition doesn't hold for at least one \(i\).Determine whether there exists a template \(t\) such that the strings \(a\) and \(b\) match it, while the string \(c\) does not.
|
The first line contains an integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases.The first line of each test case contains an integer \(n\) (\(1 \le n \le 20\)) — the length of the given strings.The next three lines contain the strings \(a, b\) and \(c\). Each string consists of exactly \(n\) lowercase Latin letters.
|
For each testcase, print ""YES"" if there exists a template \(t\) such that the strings \(a\) and \(b\) match it, while the string \(c\) does not. Otherwise, print ""NO"".
|
In the first test case, you can use the template ""C"". The first letter of strings \(a\) and \(b\) differ from 'c', so they match the template. The first letter of string \(c\) equals 'c', so it doesn't match.In the third test case, you can use the template ""CODEforces"".
|
Input: 41abc2aabbaa10mathforcesluckforcesadhoccoder3accabdabc | Output: YES NO YES NO
|
Beginner
| 3 | 898 | 328 | 171 | 19 |
886 |
E
|
886E
|
E. Maximum Element
| 2,400 |
combinatorics; dp; math
|
One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of n positive integers was too slow. Desperate, Petya decided to use a somewhat unexpected optimization using parameter k, so now his function contains the following code:int fast_max(int n, int a[]) { int ans = 0; int offset = 0; for (int i = 0; i < n; ++i) if (ans < a[i]) { ans = a[i]; offset = 0; } else { offset = offset + 1; if (offset == k) return ans; } return ans;}That way the function iteratively checks array elements, storing the intermediate maximum, and if after k consecutive iterations that maximum has not changed, it is returned as the answer.Now Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from 1 to n such that the return value of his function on those permutations is not equal to n. Since this number could be very big, output the answer modulo 109 + 7.
|
The only line contains two integers n and k (1 ≤ n, k ≤ 106), separated by a space — the length of the permutations and the parameter k.
|
Output the answer to the problem modulo 109 + 7.
|
Permutations from second example: [4, 1, 2, 3, 5], [4, 1, 3, 2, 5], [4, 2, 1, 3, 5], [4, 2, 3, 1, 5], [4, 3, 1, 2, 5], [4, 3, 2, 1, 5].
|
Input: 5 2 | Output: 22
|
Expert
| 3 | 1,123 | 136 | 48 | 8 |
1,620 |
G
|
1620G
|
G. Subsequences Galore
| 2,400 |
bitmasks; combinatorics; dp
|
For a sequence of strings \([t_1, t_2, \dots, t_m]\), let's define the function \(f([t_1, t_2, \dots, t_m])\) as the number of different strings (including the empty string) that are subsequences of at least one string \(t_i\). \(f([]) = 0\) (i. e. the number of such strings for an empty sequence is \(0\)).You are given a sequence of strings \([s_1, s_2, \dots, s_n]\). Every string in this sequence consists of lowercase Latin letters and is sorted (i. e., each string begins with several (maybe zero) characters a, then several (maybe zero) characters b, ..., ends with several (maybe zero) characters z).For each of \(2^n\) subsequences of \([s_1, s_2, \dots, s_n]\), calculate the value of the function \(f\) modulo \(998244353\).
|
The first line contains one integer \(n\) (\(1 \le n \le 23\)) — the number of strings.Then \(n\) lines follow. The \(i\)-th line contains the string \(s_i\) (\(1 \le |s_i| \le 2 \cdot 10^4\)), consisting of lowercase Latin letters. Each string \(s_i\) is sorted.
|
Since printing up to \(2^{23}\) integers would be really slow, you should do the following:For each of the \(2^n\) subsequences (which we denote as \([s_{i_1}, s_{i_2}, \dots, s_{i_k}]\)), calculate \(f([s_{i_1}, s_{i_2}, \dots, s_{i_k}])\), take it modulo \(998244353\), then multiply it by \(k \cdot (i_1 + i_2 + \dots + i_k)\). Print the XOR of all \(2^n\) integers you get.The indices \(i_1, i_2, \dots, i_k\) in the description of each subsequences are \(1\)-indexed (i. e. are from \(1\) to \(n\)).
|
Input: 3 a b c | Output: 92
|
Expert
| 3 | 736 | 263 | 504 | 16 |
|
2,090 |
C
|
2090C
|
C. Dining Hall
| 1,700 |
data structures; greedy; implementation; sortings
|
Inside the large kingdom, there is an infinite dining hall. It can be represented as a set of cells (\(x, y\)), where \(x\) and \(y\) are non-negative integers. There are an infinite number of tables in the hall. Each table occupies four cells (\(3x + 1, 3y + 1\)), (\(3x + 1, 3y + 2\)), (\(3x + 2, 3y + 1\)), (\(3x + 2, 3y + 2\)), where \(x\) and \(y\) are arbitrary non-negative integers. All cells that do not belong to any of the tables are corridors.There are \(n\) guests that come to the dining hall one by one. Each guest appears in the cell \((0, 0)\) and wants to reach a table cell. In one step, they can move to any neighboring by side corridor cell, and in their last step, they must move to a neighboring by side a free table cell. They occupy the chosen table cell, and no other guest can move there.Each guest has a characteristic \(t_i\), which can either be \(0\) or \(1\). They enter the hall in order, starting to walk from the cell (\(0, 0\)). If \(t_i=1\), the \(i\)-th guest walks to the nearest vacant table cell. If \(t_i=0\), they walk to the nearest table cell that belongs to a completely unoccupied table. Note that other guests may choose the same table later.The distance is defined as the smallest number of steps needed to reach the table cell. If there are multiple table cells at the same distance, the guests choose the cell with the smallest \(x\), and if there are still ties, they choose among those the cell with the smallest \(y\).For each guest, find the table cell which they choose.
|
The first line contains a single integer \(q\) (\(1 \leq q \leq 5000\)) — the number of test cases. Then follows their description.The first line of each test case contains a single integer \(n\) (\(1 \leq n \leq 50\,000\)) — the number of guests.The second line of each test case contains \(n\) integers \(t_1, t_2, \ldots, t_n\) (\(t_i \in \{0, 1\}\)) — the characteristics of the guests.It is guaranteed that the sum of \(n\) for all test cases does not exceed \(50\,000\).
|
For each test case, output \(n\) lines — for each guest, the cell where they sit.
|
Consider the first test case:The distance from the first guest to the cell (\(1, 1\)) is \(2\), so he sits there.The distance from the second guest to the cell (\(1, 2\)) is \(3\), as is the distance to the cell (\(2, 1\)), but since the first coordinate is smaller for the first option, he will choose it.The distance from the third guest to the cell (\(2, 1\)) is \(3\), so he will choose it.The distance from the fourth guest to the cell (\(1, 4\)) is \(5\), and he will choose it.The distance from the fifth guest to the cell (\(4, 1\)) is \(5\).The distance from the sixth guest to the cell (\(1, 5\)) is \(6\), as is the distance to the cell (\(2, 2\)), but since the first coordinate is smaller, he will choose the first option.
|
Input: 260 1 1 0 0 151 0 0 1 1 | Output: 1 1 1 2 2 1 1 4 4 1 1 5 1 1 1 4 4 1 1 2 2 1
|
Medium
| 4 | 1,526 | 476 | 81 | 20 |
1,822 |
G1
|
1822G1
|
G1. Magic Triples (Easy Version)
| 1,700 |
brute force; data structures; math; number theory
|
This is the easy version of the problem. The only difference is that in this version, \(a_i \le 10^6\).For a given sequence of \(n\) integers \(a\), a triple \((i, j, k)\) is called magic if: \(1 \le i, j, k \le n\). \(i\), \(j\), \(k\) are pairwise distinct. there exists a positive integer \(b\) such that \(a_i \cdot b = a_j\) and \(a_j \cdot b = a_k\). Kolya received a sequence of integers \(a\) as a gift and now wants to count the number of magic triples for it. Help him with this task!Note that there are no constraints on the order of integers \(i\), \(j\) and \(k\).
|
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. The description of the test cases follows.The first line of the test case contains a single integer \(n\) (\(3 \le n \le 2 \cdot 10^5\)) — the length of the sequence.The second line of the test contains \(n\) integers \(a_1, a_2, a_3, \dots, a_n\) (\(1 \le a_i \le 10^6\)) — the elements of the sequence \(a\).The sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, output a single integer — the number of magic triples for the sequence \(a\).
|
In the first example, there are \(6\) magic triples for the sequence \(a\) — \((2, 3, 5)\), \((2, 5, 3)\), \((3, 2, 5)\), \((3, 5, 2)\), \((5, 2, 3)\), \((5, 3, 2)\).In the second example, there is a single magic triple for the sequence \(a\) — \((2, 1, 3)\).
|
Input: 751 7 7 2 736 2 1891 2 3 4 5 6 7 8 941000 993 986 17971 10 100 1000 10000 100000 100000081 1 2 2 4 4 8 891 1 1 2 2 2 4 4 4 | Output: 6 1 3 0 9 16 45
|
Medium
| 4 | 577 | 478 | 97 | 18 |
1,913 |
F
|
1913F
|
F. Palindromic Problem
| 2,800 |
binary search; data structures; hashing; string suffix structures; strings
|
You are given a string \(s\) of length \(n\), consisting of lowercase Latin letters.You are allowed to replace at most one character in the string with an arbitrary lowercase Latin letter.Print the lexicographically minimal string that can be obtained from the original string and contains the maximum number of palindromes as substrings. Note that if a palindrome appears more than once as a substring, it is counted the same number of times it appears.The string \(a\) is lexicographically smaller than the string \(b\) if and only if one of the following holds: \(a\) is a prefix of \(b\), but \(a \ne b\); in the first position where \(a\) and \(b\) are different, the string \(a\) contains a letter that appears earlier in the alphabet than the corresponding letter in \(b\).
|
The first line contains one integer \(n\) (\(1 \leq n \leq 3 \cdot 10^5\)) — the number of characters in the string.The second line contains the string \(s\) itself, consisting of exactly \(n\) lowercase Latin letters.
|
In the first line, print one integer — the maximum number of palindromic substrings that can be obtained using the operation described in the statement at most once.In the second line, print the string that can be obtained from \(s\) and has the maximum possible number of palindromic substrings. If there are multiple answers, print the lexicographically smallest one.
|
Input: 5aabaa | Output: 15 aaaaa
|
Master
| 5 | 780 | 218 | 369 | 19 |
|
1,472 |
C
|
1472C
|
C. Long Jumps
| 1,100 |
dp; graphs
|
Polycarp found under the Christmas tree an array \(a\) of \(n\) elements and instructions for playing with it: At first, choose index \(i\) (\(1 \leq i \leq n\)) — starting position in the array. Put the chip at the index \(i\) (on the value \(a_i\)). While \(i \leq n\), add \(a_i\) to your score and move the chip \(a_i\) positions to the right (i.e. replace \(i\) with \(i + a_i\)). If \(i > n\), then Polycarp ends the game. For example, if \(n = 5\) and \(a = [7, 3, 1, 2, 3]\), then the following game options are possible: Polycarp chooses \(i = 1\). Game process: \(i = 1 \overset{+7}{\longrightarrow} 8\). The score of the game is: \(a_1 = 7\). Polycarp chooses \(i = 2\). Game process: \(i = 2 \overset{+3}{\longrightarrow} 5 \overset{+3}{\longrightarrow} 8\). The score of the game is: \(a_2 + a_5 = 6\). Polycarp chooses \(i = 3\). Game process: \(i = 3 \overset{+1}{\longrightarrow} 4 \overset{+2}{\longrightarrow} 6\). The score of the game is: \(a_3 + a_4 = 3\). Polycarp chooses \(i = 4\). Game process: \(i = 4 \overset{+2}{\longrightarrow} 6\). The score of the game is: \(a_4 = 2\). Polycarp chooses \(i = 5\). Game process: \(i = 5 \overset{+3}{\longrightarrow} 8\). The score of the game is: \(a_5 = 3\). Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.
|
The first line contains one integer \(t\) (\(1 \leq t \leq 10^4\)) — the number of test cases. Then \(t\) test cases follow.The first line of each test case contains one integer \(n\) (\(1 \leq n \leq 2 \cdot 10^5\)) — the length of the array \(a\).The next line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \leq a_i \leq 10^9\)) — elements of the array \(a\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, output on a separate line one number — the maximum score that Polycarp can get by playing the game on the corresponding array according to the instruction from the statement. Note that Polycarp chooses any starting position from \(1\) to \(n\) in such a way as to maximize his result.
|
The first test case is explained in the statement.In the second test case, the maximum score can be achieved by choosing \(i = 1\).In the third test case, the maximum score can be achieved by choosing \(i = 2\).In the fourth test case, the maximum score can be achieved by choosing \(i = 1\).
|
Input: 4 5 7 3 1 2 3 3 2 1 4 6 2 1000 2 3 995 1 5 1 1 1 1 1 | Output: 7 6 1000 5
|
Easy
| 2 | 1,332 | 461 | 304 | 14 |
1,090 |
E
|
1090E
| 2,300 |
flows; graphs
|
Expert
| 2 | 0 | 0 | 0 | 10 |
||||||
331 |
D1
|
331D1
|
D1. Escaping on Beaveractor
| 2,400 |
dfs and similar; implementation
|
Don't put up with what you're sick of! The Smart Beaver decided to escape from the campus of Beaver Science Academy (BSA). BSA is a b × b square on a plane. Each point x, y (0 ≤ x, y ≤ b) belongs to BSA. To make the path quick and funny, the Beaver constructed a Beaveractor, an effective and comfortable types of transport.The campus obeys traffic rules: there are n arrows, parallel to the coordinate axes. The arrows do not intersect and do not touch each other. When the Beaveractor reaches some arrow, it turns in the arrow's direction and moves on until it either reaches the next arrow or gets outside the campus. The Beaveractor covers exactly one unit of space per one unit of time. You can assume that there are no obstacles to the Beaveractor.The BSA scientists want to transport the brand new Beaveractor to the ""Academic Tractor"" research institute and send the Smart Beaver to do his postgraduate studies and sharpen pencils. They have q plans, representing the Beaveractor's initial position (xi, yi), the initial motion vector wi and the time ti that have passed after the escape started.Your task is for each of the q plans to determine the Smart Beaver's position after the given time.
|
The first line contains two integers: the number of traffic rules n and the size of the campus b, 0 ≤ n, 1 ≤ b. Next n lines contain the rules. Each line of the rules contains four space-separated integers x0, y0, x1, y1 — the beginning and the end of the arrow. It is guaranteed that all arrows are parallel to the coordinate axes and have no common points. All arrows are located inside the campus, that is, 0 ≤ x0, y0, x1, y1 ≤ b holds.Next line contains integer q — the number of plans the scientists have, 1 ≤ q ≤ 105. The i-th plan is represented by two integers, xi, yi are the Beaveractor's coordinates at the initial time, 0 ≤ xi, yi ≤ b, character wi, that takes value U, D, L, R and sets the initial direction up, down, to the left or to the right correspondingly (the Y axis is directed upwards), and ti — the time passed after the escape started, 0 ≤ ti ≤ 1015. to get 30 points you need to solve the problem with constraints n, b ≤ 30 (subproblem D1); to get 60 points you need to solve the problem with constraints n, b ≤ 1000 (subproblems D1+D2); to get 100 points you need to solve the problem with constraints n, b ≤ 105 (subproblems D1+D2+D3).
|
Print q lines. Each line should contain two integers — the Beaveractor's coordinates at the final moment of time for each plan. If the Smart Beaver manages to leave the campus in time ti, print the coordinates of the last point in the campus he visited.
|
Input: 3 30 0 0 10 2 2 23 3 2 3120 0 L 00 0 L 10 0 L 20 0 L 30 0 L 40 0 L 50 0 L 62 0 U 22 0 U 33 0 U 51 3 D 21 3 R 2 | Output: 0 00 10 21 22 23 23 22 23 21 32 21 3
|
Expert
| 2 | 1,205 | 1,162 | 253 | 3 |
|
1,043 |
E
|
1043E
|
E. Train Hard, Win Easy
| 1,900 |
constructive algorithms; greedy; math; sortings
|
Zibi is a competitive programming coach. There are \(n\) competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.Rules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the less the score is, the better).We know that the \(i\)-th competitor will always have score \(x_i\) when he codes the first task and \(y_i\) when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest.Zibi wants all competitors to write a contest with each other. However, there are \(m\) pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in?
|
The first line contains two integers \(n\) and \(m\) (\(2 \le n \le 300\,000\), \(0 \le m \le 300\,000\)) — the number of participants and the number of pairs of people who will not write a contest together.Each of the next \(n\) lines contains two integers \(x_i\) and \(y_i\) (\(-10^9 \le x_i, y_i \le 10^9\)) — the scores which will the \(i\)-th competitor get on the first problem and on the second problem. It is guaranteed that there are no two people having both \(x_i\) and \(y_i\) same.Each of the next \(m\) lines contain two integers \(u_i\) and \(v_i\) (\(1 \le u_i, v_i \le n\), \(u_i \ne v_i\)) — indices of people who don't want to write a contest in one team. Each unordered pair of indices will appear at most once.
|
Output \(n\) integers — the sum of scores for all participants in the same order as they appear in the input.
|
In the first example, there will be only one team consisting of persons \(1\) and \(3\). The optimal strategy for them is to assign the first task to the \(3\)-rd person and the second task to the \(1\)-st person, this will lead to score equal to \(1 + 2 = 3\).In the second example, nobody likes anyone, so there won't be any trainings. It seems that Zibi won't be titled coach in that case...
|
Input: 3 21 22 31 31 22 3 | Output: 3 0 3
|
Hard
| 4 | 1,608 | 732 | 109 | 10 |
698 |
F
|
698F
|
F. Coprime Permutation
| 3,000 |
combinatorics; number theory
|
Two positive integers are coprime if and only if they don't have a common divisor greater than 1.Some bear doesn't want to tell Radewoosh how to solve some algorithmic problem. So, Radewoosh is going to break into that bear's safe with solutions. To pass through the door, he must enter a permutation of numbers 1 through n. The door opens if and only if an entered permutation p1, p2, ..., pn satisfies:In other words, two different elements are coprime if and only if their indices are coprime. Some elements of a permutation may be already fixed. In how many ways can Radewoosh fill the remaining gaps so that the door will open? Print the answer modulo 109 + 7.
|
The first line of the input contains one integer n (2 ≤ n ≤ 1 000 000).The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ n) where pi = 0 means a gap to fill, and pi ≥ 1 means a fixed number.It's guaranteed that if i ≠ j and pi, pj ≥ 1 then pi ≠ pj.
|
Print the number of ways to fill the gaps modulo 109 + 7 (i.e. modulo 1000000007).
|
In the first sample test, none of four element is fixed. There are four permutations satisfying the given conditions: (1,2,3,4), (1,4,3,2), (3,2,1,4), (3,4,1,2).In the second sample test, there must be p3 = 1 and p4 = 2. The two permutations satisfying the conditions are: (3,4,1,2,5), (5,4,1,2,3).
|
Input: 40 0 0 0 | Output: 4
|
Master
| 2 | 665 | 260 | 82 | 6 |
1,991 |
C
|
1991C
|
C. Absolute Zero
| 1,300 |
constructive algorithms; greedy; math
|
You are given an array \(a\) of \(n\) integers.In one operation, you will perform the following two-step move: Choose an integer \(x\) (\(0 \le x \le 10^{9}\)). Replace each \(a_i\) with \(|a_i - x|\), where \(|v|\) denotes the absolute value of \(v\). For example, by choosing \(x = 8\), the array \([5, 7, 10]\) will be changed into \([|5-8|, |7-8|, |10-8|] = [3,1,2]\).Construct a sequence of operations to make all elements of \(a\) equal to \(0\) in at most \(40\) operations or determine that it is impossible. You do not need to minimize the number of operations.
|
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) — the length of the array \(a\).The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le 10^9\)) — the elements of the array \(a\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, output a single integer \(-1\) if it is impossible to make all array elements equal to \(0\) in at most \(40\) operations.Otherwise, output two lines. The first line of output should contain a single integer \(k\) (\(0 \le k \le 40\)) — the number of operations. The second line of output should contain \(k\) integers \(x_1, x_2, \ldots, x_k\) (\(0 \le x_i \le 10^{9}\)) — the sequence of operations, denoting that on the \(i\)-th operation, you chose \(x=x_i\).If there are multiple solutions, output any of them.You do not need to minimize the number of operations.
|
In the first test case, we can perform only one operation by choosing \(x = 5\), changing the array from \([5]\) to \([0]\).In the second test case, no operations are needed because all elements of the array are already \(0\).In the third test case, we can choose \(x = 6\) to change the array from \([4, 6, 8]\) to \([2, 0, 2]\), then choose \(x = 1\) to change it to \([1, 1, 1]\), and finally choose \(x = 1\) again to change the array into \([0, 0, 0]\).In the fourth test case, we can make all elements \(0\) by following the operation sequence \((60, 40, 20, 10, 30, 25, 5)\).In the fifth test case, it can be shown that it is impossible to make all elements \(0\) in at most \(40\) operations. Therefore, the output is \(-1\).
|
Input: 51520 034 6 8480 40 20 1051 2 3 4 5 | Output: 1 5 0 3 6 1 1 7 60 40 20 10 30 25 5 -1
|
Easy
| 3 | 570 | 539 | 588 | 19 |
1,322 |
E
|
1322E
|
E. Median Mountain Range
| 3,300 |
data structures
|
Berland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the ""Median mountain range"". This mountain range is \(n\) mountain peaks, located on one straight line and numbered in order of \(1\) to \(n\). The height of the \(i\)-th mountain top is \(a_i\). ""Median mountain range"" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from \(2\) to \(n - 1\) its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal \(b_i\), then after the alignment new heights \(a_i\) are as follows: \(a_1 = b_1\), \(a_n = b_n\) and for all \(i\) from \(2\) to \(n - 1\) \(a_i = \texttt{median}(b_{i-1}, b_i, b_{i+1})\). The median of three integers is the second largest number among them. For example, \(\texttt{median}(5,1,2) = 2\), and \(\texttt{median}(4,2,4) = 4\).Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of \(c\) — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after \(c\) alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!
|
The first line contains integers \(n\) (\(1 \le n \le 500\,000\)) — the number of mountains.The second line contains integers \(a_1, a_2, a_3, \ldots, a_n\) (\(1 \le a_i \le 10^9\)) — current heights of the mountains.
|
In the first line print \(c\) — the number of alignments, which change the height of at least one mountain.In the second line print \(n\) integers — the final heights of the mountains after \(c\) alignments.
|
In the first example, the heights of the mountains at index \(1\) and \(5\) never change. Since the median of \(1\), \(2\), \(1\) is \(1\), the second and the fourth mountains will have height 1 after the first alignment, and since the median of \(2\), \(1\), \(2\) is \(2\), the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are \(1\), \(1\), \(2\), \(1\), \(1\). After the second alignment the heights change into \(1\), \(1\), \(1\), \(1\), \(1\) and never change from now on, so there are only \(2\) alignments changing the mountain heights.In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is \(0\).
|
Input: 5 1 2 1 2 1 | Output: 2 1 1 1 1 1
|
Master
| 1 | 1,632 | 217 | 207 | 13 |
56 |
A
|
56A
|
A. Bar
| 1,000 |
implementation
|
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks?The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
|
The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators.Only the drinks from the list given above should be considered alcohol.
|
Print a single number which is the number of people Vasya should check to guarantee the law enforcement.
|
In the sample test the second and fifth clients should be checked.
|
Input: 518VODKACOKE1917 | Output: 2
|
Beginner
| 1 | 653 | 441 | 104 | 0 |
1,789 |
C
|
1789C
|
C. Serval and Toxel's Arrays
| 1,500 |
combinatorics; dp; implementation; math
|
Toxel likes arrays. Before traveling to the Paldea region, Serval gave him an array \(a\) as a gift. This array has \(n\) pairwise distinct elements.In order to get more arrays, Toxel performed \(m\) operations with the initial array. In the \(i\)-th operation, he modified the \(p_{i}\)-th element of the \((i-1)\)-th array to \(v_{i}\), resulting in the \(i\)-th array (the initial array \(a\) is numbered as \(0\)). During modifications, Toxel guaranteed that the elements of each array are still pairwise distinct after each operation.Finally, Toxel got \(m+1\) arrays and denoted them as \(A_{0}=a, A_{1},\ldots,A_{m}\). For each pair \((i,j)\) (\(0\le i<j\le m\)), Toxel defines its value as the number of distinct elements of the concatenation of \(A_{i}\) and \(A_{j}\). Now Toxel wonders, what is the sum of the values of all pairs? Please help him to calculate the answer.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1\le t\le10^{4}\)). The description of the test cases follows.The first line of each test case contains two integers \(n\) and \(m\) (\(1\le n,m\le2\cdot10^{5}\)) — the length of the array and the number of operations.The second line of each test case contains \(n\) integers \(a_{1},a_{2},\dots,a_{n}\) (\(1\le a_{i}\le n+m\)). It is guaranteed that all \(a_i\) are pairwise distinct.Each of the next \(m\) lines of each test case contains two integers \(p_{i}\) and \(v_{i}\) (\(1\le p_{i}\le n\), \(1\le v_{i}\le n+m\)) — the position of the modified element and its new value. It is guaranteed that the elements of each array are still pairwise distinct after each modification.It is guaranteed that the sum of \(n\) and the sum of \(m\) over all test cases do not exceed \(2\cdot10^{5}\).
|
For each test case, print a single integer — the sum of the values of all pairs of arrays.
|
In the first test case, the arrays change as follows: \([1,2,3]\to[\underline{4},2,3]\to[4,\underline{5},3]\).The concatenation of the \(0\)-th array and the \(1\)-st array is \(\require{cancel}[1,2,3,4,\cancel{2},\cancel{3}]\). There are \(4\) distinct elements.The concatenation of the \(0\)-th array and the \(2\)-nd array is \(\require{cancel}[1,2,3,4,5,\cancel{3}]\). There are \(5\) distinct elements.The concatenation of the \(1\)-st array and the \(2\)-nd array is \(\require{cancel}[4,2,3,\cancel{4},5,\cancel{3}]\). There are \(4\) distinct elements.Strikethrough elements are duplicates in the array.Therefore, the answer is \(4+5+4=13\).In the second test case, note that the array may remain unchanged after operations.
|
Input: 33 21 2 31 42 51 111 110 104 6 9 12 16 20 2 10 19 71 35 42 172 186 117 18 175 55 52 2 | Output: 13 1 705
|
Medium
| 4 | 882 | 891 | 90 | 17 |
314 |
D
|
314D
|
D. Sereja and Straight Lines
| 2,500 |
binary search; data structures; geometry; sortings; two pointers
|
Sereja placed n points on a plane. Now Sereja wants to place on the plane two straight lines, intersecting at a right angle, so that one of the straight lines intersect the Ox axis at an angle of 45 degrees and the maximum distance from the points to the straight lines were minimum. In this problem we consider the distance between points (x1, y1) and (x2, y2) equal |x1 - x2| + |y1 - y2|. The distance between the point and the straight lines is the minimum distance from the point to some point belonging to one of the lines.Help Sereja, find the maximum distance from the points to the optimally located straight lines.
|
The first line contains integer n (1 ≤ n ≤ 105). Next n lines contain the coordinates of the lines. The i-th line contains two integers xi, yi (|xi|, |yi| ≤ 109).
|
In a single line print a real number — the answer to the problem. Your answer will be considered correct iff its absolute or relative error doesn't exceed 10 - 6.
|
Input: 40 02 00 22 2 | Output: 0.000000000000000
|
Expert
| 5 | 623 | 162 | 162 | 3 |
|
1,988 |
F
|
1988F
|
F. Heartbeat
| 3,000 |
combinatorics; dp; fft; math
|
For an array \(u_1, u_2, \ldots, u_n\), define a prefix maximum as an index \(i\) such that \(u_i>u_j\) for all \(j<i\); a suffix maximum as an index \(i\) such that \(u_i>u_j\) for all \(j>i\); an ascent as an index \(i\) (\(i>1\)) such that \(u_i>u_{i-1}\). You are given three cost arrays: \([a_1, a_2, \ldots, a_n]\), \([b_1, b_2, \ldots, b_n]\), and \([c_0, c_1, \ldots, c_{n-1}]\).Define the cost of an array that has \(x\) prefix maximums, \(y\) suffix maximums, and \(z\) ascents as \(a_x\cdot b_y\cdot c_z\).Let the sum of costs of all permutations of \(1,2,\ldots,n\) be \(f(n)\). Find \(f(1)\), \(f(2)\), ..., \(f(n)\) modulo \(998\,244\,353\).
|
The first line contains an integer \(n\) (\(1\le n\le 700\)).The second line contains \(n\) integers \(a_1,\ldots,a_n\) (\(0\le a_i<998\,244\,353\)).The third line contains \(n\) integers \(b_1,\ldots,b_n\) (\(0\le b_i<998\,244\,353\)).The fourth line contains \(n\) integers \(c_0,\ldots,c_{n-1}\) (\(0\le c_i<998\,244\,353\)).
|
Print \(n\) integers: the \(i\)-th one is \(f(i)\) modulo \(998\,244\,353\).
|
In the second example: Consider permutation \([1,2,3]\). Indices \(1,2,3\) are prefix maximums. Index \(3\) is the only suffix maximum. Indices \(2,3\) are ascents. In conclusion, it has \(3\) prefix maximums, \(1\) suffix maximums, and \(2\) ascents. Therefore, its cost is \(a_3b_1c_2=12\). Permutation \([1,3,2]\) has \(2\) prefix maximums, \(2\) suffix maximums, and \(1\) ascent. Its cost is \(6\). Permutation \([2,1,3]\) has \(2\) prefix maximums, \(1\) suffix maximum, and \(1\) ascent. Its cost is \(4\). Permutation \([2,3,1]\) has \(2\) prefix maximums, \(2\) suffix maximums, and \(1\) ascent. Its cost is \(6\). Permutation \([3,1,2]\) has \(1\) prefix maximum, \(2\) suffix maximums, and \(1\) ascent. Its cost is \(3\). Permutation \([3,2,1]\) has \(1\) prefix maximum, \(3\) suffix maximums, and \(0\) ascents. Its cost is \(3\). The sum of all permutations' costs is \(34\), so \(f(3)=34\).
|
Input: 31 1 11 1 11 1 1 | Output: 1 2 6
|
Master
| 4 | 655 | 328 | 76 | 19 |
1,765 |
L
|
1765L
|
L. Project Manager
| 2,400 |
brute force; data structures; implementation
|
There are \(n\) employees at Bersoft company, numbered from \(1\) to \(n\). Each employee works on some days of the week and rests on the other days. You are given the lists of working days of the week for each employee.There are regular days and holidays. On regular days, only those employees work that have the current day of the week on their list. On holidays, no one works. You are provided with a list of days that are holidays. The days are numbered from \(1\) onwards, day \(1\) is Monday.The company receives \(k\) project offers they have to complete. The projects are numbered from \(1\) to \(k\) in the order of decreasing priority. Each project consists of multiple parts, where the \(i\)-th part must be completed by the \(a_i\)-th employee. The parts must be completed in order (i. e. the \((i+1)\)-st part can only be started when the \(i\)-th part is completed). Each part takes the corresponding employee a day to complete.The projects can be worked on simultaneously. However, one employee can complete a part of only one project during a single day. If they have a choice of what project to complete a part on, they always go for the project with the highest priority (the lowest index).For each project, output the day that project will be completed on.
|
The first line contains three integers \(n, m\) and \(k\) (\(1 \le n, m, k \le 2 \cdot 10^5\)) — the number of employees, the number of holidays and the number of projects.The \(i\)-th of the next \(n\) lines contains the list of working days of the \(i\)-th employee. First, a single integer \(t\) (\(1 \le t \le 7\)) — the number of working days. Then \(t\) days of the week in the increasing order. The possible days are: ""Monday"", ""Tuesday"", ""Wednesday"", ""Thursday"", ""Friday"", ""Saturday"", ""Sunday"".The next line contains \(m\) integers \(h_1, h_2, \dots, h_m\) (\(1 \le h_1 < h_2 < \dots < h_m \le 10^9\)) — the list of holidays.The \(j\)-th of the next \(k\) lines contains a description of the \(j\)-th project. It starts with an integer \(p\) (\(1 \le p \le 2 \cdot 10^5\)) — the number of parts in the project. Then \(p\) integers \(a_1, a_2, \dots, a_p\) (\(1 \le a_x \le n\)) follow, where \(p_i\) is the index of the employee that must complete the \(i\)-th part.The total number of parts in all projects doesn't exceed \(2 \cdot 10^5\).
|
Print \(k\) integers — the \(j\)-th value should be equal to the day the \(j\)-th project is completed on.
|
Input: 3 5 4 2 Saturday Sunday 2 Tuesday Thursday 4 Monday Wednesday Friday Saturday 4 7 13 14 15 5 1 1 3 3 2 3 2 3 2 5 3 3 3 1 1 8 3 3 3 3 3 3 3 3 | Output: 25 9 27 27
|
Expert
| 3 | 1,275 | 1,062 | 106 | 17 |
|
383 |
B
|
383B
|
B. Volcanoes
| 2,500 |
binary search; implementation; sortings; two pointers
|
Iahub got lost in a very big desert. The desert can be represented as a n × n square matrix, where each cell is a zone of the desert. The cell (i, j) represents the cell at row i and column j (1 ≤ i, j ≤ n). Iahub can go from one cell (i, j) only down or right, that is to cells (i + 1, j) or (i, j + 1). Also, there are m cells that are occupied by volcanoes, which Iahub cannot enter. Iahub is initially at cell (1, 1) and he needs to travel to cell (n, n). Knowing that Iahub needs 1 second to travel from one cell to another, find the minimum time in which he can arrive in cell (n, n).
|
The first line contains two integers n (1 ≤ n ≤ 109) and m (1 ≤ m ≤ 105). Each of the next m lines contains a pair of integers, x and y (1 ≤ x, y ≤ n), representing the coordinates of the volcanoes.Consider matrix rows are numbered from 1 to n from top to bottom, and matrix columns are numbered from 1 to n from left to right. There is no volcano in cell (1, 1). No two volcanoes occupy the same location.
|
Print one integer, the minimum time in which Iahub can arrive at cell (n, n). If no solution exists (there is no path to the final cell), print -1.
|
Consider the first sample. A possible road is: (1, 1) → (1, 2) → (2, 2) → (2, 3) → (3, 3) → (3, 4) → (4, 4).
|
Input: 4 21 31 4 | Output: 6
|
Expert
| 4 | 590 | 406 | 147 | 3 |
20 |
B
|
20B
|
B. Equation
| 2,000 |
math
|
You are given an equation: Ax2 + Bx + C = 0. Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
|
The first line contains three integer numbers A, B and C ( - 105 ≤ A, B, C ≤ 105). Any coefficient may be equal to 0.
|
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
|
Input: 1 -5 6 | Output: 22.00000000003.0000000000
|
Hard
| 1 | 152 | 117 | 282 | 0 |
|
1,841 |
B
|
1841B
|
B. Keep it Beautiful
| 1,000 |
implementation
|
The array \([a_1, a_2, \dots, a_k]\) is called beautiful if it is possible to remove several (maybe zero) elements from the beginning of the array and insert all these elements to the back of the array in the same order in such a way that the resulting array is sorted in non-descending order.In other words, the array \([a_1, a_2, \dots, a_k]\) is beautiful if there exists an integer \(i \in [0, k-1]\) such that the array \([a_{i+1}, a_{i+2}, \dots, a_{k-1}, a_k, a_1, a_2, \dots, a_i]\) is sorted in non-descending order.For example: \([3, 7, 7, 9, 2, 3]\) is beautiful: we can remove four first elements and insert them to the back in the same order, and we get the array \([2, 3, 3, 7, 7, 9]\), which is sorted in non-descending order; \([1, 2, 3, 4, 5]\) is beautiful: we can remove zero first elements and insert them to the back, and we get the array \([1, 2, 3, 4, 5]\), which is sorted in non-descending order; \([5, 2, 2, 1]\) is not beautiful. Note that any array consisting of zero elements or one element is beautiful.You are given an array \(a\), which is initially empty. You have to process \(q\) queries to it. During the \(i\)-th query, you will be given one integer \(x_i\), and you have to do the following: if you can append the integer \(x_i\) to the back of the array \(a\) so that the array \(a\) stays beautiful, you have to append it; otherwise, do nothing. After each query, report whether you appended the given integer \(x_i\), or not.
|
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.Each test case consists of two lines. The first line contains one integer \(q\) (\(1 \le q \le 2 \cdot 10^5\)) — the number of queries. The second line contains \(q\) integers \(x_1, x_2, \dots, x_q\) (\(0 \le x_i \le 10^9\)).Additional constraint on the input: the sum of \(q\) over all test cases does not exceed \(2 \cdot 10^5\)).
|
For each test case, print one string consisting of exactly \(q\) characters. The \(i\)-th character of the string should be 1 if you appended the integer during the \(i\)-th query; otherwise, it should be 0.
|
Consider the first test case of the example. Initially, the array is \([]\). trying to append an integer \(3\). The array \([3]\) is beautiful, so we append \(3\); trying to append an integer \(7\). The array \([3, 7]\) is beautiful, so we append \(7\); trying to append an integer \(7\). The array \([3, 7, 7]\) is beautiful, so we append \(7\); trying to append an integer \(9\). The array \([3, 7, 7, 9]\) is beautiful, so we append \(9\); trying to append an integer \(2\). The array \([3, 7, 7, 9, 2]\) is beautiful, so we append \(2\); trying to append an integer \(4\). The array \([3, 7, 7, 9, 2, 4]\) is not beautiful, so we don't append \(4\); trying to append an integer \(6\). The array \([3, 7, 7, 9, 2, 6]\) is not beautiful, so we don't append \(6\); trying to append an integer \(3\). The array \([3, 7, 7, 9, 2, 3]\) is beautiful, so we append \(3\); trying to append an integer \(4\). The array \([3, 7, 7, 9, 2, 3, 4]\) is not beautiful, so we don't append \(4\).
|
Input: 393 7 7 9 2 4 6 3 451 1 1 1 153 2 1 2 3 | Output: 111110010 11111 11011
|
Beginner
| 1 | 1,466 | 425 | 207 | 18 |
1,515 |
D
|
1515D
|
D. Phoenix and Socks
| 1,500 |
greedy; sortings; two pointers
|
To satisfy his love of matching socks, Phoenix has brought his \(n\) socks (\(n\) is even) to the sock store. Each of his socks has a color \(c_i\) and is either a left sock or right sock. Phoenix can pay one dollar to the sock store to either: recolor a sock to any color \(c'\) \((1 \le c' \le n)\) turn a left sock into a right sock turn a right sock into a left sock The sock store may perform each of these changes any number of times. Note that the color of a left sock doesn't change when it turns into a right sock, and vice versa. A matching pair of socks is a left and right sock with the same color. What is the minimum cost for Phoenix to make \(n/2\) matching pairs? Each sock must be included in exactly one matching pair.
|
The input consists of multiple test cases. The first line contains an integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases.The first line of each test case contains three integers \(n\), \(l\), and \(r\) (\(2 \le n \le 2 \cdot 10^5\); \(n\) is even; \(0 \le l, r \le n\); \(l+r=n\)) — the total number of socks, and the number of left and right socks, respectively.The next line contains \(n\) integers \(c_i\) (\(1 \le c_i \le n\)) — the colors of the socks. The first \(l\) socks are left socks, while the next \(r\) socks are right socks.It is guaranteed that the sum of \(n\) across all the test cases will not exceed \(2 \cdot 10^5\).
|
For each test case, print one integer — the minimum cost for Phoenix to make \(n/2\) matching pairs. Each sock must be included in exactly one matching pair.
|
In the first test case, Phoenix can pay \(2\) dollars to: recolor sock \(1\) to color \(2\) recolor sock \(3\) to color \(2\) There are now \(3\) matching pairs. For example, pairs \((1, 4)\), \((2, 5)\), and \((3, 6)\) are matching.In the second test case, Phoenix can pay \(3\) dollars to: turn sock \(6\) from a right sock to a left sock recolor sock \(3\) to color \(1\) recolor sock \(4\) to color \(1\) There are now \(3\) matching pairs. For example, pairs \((1, 3)\), \((2, 4)\), and \((5, 6)\) are matching.
|
Input: 4 6 3 3 1 2 3 2 2 2 6 2 4 1 1 2 2 2 2 6 5 1 6 5 4 3 2 1 4 0 4 4 4 4 3 | Output: 2 3 5 3
|
Medium
| 3 | 736 | 650 | 157 | 15 |
1,778 |
F
|
1778F
|
F. Maximizing Root
| 2,600 |
dfs and similar; dp; graphs; math; number theory; trees
|
You are given a rooted tree consisting of \(n\) vertices numbered from \(1\) to \(n\). Vertex \(1\) is the root of the tree. Each vertex has an integer value. The value of \(i\)-th vertex is \(a_i\). You can do the following operation at most \(k\) times. Choose a vertex \(v\) that has not been chosen before and an integer \(x\) such that \(x\) is a common divisor of the values of all vertices of the subtree of \(v\). Multiply by \(x\) the value of each vertex in the subtree of \(v\). What is the maximum possible value of the root node \(1\) after at most \(k\) operations? Formally, you have to maximize the value of \(a_1\).A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. The subtree of a node \(u\) is the set of all nodes \(y\) such that the simple path from \(y\) to the root passes through \(u\). Note that \(u\) is in the subtree of \(u\).
|
The first line contains an integer \(t\) (\(1 \leq t \leq 50\,000\)) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers \(n\) and \(k\) (\(2 \leq n \leq 10^5\), \(0 \leq k \leq n\)) — the number of vertices in the tree and the number of operations.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 1000\)), where \(a_i\) denotes the value of vertex \(i\).Each of the next \(n - 1\) lines contains two integers \(u_i\) and \(v_i\) (\(1 \leq u_i, v_i \leq n\), \(u_i \neq v_i\)), denoting the edge of the tree between vertices \(u_i\) and \(v_i\). It is guaranteed that the given edges form a tree.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, output the maximum value of the root after performing at most \(k\) operations.
|
Both examples have the same tree: For the first test case, you can do two operations as follows: Choose the subtree of vertex \(4\) and \(x = 2\). After this operation, the node values become \(\{24, 12, 24, 12, 12\}.\) Choose the subtree of vertex \(1\) and \(x = 12\). After this operation, the node values become \(\{288, 144, 288, 144, 144\}.\) The value of the root is \(288\) and it is the maximum.For the second test case, you can do three operations as follows: Choose the subtree of vertex \(4\) and \(x = 2\). After this operation, the node values become \(\{24, 12, 24, 12, 12\}.\) Choose the subtree of vertex \(2\) and \(x = 4\). After this operation, the node values become \(\{24, 48, 24, 48, 48\}.\) Choose the subtree of vertex \(1\) and \(x = 24\). After this operation, the node values become \(\{576, 1152, 576, 1152, 1152\}.\) The value of the root is \(576\) and it is the maximum.
|
Input: 25 224 12 24 6 121 21 32 42 55 324 12 24 6 121 21 32 42 5 | Output: 288 576
|
Expert
| 6 | 933 | 797 | 99 | 17 |
1,423 |
C
|
1423C
|
C. Dušan's Railway
| 3,500 |
divide and conquer; graphs; trees
|
As you may already know, Dušan is keen on playing with railway models. He has a big map with cities that are connected with railways. His map can be seen as a graph where vertices are cities and the railways connecting them are the edges. So far, the graph corresponding to his map is a tree. As you already know, a tree is a connected acyclic undirected graph.He is curious to find out whether his railway can be optimized somehow. He wants to add so-called shortcuts, which are also railways connecting pairs of cities. This shortcut will represent the railways in the unique path in the tree between the pair of cities it connects. Since Dušan doesn't like repeating the railways, he has also defined good paths in his newly obtained network (notice that after adding the shortcuts, his graph is no more a tree). He calls a path good, if no edge appears more than once, either as a regular railway edge or as an edge represented by some shortcut (Every shortcut in a good path has length 1, but uses up all the edges it represents - they can't appear again in that path). Having defined good paths, he defines good distance between two cities to be the length of the shortest good path between them. Finally, the shortcutting diameter of his network is the largest good distance between any two cities.Now he is curious to find out whether it is possible to achieve shortcutting diameter less or equal than \(k\), while adding as few shortcuts as possible.Your solution should add no more than \(\mathbf{10 \cdot n}\) shortcuts.
|
The first line in the standard input contains an integer \(n\) (\(1 \le n \le 10^4\)), representing the number of the cities in Dušan's railway map, and an integer k (\(3 \le k \le n\)) representing the shortcutting diameter that he wants to achieve.Each of the following \(n - 1\) lines will contain two integers \(u_i\) and \(v_i\) (\(1 \le u_i, v_i \le n, u_i \neq v_i\)), meaning that there is a railway between cities \(u_i\) and \(v_i\).
|
The first line of the output should contain a number \(t\) representing the number of the shortcuts that were added.Each of the following \(t\) lines should contain two integers \(u_i\) and \(v_i\), signifying that a shortcut is added between cities \(u_i\) and \(v_i\).
|
Notice that adding a shortcut between all cities and city 1 will make a graph theoretic diameter become 2. On the other hand, the paths obtained that way might not be good, since some of the edges might get duplicated. In the example, adding a shortcut between all cities and city 1 doesn't create a valid solution, because for cities 5 and 10 the path that uses shortcuts 5-1 and 1-10 is not valid because it uses edges 1-2, 2-3, 3-4, 4-5 twice.
|
Input: 10 3 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 | Output: 8 3 7 3 5 3 6 3 1 7 9 7 10 7 4 7 5
|
Master
| 3 | 1,531 | 443 | 270 | 14 |
1,450 |
D
|
1450D
|
D. Rating Compression
| 1,800 |
binary search; data structures; greedy; implementation; two pointers
|
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers \(a\) of length \(n\). You are now updating the infrastructure, so you've created a program to compress these graphs.The program works as follows. Given an integer parameter \(k\), the program takes the minimum of each contiguous subarray of length \(k\) in \(a\).More formally, for an array \(a\) of length \(n\) and an integer \(k\), define the \(k\)-compression array of \(a\) as an array \(b\) of length \(n-k+1\), such that $$$\(b_j =\min_{j\le i\le j+k-1}a_i\)\(For example, the \)3\(-compression array of \)[1, 3, 4, 5, 2]\( is \)[\min\{1, 3, 4\}, \min\{3, 4, 5\}, \min\{4, 5, 2\}]=[1, 3, 2].\(A permutation of length \)m\( is an array consisting of \)m\( distinct integers from \)1\( to \)m\( in arbitrary order. For example, \)[2,3,1,5,4]\( is a permutation, but \)[1,2,2]\( is not a permutation (\)2\( appears twice in the array) and \)[1,3,4]\( is also not a permutation (\)m=3\( but there is \)4\( in the array).A \)k\(-compression array will make CodeCook users happy if it will be a permutation. Given an array \)a\(, determine for all \)1\leq k\leq n\( if CodeCook users will be happy after a \)k$$$-compression of this array or not.
|
The first line contains a single integer \(t\) (\(1\leq t\leq 10^4\)) — the number of test cases.The first line of the description of each test case contains a single integer \(n\) (\(1\leq n\leq 3\cdot 10^5\)) — the length of the array.The second line of the description of each test case contains \(n\) integers \(a_1,\ldots,a_n\) (\(1\leq a_i\leq n\)) — the elements of the array.It is guaranteed, that the sum of \(n\) for all test cases does not exceed \(3\cdot 10^5\).
|
For each test case, print a binary string of length \(n\). The \(k\)-th character of the string should be \(1\) if CodeCook users will be happy after a \(k\)-compression of the array \(a\), and \(0\) otherwise.
|
In the first test case, \(a=[1, 5, 3, 4, 2]\). The \(1\)-compression of \(a\) is \([1, 5, 3, 4, 2]\) and it is a permutation. The \(2\)-compression of \(a\) is \([1, 3, 3, 2]\) and it is not a permutation, since \(3\) appears twice. The \(3\)-compression of \(a\) is \([1, 3, 2]\) and it is a permutation. The \(4\)-compression of \(a\) is \([1, 2]\) and it is a permutation. The \(5\)-compression of \(a\) is \([1]\) and it is a permutation.
|
Input: 5 5 1 5 3 4 2 4 1 3 2 1 5 1 3 3 3 2 10 1 2 3 4 5 6 7 8 9 10 3 3 3 2 | Output: 10111 0001 00111 1111111111 000
|
Medium
| 5 | 1,264 | 474 | 210 | 14 |
1,065 |
D
|
1065D
|
D. Three Pieces
| 2,200 |
dfs and similar; dp; shortest paths
|
You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily \(8 \times 8\), but it still is \(N \times N\). Each square has some number written on it, all the numbers are from \(1\) to \(N^2\) and all the numbers are pairwise distinct. The \(j\)-th square in the \(i\)-th row has a number \(A_{ij}\) written on it.In your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number \(1\) (you can choose which one). Then you want to reach square \(2\) (possibly passing through some other squares in process), then square \(3\) and so on until you reach square \(N^2\). In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. Each square can be visited arbitrary number of times.A knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on.You want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements.What is the path you should take to satisfy all conditions?
|
The first line contains a single integer \(N\) (\(3 \le N \le 10\)) — the size of the chessboard.Each of the next \(N\) lines contains \(N\) integers \(A_{i1}, A_{i2}, \dots, A_{iN}\) (\(1 \le A_{ij} \le N^2\)) — the numbers written on the squares of the \(i\)-th row of the board.It is guaranteed that all \(A_{ij}\) are pairwise distinct.
|
The only line should contain two integers — the number of steps in the best answer and the number of replacement moves in it.
|
Here are the steps for the first example (the starting piece is a knight): Move to \((3, 2)\) Move to \((1, 3)\) Move to \((3, 2)\) Replace the knight with a rook Move to \((3, 1)\) Move to \((3, 3)\) Move to \((3, 2)\) Move to \((2, 2)\) Move to \((2, 3)\) Move to \((2, 1)\) Move to \((1, 1)\) Move to \((1, 2)\)
|
Input: 31 9 38 6 74 2 5 | Output: 12 1
|
Hard
| 3 | 1,407 | 340 | 125 | 10 |
1,172 |
C1
|
1172C1
|
C1. Nauuo and Pictures (easy version)
| 2,300 |
dp; probabilities
|
The only difference between easy and hard versions is constraints.Nauuo is a girl who loves random picture websites.One day she made a random picture website by herself which includes \(n\) pictures.When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The \(i\)-th picture has a non-negative weight \(w_i\), and the probability of the \(i\)-th picture being displayed is \(\frac{w_i}{\sum_{j=1}^nw_j}\). That is to say, the probability of a picture to be displayed is proportional to its weight.However, Nauuo discovered that some pictures she does not like were displayed too often. To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add \(1\) to its weight; otherwise, she would subtract \(1\) from its weight.Nauuo will visit the website \(m\) times. She wants to know the expected weight of each picture after all the \(m\) visits modulo \(998244353\). Can you help her?The expected weight of the \(i\)-th picture can be denoted by \(\frac {q_i} {p_i}\) where \(\gcd(p_i,q_i)=1\), you need to print an integer \(r_i\) satisfying \(0\le r_i<998244353\) and \(r_i\cdot p_i\equiv q_i\pmod{998244353}\). It can be proved that such \(r_i\) exists and is unique.
|
The first line contains two integers \(n\) and \(m\) (\(1\le n\le 50\), \(1\le m\le 50\)) — the number of pictures and the number of visits to the website.The second line contains \(n\) integers \(a_1,a_2,\ldots,a_n\) (\(a_i\) is either \(0\) or \(1\)) — if \(a_i=0\) , Nauuo does not like the \(i\)-th picture; otherwise Nauuo likes the \(i\)-th picture. It is guaranteed that there is at least one picture which Nauuo likes.The third line contains \(n\) integers \(w_1,w_2,\ldots,w_n\) (\(1\le w_i\le50\)) — the initial weights of the pictures.
|
The output contains \(n\) integers \(r_1,r_2,\ldots,r_n\) — the expected weights modulo \(998244353\).
|
In the first example, if the only visit shows the first picture with a probability of \(\frac 2 3\), the final weights are \((1,1)\); if the only visit shows the second picture with a probability of \(\frac1 3\), the final weights are \((2,2)\).So, both expected weights are \(\frac2 3\cdot 1+\frac 1 3\cdot 2=\frac4 3\) .Because \(332748119\cdot 3\equiv 4\pmod{998244353}\), you need to print \(332748119\) instead of \(\frac4 3\) or \(1.3333333333\).In the second example, there is only one picture which Nauuo likes, so every time Nauuo visits the website, \(w_1\) will be increased by \(1\).So, the expected weight is \(1+2=3\).Nauuo is very naughty so she didn't give you any hint of the third example.
|
Input: 2 1 0 1 2 1 | Output: 332748119 332748119
|
Expert
| 2 | 1,281 | 546 | 102 | 11 |
1,968 |
G2
|
1968G2
|
G2. Division + LCP (hard version)
| 2,200 |
binary search; brute force; data structures; dp; hashing; math; string suffix structures; strings
|
This is the hard version of the problem. In this version \(l\le r\).You are given a string \(s\). For a fixed \(k\), consider a division of \(s\) into exactly \(k\) continuous substrings \(w_1,\dots,w_k\). Let \(f_k\) be the maximal possible \(LCP(w_1,\dots,w_k)\) among all divisions.\(LCP(w_1,\dots,w_m)\) is the length of the Longest Common Prefix of the strings \(w_1,\dots,w_m\).For example, if \(s=abababcab\) and \(k=4\), a possible division is \(\color{red}{ab}\color{blue}{ab}\color{orange}{abc}\color{green}{ab}\). The \(LCP(\color{red}{ab},\color{blue}{ab},\color{orange}{abc},\color{green}{ab})\) is \(2\), since \(ab\) is the Longest Common Prefix of those four strings. Note that each substring consists of a continuous segment of characters and each character belongs to exactly one substring.Your task is to find \(f_l,f_{l+1},\dots,f_r\).
|
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.The first line of each test case contains two integers \(n\), \(l\), \(r\) (\(1 \le l \le r \le n \le 2 \cdot 10^5\)) — the length of the string and the given range.The second line of each test case contains string \(s\) of length \(n\), all characters are lowercase English letters.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot 10^5\).
|
For each test case, output \(r-l+1\) values: \(f_l,\dots,f_r\).
|
Input: 73 1 3aba3 2 3aaa7 1 5abacaba9 1 6abababcab10 1 10aaaaaaawac9 1 9abafababa7 2 7vvzvvvv | Output: 3 1 0 1 1 7 3 1 1 0 9 2 2 2 0 0 10 3 2 1 1 1 1 1 0 0 9 3 2 1 1 0 0 0 0 2 2 1 1 1 0
|
Hard
| 8 | 855 | 471 | 63 | 19 |
|
1,583 |
H
|
1583H
|
H. Omkar and Tours
| 3,300 |
data structures; divide and conquer; sortings; trees
|
Omkar is hosting tours of his country, Omkarland! There are \(n\) cities in Omkarland, and, rather curiously, there are exactly \(n-1\) bidirectional roads connecting the cities to each other. It is guaranteed that you can reach any city from any other city through the road network.Every city has an enjoyment value \(e\). Each road has a capacity \(c\), denoting the maximum number of vehicles that can be on it, and an associated toll \(t\). However, the toll system in Omkarland has an interesting quirk: if a vehicle travels on multiple roads on a single journey, they pay only the highest toll of any single road on which they traveled. (In other words, they pay \(\max t\) over all the roads on which they traveled.) If a vehicle traverses no roads, they pay \(0\) toll.Omkar has decided to host \(q\) tour groups. Each tour group consists of \(v\) vehicles starting at city \(x\). (Keep in mind that a tour group with \(v\) vehicles can travel only on roads with capacity \(\geq v\).) Being the tour organizer, Omkar wants his groups to have as much fun as they possibly can, but also must reimburse his groups for the tolls that they have to pay. Thus, for each tour group, Omkar wants to know two things: first, what is the enjoyment value of the city \(y\) with maximum enjoyment value that the tour group can reach from their starting city, and second, how much per vehicle will Omkar have to pay to reimburse the entire group for their trip from \(x\) to \(y\)? (This trip from \(x\) to \(y\) will always be on the shortest path from \(x\) to \(y\).)In the case that there are multiple reachable cities with the maximum enjoyment value, Omkar will let his tour group choose which one they want to go to. Therefore, to prepare for all possible scenarios, he wants to know the amount of money per vehicle that he needs to guarantee that he can reimburse the group regardless of which city they choose.
|
The first line contains two integers \(n\) and \(q\) (\(2 \leq n \leq 2 \cdot 10^5\), \(1 \leq q \leq 2 \cdot 10^5\)), representing the number of cities and the number of groups, respectively.The next line contains \(n\) integers \(e_1, e_2, \ldots, e_n\) (\(1 \leq e_i \leq 10^9\)), where \(e_i\) represents the enjoyment value for city \(i\).The next \(n-1\) lines each contain four integers \(a\), \(b\), \(c\), and \(t\) (\(1 \leq a,b \leq n\), \(1 \leq c \leq 10^9\), \(1 \leq t \leq 10^9\)), representing an road between city \(a\) and city \(b\) with capacity \(c\) and toll \(t\).The next \(q\) lines each contain two integers \(v\) and \(x\) (\(1 \leq v \leq 10^9\), \(1 \leq x \leq n\)), representing the number of vehicles in the tour group and the starting city, respectively.
|
Output \(q\) lines. The \(i\)-th line should contain two integers: the highest possible enjoyment value of a city reachable by the \(i\)-th tour group, and the amount of money per vehicle Omkar needs to guarantee that he can reimburse the \(i\)-th tour group.
|
A map of the first sample is shown below. For the nodes, unbolded numbers represent indices and bolded numbers represent enjoyment values. For the edges, unbolded numbers represent capacities and bolded numbers represent tolls. For the first query, a tour group of size \(1\) starting at city \(3\) can reach cities \(1\), \(2\), \(3\), \(4\), and \(5\). Thus, the largest enjoyment value that they can reach is \(3\). If the tour group chooses to go to city \(4\), Omkar will have to pay \(8\) per vehicle, which is the maximum.For the second query, a tour group of size \(9\) starting at city \(5\) can reach only city \(5\). Thus, the largest reachable enjoyment value is still \(3\), and Omkar will pay \(0\) per vehicle.For the third query, a tour group of size \(6\) starting at city \(2\) can reach cities \(2\) and \(4\). The largest reachable enjoyment value is again \(3\). If the tour group chooses to go to city \(4\), Omkar will have to pay \(2\) per vehicle, which is the maximum.A map of the second sample is shown below: For the first query, a tour group of size \(5\) starting at city \(1\) can only reach city \(1\). Thus, their maximum enjoyment value is \(1\) and the cost Omkar will have to pay is \(0\) per vehicle.For the second query, a tour group of size \(4\) starting at city \(1\) can reach cities \(1\) and \(2\). Thus, their maximum enjoyment value is \(2\) and Omkar will pay \(1\) per vehicle.For the third query, a tour group of size \(3\) starting at city \(1\) can reach cities \(1\), \(2\), and \(3\). Thus, their maximum enjoyment value is \(3\) and Omkar will pay \(1\) per vehicle.For the fourth query, a tour group of size \(2\) starting at city \(1\) can reach cities \(1\), \(2\), \(3\) and \(4\). Thus, their maximum enjoyment value is \(4\) and Omkar will pay \(1\) per vehicle.For the fifth query, a tour group of size \(1\) starting at city \(1\) can reach cities \(1\), \(2\), \(3\), \(4\), and \(5\). Thus, their maximum enjoyment value is \(5\) and Omkar will pay \(1\) per vehicle.
|
Input: 5 3 2 2 3 3 3 1 2 4 7 1 3 2 8 2 4 8 2 2 5 1 1 1 3 9 5 6 2 | Output: 3 8 3 0 3 2
|
Master
| 4 | 1,912 | 788 | 259 | 15 |
1,003 |
F
|
1003F
|
F. Abbreviation
| 2,200 |
dp; hashing; strings
|
You are given a text consisting of \(n\) space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. \(w_i\) is the \(i\)-th word of text. All words consist only of lowercase Latin letters.Let's denote a segment of words \(w[i..j]\) as a sequence of words \(w_i, w_{i + 1}, \dots, w_j\). Two segments of words \(w[i_1 .. j_1]\) and \(w[i_2 .. j_2]\) are considered equal if \(j_1 - i_1 = j_2 - i_2\), \(j_1 \ge i_1\), \(j_2 \ge i_2\), and for every \(t \in [0, j_1 - i_1]\) \(w_{i_1 + t} = w_{i_2 + t}\). For example, for the text ""to be or not to be"" the segments \(w[1..2]\) and \(w[5..6]\) are equal, they correspond to the words ""to be"".An abbreviation is a replacement of some segments of words with their first uppercase letters. In order to perform an abbreviation, you have to choose at least two non-intersecting equal segments of words, and replace each chosen segment with the string consisting of first letters of the words in the segment (written in uppercase). For example, for the text ""a ab a a b ab a a b c"" you can replace segments of words \(w[2..4]\) and \(w[6..8]\) with an abbreviation ""AAA"" and obtain the text ""a AAA b AAA b c"", or you can replace segments of words \(w[2..5]\) and \(w[6..9]\) with an abbreviation ""AAAB"" and obtain the text ""a AAAB AAAB c"".What is the minimum length of the text after at most one abbreviation?
|
The first line of the input contains one integer \(n\) (\(1 \le n \le 300\)) — the number of words in the text.The next line contains \(n\) space-separated words of the text \(w_1, w_2, \dots, w_n\). Each word consists only of lowercase Latin letters.It is guaranteed that the length of text does not exceed \(10^5\).
|
Print one integer — the minimum length of the text after at most one abbreviation.
|
In the first example you can obtain the text ""TB or not TB"".In the second example you can obtain the text ""a AAAB AAAB c"".In the third example you can obtain the text ""AB aa AB bb"".
|
Input: 6to be or not to be | Output: 12
|
Hard
| 3 | 1,541 | 317 | 82 | 10 |
1,034 |
A
|
1034A
|
A. Enlarge GCD
| 1,800 |
number theory
|
Mr. F has \(n\) positive integers, \(a_1, a_2, \ldots, a_n\).He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers.But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward.Your task is to calculate the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers.
|
The first line contains an integer \(n\) (\(2 \leq n \leq 3 \cdot 10^5\)) — the number of integers Mr. F has.The second line contains \(n\) integers, \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 1.5 \cdot 10^7\)).
|
Print an integer — the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers.You should not remove all of the integers.If there is no solution, print «-1» (without quotes).
|
In the first example, the greatest common divisor is \(1\) in the beginning. You can remove \(1\) so that the greatest common divisor is enlarged to \(2\). The answer is \(1\).In the second example, the greatest common divisor is \(3\) in the beginning. You can remove \(6\) and \(9\) so that the greatest common divisor is enlarged to \(15\). There is no solution which removes only one integer. So the answer is \(2\).In the third example, there is no solution to enlarge the greatest common divisor. So the answer is \(-1\).
|
Input: 31 2 4 | Output: 1
|
Medium
| 1 | 501 | 213 | 262 | 10 |
111 |
A
|
111A
|
A. Petya and Inequiations
| 1,400 |
greedy
|
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied: a12 + a22 + ... + an2 ≥ x a1 + a2 + ... + an ≤ y
|
The first line contains three space-separated integers n, x and y (1 ≤ n ≤ 105, 1 ≤ x ≤ 1012, 1 ≤ y ≤ 106).Please do not use the %lld specificator to read or write 64-bit integers in С++. It is recommended to use cin, cout streams or the %I64d specificator.
|
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number ""-1"". If there are several solutions, print any of them.
|
Input: 5 15 15 | Output: 44112
|
Easy
| 1 | 185 | 257 | 187 | 1 |
|
1,574 |
C
|
1574C
|
C. Slay the Dragon
| 1,300 |
binary search; greedy; sortings; ternary search
|
Recently, Petya learned about a new game ""Slay the Dragon"". As the name suggests, the player will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To do this, the player has a squad of \(n\) heroes, the strength of the \(i\)-th hero is equal to \(a_i\).According to the rules of the game, exactly one hero should go kill the dragon, all the others will defend the castle. If the dragon's defense is equal to \(x\), then you have to send a hero with a strength of at least \(x\) to kill it. If the dragon's attack power is \(y\), then the total strength of the heroes defending the castle should be at least \(y\).The player can increase the strength of any hero by \(1\) for one gold coin. This operation can be done any number of times.There are \(m\) dragons in the game, the \(i\)-th of them has defense equal to \(x_i\) and attack power equal to \(y_i\). Petya was wondering what is the minimum number of coins he needs to spend to defeat the \(i\)-th dragon.Note that the task is solved independently for each dragon (improvements are not saved).
|
The first line contains a single integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) — number of heroes.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^{12}\)), where \(a_i\) is the strength of the \(i\)-th hero.The third line contains a single integer \(m\) (\(1 \le m \le 2 \cdot 10^5\)) — the number of dragons.The next \(m\) lines contain two integers each, \(x_i\) and \(y_i\) (\(1 \le x_i \le 10^{12}; 1 \le y_i \le 10^{18}\)) — defense and attack power of the \(i\)-th dragon.
|
Print \(m\) lines, \(i\)-th of which contains a single integer — the minimum number of coins that should be spent to defeat the \(i\)-th dragon.
|
To defeat the first dragon, you can increase the strength of the third hero by \(1\), then the strength of the heroes will be equal to \([3, 6, 3, 3]\). To kill the dragon, you can choose the first hero.To defeat the second dragon, you can increase the forces of the second and third heroes by \(1\), then the strength of the heroes will be equal to \([3, 7, 3, 3]\). To kill the dragon, you can choose a second hero.To defeat the third dragon, you can increase the strength of all the heroes by \(1\), then the strength of the heroes will be equal to \([4, 7, 3, 4]\). To kill the dragon, you can choose a fourth hero.To defeat the fourth dragon, you don't need to improve the heroes and choose a third hero to kill the dragon.To defeat the fifth dragon, you can increase the strength of the second hero by \(2\), then the strength of the heroes will be equal to \([3, 8, 2, 3]\). To kill the dragon, you can choose a second hero.
|
Input: 4 3 6 2 3 5 3 12 7 9 4 14 1 10 8 7 | Output: 1 2 4 0 2
|
Easy
| 4 | 1,096 | 513 | 144 | 15 |
876 |
A
|
876A
|
A. Trip For Meal
| 900 |
math
|
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters.For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store).Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance.
|
First line contains an integer n (1 ≤ n ≤ 100) — number of visits.Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses.Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses.Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses.
|
Output one number — minimum distance in meters Winnie must go through to have a meal n times.
|
In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3.In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all.
|
Input: 3231 | Output: 3
|
Beginner
| 1 | 1,238 | 347 | 93 | 8 |
1,804 |
H
|
1804H
|
H. Code Lock
| 3,300 |
bitmasks; dp
|
Lara has a safe that is locked with a circle-shaped code lock that consists of a rotating arrow, a static circumference around the arrow, an input screen, and an input button.The circumference of the lock is split into \(k\) equal sections numbered from \(1\) to \(k\) in clockwise order. Arrow always points to one of the sections. Each section is marked with one of the first \(k\) letters of the English alphabet. No two sections are marked with the same letter.Due to the lock limitations, the safe's password is a string of length \(n\) that consists of first \(k\) letters of the English alphabet only. Lara enters the password by rotating the lock's arrow and pressing the input button. Initially, the lock's arrow points to section \(1\) and the input screen is empty. In one second she can do one of the following actions. Rotate the arrow one section clockwise. If the arrow was pointing at section \(x < k\) it will now point at section \(x + 1\). If the arrow was pointing at section \(k\) it will now point at section \(1\). Rotate the arrow one section counter-clockwise. If the arrow was pointing at section \(x > 1\) it will now point at section \(x - 1\). If the arrow was pointing at section \(1\) it will now point at section \(k\). Press the input button. The letter marked on the section that the arrow points to will be added to the content of the input screen. As soon as the content of the input screen matches the password, the safe will open. Lara always enters her password in the minimum possible time.Lara has recently found out that the safe can be re-programmed. She can take the first \(k\) letters of the English alphabet and assign them to the sectors in any order she likes. Now she wants to re-arrange the letters in a way that will minimize the number of seconds it takes her to input the password. Compute this minimum number of seconds and the number of ways to assign letters, for which this minimum number of seconds is achieved.Two ways to assign letters to sectors are considered to be distinct if there exists at least one sector \(i\) that is assigned different letters.
|
The first line of the input contains two integers \(k\) and \(n\) (\(2 \leq k \leq 16\), \(2 \leq n \leq 100\,000\)) — the number of sectors on the lock's circumference and the length of Lara's password, respectively.The second line of the input contains a string of length \(n\) that consists of the first \(k\) lowercase letters of the English alphabet only. This string is the password.
|
On the first line print minimum possible number of seconds it can take Lara to enter the password and open the safe if she assigns letters to sectors optimally.On the second line print the number of ways to assign letters optimally.
|
The initial states of optimal arrangements for the first example are shown in the figure below. The initial states of optimal arrangements for the second example are shown in the figure below. The initial states of optimal arrangements for the third example are shown in the figure below.
|
Input: 3 10 abcabcabca | Output: 19 2
|
Master
| 2 | 2,115 | 389 | 232 | 18 |
1,371 |
E2
|
1371E2
|
E2. Asterism (Hard Version)
| 2,300 |
binary search; combinatorics; dp; math; number theory; sortings
|
This is the hard version of the problem. The difference between versions is the constraints on \(n\) and \(a_i\). You can make hacks only if all versions of the problem are solved.First, Aoi came up with the following idea for the competitive programming problem:Yuzu is a girl who collecting candies. Originally, she has \(x\) candies. There are also \(n\) enemies numbered with integers from \(1\) to \(n\). Enemy \(i\) has \(a_i\) candies.Yuzu is going to determine a permutation \(P\). A permutation is an array consisting of \(n\) distinct integers from \(1\) to \(n\) in arbitrary order. For example, \(\{2,3,1,5,4\}\) is a permutation, but \(\{1,2,2\}\) is not a permutation (\(2\) appears twice in the array) and \(\{1,3,4\}\) is also not a permutation (because \(n=3\) but there is the number \(4\) in the array).After that, she will do \(n\) duels with the enemies with the following rules: If Yuzu has equal or more number of candies than enemy \(P_i\), she wins the duel and gets \(1\) candy. Otherwise, she loses the duel and gets nothing. The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations \(P\) exist?This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea:Let's define \(f(x)\) as the number of valid permutations for the integer \(x\).You are given \(n\), \(a\) and a prime number \(p \le n\). Let's call a positive integer \(x\) good, if the value \(f(x)\) is not divisible by \(p\). Find all good integers \(x\).Your task is to solve this problem made by Akari.
|
The first line contains two integers \(n\), \(p\) \((2 \le p \le n \le 10^5)\). It is guaranteed, that the number \(p\) is prime (it has exactly two divisors \(1\) and \(p\)).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) \((1 \le a_i \le 10^9)\).
|
In the first line, print the number of good integers \(x\).In the second line, output all good integers \(x\) in the ascending order.It is guaranteed that the number of good integers \(x\) does not exceed \(10^5\).
|
In the first test, \(p=2\). If \(x \le 2\), there are no valid permutations for Yuzu. So \(f(x)=0\) for all \(x \le 2\). The number \(0\) is divisible by \(2\), so all integers \(x \leq 2\) are not good. If \(x = 3\), \(\{1,2,3\}\) is the only valid permutation for Yuzu. So \(f(3)=1\), so the number \(3\) is good. If \(x = 4\), \(\{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\}\) are all valid permutations for Yuzu. So \(f(4)=4\), so the number \(4\) is not good. If \(x \ge 5\), all \(6\) permutations are valid for Yuzu. So \(f(x)=6\) for all \(x \ge 5\), so all integers \(x \ge 5\) are not good. So, the only good number is \(3\).In the third test, for all positive integers \(x\) the value \(f(x)\) is divisible by \(p = 3\).
|
Input: 3 2 3 4 5 | Output: 1 3
|
Expert
| 6 | 1,625 | 266 | 214 | 13 |
1,531 |
E1
|
1531E1
|
E1. Сортировка слиянием
| 0 |
*special
|
Рассмотрим следующий код сортировки слиянием на языке Python: def sort(a): n = len(a) b = [0 for i in range(n)] log = [] def mergeSort(l, r): if r - l <= 1: return m = (l + r) >> 1 mergeSort(l, m) mergeSort(m, r) i, j, k = l, m, l while i < m and j < r: if a[i] < a[j]: log.append('0') b[k] = a[i] i += 1 else: log.append('1') b[k] = a[j] j += 1 k += 1 while i < m: b[k] = a[i] i += 1 k += 1 while j < r: b[k] = a[j] j += 1 k += 1 for p in range(l, r): a[p] = b[p] mergeSort(0, n) return """".join(log)Как можно заметить, этот код использует логирование — важнейший инструмент разработки.Старший разработчик ВКонтакте Вася сгенерировал перестановку \(a\) (массив из \(n\) различных целых чисел от \(1\) до \(n\)), дал её на вход функции sort и получил на выходе строку \(s\). На следующий день строку \(s\) Вася нашёл, а перестановка \(a\) потерялась. Вася хочет восстановить любую перестановку \(a\) такую, что вызов функции sort от неё даст ту же строку \(s\). Помогите ему!
|
Ввод содержит непустую строку \(s\), состоящую из символов 0 и 1. В этой версии задачи для любого теста существует перестановка длины \(16\), удовлетворяющая условию. Тем не менее, ваш ответ может иметь любую длину, в том числе отличную от \(16\).
|
В первой строке выведите целое число \(n\) — длину перестановки.Во второй строке выведите \(n\) различных целых чисел \(a_0, a_1, \ldots, a_{n-1}\) (\(1 \le a_i \le n\)) — элементы перестановки.Если существует несколько вариантов ответа, выведите любой из них.
|
Input: 00000000000000000000000000000000 | Output: 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
Beginner
| 1 | 976 | 247 | 260 | 15 |
|
1,775 |
D
|
1775D
|
D. Friendly Spiders
| 1,800 |
dfs and similar; graphs; math; number theory; shortest paths
|
Mars is home to an unusual species of spiders — Binary spiders.Right now, Martian scientists are observing a colony of \(n\) spiders, the \(i\)-th of which has \(a_i\) legs.Some of the spiders are friends with each other. Namely, the \(i\)-th and \(j\)-th spiders are friends if \(\gcd(a_i, a_j) \ne 1\), i. e., there is some integer \(k \ge 2\) such that \(a_i\) and \(a_j\) are simultaneously divided by \(k\) without a remainder. Here \(\gcd(x, y)\) denotes the greatest common divisor (GCD) of integers \(x\) and \(y\).Scientists have discovered that spiders can send messages. If two spiders are friends, then they can transmit a message directly in one second. Otherwise, the spider must pass the message to his friend, who in turn must pass the message to his friend, and so on until the message reaches the recipient.Let's look at an example.Suppose a spider with eight legs wants to send a message to a spider with \(15\) legs. He can't do it directly, because \(\gcd(8, 15) = 1\). But he can send a message through the spider with six legs because \(\gcd(8, 6) = 2\) and \(\gcd(6, 15) = 3\). Thus, the message will arrive in two seconds.Right now, scientists are observing how the \(s\)-th spider wants to send a message to the \(t\)-th spider. The researchers have a hypothesis that spiders always transmit messages optimally. For this reason, scientists would need a program that could calculate the minimum time to send a message and also deduce one of the optimal routes.
|
The first line of input contains an integer \(n\) (\(2 \le n \le 3\cdot10^5\)) — the number of spiders in the colony.The second line of input contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 3\cdot10^5\)) — the number of legs the spiders have.The third line of input contains two integers \(s\) and \(t\) (\(1 \le s, t \le n\)) —the spiders between which the message must be sent.
|
If it is impossible to transmit a message between the given pair of spiders, print \(-1\).Otherwise, in the first line of the output print the integer \(t\) (\(t \ge 1\)) — the number of spiders that participate in the message transmission (i. e. the minimum time of message delivery in seconds plus one). In the second line, print \(t\) different integers \(b_1, b_2, \ldots, b_t\) (\(1 \le b_i \le n\)) — the ids of the spiders through which the message should follow, in order from sender to receiver.If there are several optimal routes for the message, output any of them.
|
The first example is shown above. It shows that the message from the \(5\)-th spider (with eight legs) to the \(6\)-th spider (with \(15\) legs) is optimal to pass through the \(4\)-th spider (with six legs).In the second example, the spider number \(7\) (with \(11\) legs) is not friends with anyone, so it is impossible to send him a message.
|
Input: 7 2 14 9 6 8 15 11 5 6 | Output: 3 5 4 6
|
Medium
| 5 | 1,485 | 398 | 576 | 17 |
1,864 |
E
|
1864E
|
E. Guess Game
| 2,100 |
bitmasks; data structures; games; math; probabilities; sortings; strings; trees
|
Carol has a sequence \(s\) of \(n\) non-negative integers. She wants to play the ""Guess Game"" with Alice and Bob.To play the game, Carol will randomly select two integer indices \(i_a\) and \(i_b\) within the range \([1, n]\), and set \(a=s_{i_a}\), \(b=s_{i_b}\). Please note that \(i_a\) and \(i_b\) may coincide.Carol will tell: the value of \(a\) to Alice; the value of \(b\) to Bob; the value of \(a \mid b\) to both Alice and Bob, where \(|\) denotes the bitwise OR operation. Please note that Carol will not tell any information about \(s\) to either Alice or Bob.Then the guessing starts. The two players take turns making guesses, with Alice starting first. The goal of both players is to establish which of the following is true: \(a < b\), \(a > b\), or \(a = b\).In their turn, a player can do one of the following two things: say ""I don't know"", and pass the turn to the other player; say ""I know"", followed by the answer ""\(a<b\)"", ""\(a>b\)"", or ""\(a=b\)""; then the game ends. Alice and Bob hear what each other says, and can use this information to deduce the answer. Both Alice and Bob are smart enough and only say ""I know"" when they are completely sure.You need to calculate the expected value of the number of turns taken by players in the game. Output the answer modulo \(998\,244\,353\).Formally, let \(M = 998\,244\,353\). It can be shown that the answer can be expressed as an irreducible fraction \(\frac{p}{q}\), where \(p\) and \(q\) are integers and \(q \not \equiv 0 \pmod{M}\). Output the integer equal to \(p \cdot q^{-1} \bmod M\). In other words, output such an integer \(x\) that \(0 \le x < M\) and \(x \cdot q \equiv p \pmod{M}\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^5\)). The description of the test cases follows.The first line of each testcase contains a single integer \(n\) (\(1 \le n \le 2\cdot 10^5\)).The second line of each testcase contains \(n\) integers \(s_1,s_2,\ldots, s_n\) (\(0 \le s_i < 2^{30}\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, print a single integer — the answer to the problem modulo \(998\,244\,353\).
|
In the first test case, there are only \(4\) possible situations: \(i_a=1\), \(i_b=1\), \(a=2\), \(b=2\), the number of turns is \(2\); \(i_a=1\), \(i_b=2\), \(a=2\), \(b=3\), the number of turns is \(3\); \(i_a=2\), \(i_b=1\), \(a=3\), \(b=2\), the number of turns is \(2\); \(i_a=2\), \(i_b=2\), \(a=3\), \(b=3\), the number of turns is \(3\). The expected number of turns is \(\frac{2+3+2+3}{4}=\frac{5}{2}=499122179\pmod{998244353}\).Consider the first case, when \(a=2\), \(b=2\). The guessing process is as follows.In the first turn, Alice thinks, ""I know that \(a=2, a\mid b=2\). I can infer that \(b=0\) or \(b=2\), but I am not sure which one"". Thus, she says, ""I don't know"".In the second turn, Bob thinks, ""I know that \(b=2, a\mid b=2\). I can infer that \(a=0\) or \(a=2\). But if \(a=0\), then Alice would have already said that \(a<b\) in the first turn, but she hasn't. So \(a=2\)"". Thus, he says, ""I know, \(a=b\)"". The game ends. In the second test case, for \(a=0\), \(b=0\), Alice knows that \(a=b\) immediately. The expected number of turns equals \(1\).
|
Input: 422 330 0 039 9 6834124838 0 113193378 8 321939321 113193378 9463828 99 | Output: 499122179 1 332748120 77987843
|
Hard
| 8 | 1,679 | 453 | 96 | 18 |
598 |
C
|
598C
|
C. Nearest vectors
| 2,300 |
geometry; sortings
|
You are given the set of vectors on the plane, each of them starting at the origin. Your task is to find a pair of vectors with the minimal non-oriented angle between them.Non-oriented angle is non-negative value, minimal between clockwise and counterclockwise direction angles. Non-oriented angle is always between 0 and π. For example, opposite directions vectors have angle equals to π.
|
First line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of vectors.The i-th of the following n lines contains two integers xi and yi (|x|, |y| ≤ 10 000, x2 + y2 > 0) — the coordinates of the i-th vector. Vectors are numbered from 1 to n in order of appearing in the input. It is guaranteed that no two vectors in the input share the same direction (but they still can have opposite directions).
|
Print two integer numbers a and b (a ≠ b) — a pair of indices of vectors with the minimal non-oriented angle. You can print the numbers in any order. If there are many possible answers, print any.
|
Input: 4-1 00 -11 01 1 | Output: 3 4
|
Expert
| 2 | 389 | 421 | 196 | 5 |
|
1,250 |
D
|
1250D
|
D. Conference Problem
| 3,000 |
dp
|
A large-scale conference on unnatural sciences is going to be held soon in Berland! In total, \(n\) scientists from all around the world have applied. All of them have indicated a time segment when they will attend the conference: two integers \(l_i\), \(r_i\) — day of arrival and day of departure.Also, some of the scientists have indicated their country, while some preferred not to. So, each scientist also has a value \(c_i\), where: \(c_i > 0\), if the scientist is coming from country \(c_i\) (all countries are numbered from \(1\) to \(200\)); \(c_i = 0\), if the scientist preferred to not indicate the country. Everyone knows that it is interesting and useful to chat with representatives of other countries! A participant of the conference will be upset if she will not meet people from other countries during the stay. It is possible to meet people during all time of stay, including the day of arrival and the day of departure.Conference organizers need to be ready for the worst! They are interested in the largest number \(x\), that it is possible that among all people attending the conference exactly \(x\) will be upset.Help the organizers to find the maximum number of upset scientists.
|
The first line of the input contains integer \(t\) (\(1 \le t \le 100\)) — number of test cases. Then the test cases follow.The first line of each test case contains integer \(n\) (\(1 \le n \le 500\)) — the number of registered conference participants.Next \(n\) lines follow, each containing three integers \(l_i\), \(r_i\), \(c_i\) (\(1 \le l_i \le r_i \le 10^6\), \(0 \le c_i \le 200\)) — the day of arrival, the day of departure and the country (or the fact that it was not indicated) for the \(i\)-th participant.The sum of \(n\) among all test cases in the input does not exceed \(500\).
|
Output \(t\) integers — maximum number of upset scientists for each test case.
|
Input: 2 4 1 10 30 5 6 30 6 12 0 1 1 0 4 1 2 1 2 3 0 3 4 0 4 5 2 | Output: 4 2
|
Master
| 1 | 1,205 | 594 | 78 | 12 |
|
1,451 |
E1
|
1451E1
|
E1. Bitwise Queries (Easy Version)
| 2,000 |
bitmasks; constructive algorithms; interactive; math
|
The only difference between the easy and hard versions is the constraints on the number of queries.This is an interactive problem.Ridbit has a hidden array \(a\) of \(n\) integers which he wants Ashish to guess. Note that \(n\) is a power of two. Ashish is allowed to ask three different types of queries. They are of the form AND \(i\) \(j\): ask for the bitwise AND of elements \(a_i\) and \(a_j\) \((1 \leq i, j \le n\), \(i \neq j)\) OR \(i\) \(j\): ask for the bitwise OR of elements \(a_i\) and \(a_j\) \((1 \leq i, j \le n\), \(i \neq j)\) XOR \(i\) \(j\): ask for the bitwise XOR of elements \(a_i\) and \(a_j\) \((1 \leq i, j \le n\), \(i \neq j)\) Can you help Ashish guess the elements of the array?In this version, each element takes a value in the range \([0, n-1]\) (inclusive) and Ashish can ask no more than \(n+2\) queries.
|
The first line of input contains one integer \(n\) \((4 \le n \le 2^{16})\) — the length of the array. It is guaranteed that \(n\) is a power of two.
|
The array \(a\) in the example is \([0, 0, 2, 3]\).
|
Input: 4 0 2 3 | Output: OR 1 2 OR 2 3 XOR 2 4 ! 0 0 2 3
|
Hard
| 4 | 840 | 149 | 0 | 14 |
|
1,699 |
A
|
1699A
|
A. The Third Three Number Problem
| 800 |
constructive algorithms; math
|
You are given a positive integer \(n\). Your task is to find any three integers \(a\), \(b\) and \(c\) (\(0 \le a, b, c \le 10^9\)) for which \((a\oplus b)+(b\oplus c)+(a\oplus c)=n\), or determine that there are no such integers.Here \(a \oplus b\) denotes the bitwise XOR of \(a\) and \(b\). For example, \(2 \oplus 4 = 6\) and \(3 \oplus 1=2\).
|
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. The following lines contain the descriptions of the test cases.The only line of each test case contains a single integer \(n\) (\(1 \le n \le 10^9\)).
|
For each test case, print any three integers \(a\), \(b\) and \(c\) (\(0 \le a, b, c \le 10^9\)) for which \((a\oplus b)+(b\oplus c)+(a\oplus c)=n\). If no such integers exist, print \(-1\).
|
In the first test case, \(a=3\), \(b=3\), \(c=1\), so \((3 \oplus 3)+(3 \oplus 1) + (3 \oplus 1)=0+2+2=4\).In the second test case, there are no solutions.In the third test case, \((2 \oplus 4)+(4 \oplus 6) + (2 \oplus 6)=6+2+4=12\).
|
Input: 541122046194723326 | Output: 3 3 1 -1 2 4 6 69 420 666 12345678 87654321 100000000
|
Beginner
| 2 | 347 | 288 | 190 | 16 |
1,136 |
D
|
1136D
|
D. Nastya Is Buying Lunch
| 1,800 |
greedy
|
At the big break Nastya came to the school dining room. There are \(n\) pupils in the school, numbered from \(1\) to \(n\). Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs \(u\), \(v\) such that if the pupil with number \(u\) stands directly in front of the pupil with number \(v\), Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
|
The first line contains two integers \(n\) and \(m\) (\(1 \leq n \leq 3 \cdot 10^{5}\), \(0 \leq m \leq 5 \cdot 10^{5}\)) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.The second line contains \(n\) integers \(p_1\), \(p_2\), ..., \(p_n\) — the initial arrangement of pupils in the queue, from the queue start to its end (\(1 \leq p_i \leq n\), \(p\) is a permutation of integers from \(1\) to \(n\)). In other words, \(p_i\) is the number of the pupil who stands on the \(i\)-th position in the queue.The \(i\)-th of the following \(m\) lines contains two integers \(u_i\), \(v_i\) (\(1 \leq u_i, v_i \leq n, u_i \neq v_i\)), denoting that the pupil with number \(u_i\) agrees to change places with the pupil with number \(v_i\) if \(u_i\) is directly in front of \(v_i\). It is guaranteed that if \(i \neq j\), than \(v_i \neq v_j\) or \(u_i \neq u_j\). Note that it is possible that in some pairs both pupils agree to change places with each other.Nastya is the last person in the queue, i.e. the pupil with number \(p_n\).
|
Print a single integer — the number of places in queue she can move forward.
|
In the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers \(1\) and \(3\). change places for pupils with numbers \(3\) and \(2\). change places for pupils with numbers \(1\) and \(2\). The queue looks like \([3, 1, 2]\), then \([1, 3, 2]\), then \([1, 2, 3]\), and finally \([2, 1, 3]\) after these operations.
|
Input: 2 11 21 2 | Output: 1
|
Medium
| 1 | 695 | 1,162 | 76 | 11 |
1,925 |
D
|
1925D
|
D. Good Trip
| 1,900 |
combinatorics; dp; math; probabilities
|
There are \(n\) children in a class, \(m\) pairs among them are friends. The \(i\)-th pair who are friends have a friendship value of \(f_i\). The teacher has to go for \(k\) excursions, and for each of the excursions she chooses a pair of children randomly, equiprobably and independently. If a pair of children who are friends is chosen, their friendship value increases by \(1\) for all subsequent excursions (the teacher can choose a pair of children more than once). The friendship value of a pair who are not friends is considered \(0\), and it does not change for subsequent excursions. Find the expected value of the sum of friendship values of all \(k\) pairs chosen for the excursions (at the time of being chosen). It can be shown that this answer can always be expressed as a fraction \(\dfrac{p}{q}\) where \(p\) and \(q\) are coprime integers. Calculate \(p\cdot q^{-1} \bmod (10^9+7)\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 5 \cdot 10^4\)). Description of the test cases follows.The first line of each test case contains \(3\) integers \(n\), \(m\) and \(k\) (\(2 \le n \le 10^5\), \(0 \le m \le \min \Big(10^5\), \( \frac{n(n-1)}{2} \Big)\), \(1 \le k \le 2 \cdot 10^5\)) — the number of children, pairs of friends and excursions respectively.The next \(m\) lines contain three integers each — \(a_i\), \(b_i\), \(f_i\) — the indices of the pair of children who are friends and their friendship value. (\(a_i \neq b_i\), \(1 \le a_i,b_i \le n\), \(1 \le f_i \le 10^9\)). It is guaranteed that all pairs of friends are distinct.It is guaranteed that the sum of \(n\) and sum \(m\) over all test cases does not exceed \(10^5\) and the sum of \(k\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, print one integer — the answer to the problem.
|
For the first test case, there are no pairs of friends, so the friendship value of all pairs is \(0\) and stays \(0\) for subsequent rounds, hence the friendship value for all excursions is \(0\).For the second test case, there is only one pair possible \((1, 2)\) and its friendship value is initially \(1\), so each turn they are picked and their friendship value increases by \(1\). Therefore, the total sum is \(1+2+3+\ldots+10 = 55\).For the third test case, the final answer is \(\frac{7}{9} = 777\,777\,784\bmod (10^9+7)\).
|
Input: 4100 0 242 1 101 2 13 1 22 1 15 2 41 2 253 2 24 | Output: 0 55 777777784 40000020
|
Hard
| 4 | 901 | 886 | 66 | 19 |
1,399 |
F
|
1399F
|
F. Yet Another Segments Subset
| 2,300 |
data structures; dp; graphs; sortings
|
You are given \(n\) segments on a coordinate axis \(OX\). The \(i\)-th segment has borders \([l_i; r_i]\). All points \(x\), for which \(l_i \le x \le r_i\) holds, belong to the \(i\)-th segment.Your task is to choose the maximum by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.Two segments \([l_i; r_i]\) and \([l_j; r_j]\) are non-intersecting if they have no common points. For example, segments \([1; 2]\) and \([3; 4]\), \([1; 3]\) and \([5; 5]\) are non-intersecting, while segments \([1; 2]\) and \([2; 3]\), \([1; 2]\) and \([2; 2]\) are intersecting.The segment \([l_i; r_i]\) lies inside the segment \([l_j; r_j]\) if \(l_j \le l_i\) and \(r_i \le r_j\). For example, segments \([2; 2]\), \([2, 3]\), \([3; 4]\) and \([2; 4]\) lie inside the segment \([2; 4]\), while \([2; 5]\) and \([1; 4]\) are not.You have to answer \(t\) independent test cases.
|
The first line of the input contains one integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases. Then \(t\) test cases follow.The first line of the test case contains one integer \(n\) (\(1 \le n \le 3000\)) — the number of segments. The next \(n\) lines describe segments. The \(i\)-th segment is given as two integers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le 2 \cdot 10^5\)), where \(l_i\) is the left border of the \(i\)-th segment and \(r_i\) is the right border of the \(i\)-th segment.Additional constraint on the input: there are no duplicates in the list of segments.It is guaranteed that the sum of \(n\) does not exceed \(3000\) (\(\sum n \le 3000\)).
|
For each test case, print the answer: the maximum possible size of the subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.
|
Input: 4 4 1 5 2 4 2 3 3 4 5 1 5 2 3 2 5 3 5 2 2 3 1 3 2 4 2 3 7 1 10 2 8 2 5 3 4 4 4 6 8 7 7 | Output: 3 4 2 7
|
Expert
| 4 | 993 | 674 | 219 | 13 |
|
362 |
C
|
362C
|
C. Insertion Sort
| 1,900 |
data structures; dp; implementation; math
|
Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array a of size n in the non-decreasing order. for (int i = 1; i < n; i = i + 1){ int j = i; while (j > 0 && a[j] < a[j - 1]) { swap(a[j], a[j - 1]); // swap elements a[j] and a[j - 1] j = j - 1; }}Petya uses this algorithm only for sorting of arrays that are permutations of numbers from 0 to n - 1. He has already chosen the permutation he wants to sort but he first decided to swap some two of its elements. Petya wants to choose these elements in such a way that the number of times the sorting executes function swap, was minimum. Help Petya find out the number of ways in which he can make the swap and fulfill this requirement.It is guaranteed that it's always possible to swap two elements of the input permutation in such a way that the number of swap function calls decreases.
|
The first line contains a single integer n (2 ≤ n ≤ 5000) — the length of the permutation. The second line contains n different integers from 0 to n - 1, inclusive — the actual permutation.
|
Print two integers: the minimum number of times the swap function is executed and the number of such pairs (i, j) that swapping the elements of the input permutation with indexes i and j leads to the minimum number of the executions.
|
In the first sample the appropriate pairs are (0, 3) and (0, 4). In the second sample the appropriate pairs are (0, 4), (1, 4), (2, 4) and (3, 4).
|
Input: 54 0 3 1 2 | Output: 3 2
|
Hard
| 4 | 1,072 | 189 | 233 | 3 |
1,032 |
G
|
1032G
|
G. Chattering
| 2,900 |
There are \(n\) parrots standing in a circle. Each parrot has a certain level of respect among other parrots, namely \(r_i\). When a parrot with respect level \(x\) starts chattering, \(x\) neighbours to the right and to the left of it start repeating the same words in 1 second. Their neighbours then start repeating as well, and so on, until all the birds begin to chatter.You are given the respect levels of all parrots. For each parrot answer a question: if this certain parrot starts chattering, how many seconds will pass until all other birds will start repeating it?
|
In the first line of input there is a single integer \(n\), the number of parrots (\(1 \leq n \leq 10^5\)).In the next line of input there are \(n\) integers \(r_1\), ..., \(r_n\), the respect levels of parrots in order they stand in the circle (\(1 \leq r_i \leq n\)).
|
Print \(n\) integers. \(i\)-th of them should equal the number of seconds that is needed for all parrots to start chattering if the \(i\)-th parrot is the first to start.
|
Input: 4 1 1 4 1 | Output: 2 2 1 2
|
Master
| 0 | 574 | 269 | 170 | 10 |
||
1,085 |
G
|
1085G
|
G. Beautiful Matrix
| 2,900 |
combinatorics; data structures; dp
|
Petya collects beautiful matrix.A matrix of size \(n \times n\) is beautiful if: All elements of the matrix are integers between \(1\) and \(n\); For every row of the matrix, all elements of this row are different; For every pair of vertically adjacent elements, these elements are different. Today Petya bought a beautiful matrix \(a\) of size \(n \times n\), and now he wants to determine its rarity.The rarity of the matrix is its index in the list of beautiful matrices of size \(n \times n\), sorted in lexicographical order. Matrix comparison is done row by row. (The index of lexicographically smallest matrix is zero).Since the number of beautiful matrices may be huge, Petya wants you to calculate the rarity of the matrix \(a\) modulo \(998\,244\,353\).
|
The first line contains one integer \(n\) (\(1 \le n \le 2000\)) — the number of rows and columns in \(a\).Each of the next \(n\) lines contains \(n\) integers \(a_{i,j}\) (\(1 \le a_{i,j} \le n\)) — the elements of \(a\).It is guaranteed that \(a\) is a beautiful matrix.
|
Print one integer — the rarity of matrix \(a\), taken modulo \(998\,244\,353\).
|
There are only \(2\) beautiful matrices of size \(2 \times 2\): There are the first \(5\) beautiful matrices of size \(3 \times 3\) in lexicographical order:
|
Input: 2 2 1 1 2 | Output: 1
|
Master
| 3 | 763 | 272 | 79 | 10 |
1,288 |
D
|
1288D
|
D. Minimax Problem
| 2,000 |
binary search; bitmasks; dp
|
You are given \(n\) arrays \(a_1\), \(a_2\), ..., \(a_n\); each array consists of exactly \(m\) integers. We denote the \(y\)-th element of the \(x\)-th array as \(a_{x, y}\).You have to choose two arrays \(a_i\) and \(a_j\) (\(1 \le i, j \le n\), it is possible that \(i = j\)). After that, you will obtain a new array \(b\) consisting of \(m\) integers, such that for every \(k \in [1, m]\) \(b_k = \max(a_{i, k}, a_{j, k})\).Your goal is to choose \(i\) and \(j\) so that the value of \(\min \limits_{k = 1}^{m} b_k\) is maximum possible.
|
The first line contains two integers \(n\) and \(m\) (\(1 \le n \le 3 \cdot 10^5\), \(1 \le m \le 8\)) — the number of arrays and the number of elements in each array, respectively.Then \(n\) lines follow, the \(x\)-th line contains the array \(a_x\) represented by \(m\) integers \(a_{x, 1}\), \(a_{x, 2}\), ..., \(a_{x, m}\) (\(0 \le a_{x, y} \le 10^9\)).
|
Print two integers \(i\) and \(j\) (\(1 \le i, j \le n\), it is possible that \(i = j\)) — the indices of the two arrays you have to choose so that the value of \(\min \limits_{k = 1}^{m} b_k\) is maximum possible. If there are multiple answers, print any of them.
|
Input: 6 5 5 0 3 1 2 1 8 9 1 3 1 2 3 4 5 9 1 0 3 7 2 3 0 6 3 6 4 1 7 0 | Output: 1 5
|
Hard
| 3 | 541 | 357 | 264 | 12 |
|
1,336 |
B
|
1336B
|
B. Xenia and Colorful Gems
| 1,700 |
binary search; greedy; math; sortings; two pointers
|
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought \(n_r\) red gems, \(n_g\) green gems and \(n_b\) blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are \(x\), \(y\) and \(z\), Xenia wants to find the minimum value of \((x-y)^2+(y-z)^2+(z-x)^2\). As her dear friend, can you help her?
|
The first line contains a single integer \(t\) (\(1\le t \le 100\)) — the number of test cases. Then \(t\) test cases follow.The first line of each test case contains three integers \(n_r,n_g,n_b\) (\(1\le n_r,n_g,n_b\le 10^5\)) — the number of red gems, green gems and blue gems respectively.The second line of each test case contains \(n_r\) integers \(r_1,r_2,\ldots,r_{n_r}\) (\(1\le r_i \le 10^9\)) — \(r_i\) is the weight of the \(i\)-th red gem.The third line of each test case contains \(n_g\) integers \(g_1,g_2,\ldots,g_{n_g}\) (\(1\le g_i \le 10^9\)) — \(g_i\) is the weight of the \(i\)-th green gem.The fourth line of each test case contains \(n_b\) integers \(b_1,b_2,\ldots,b_{n_b}\) (\(1\le b_i \le 10^9\)) — \(b_i\) is the weight of the \(i\)-th blue gem.It is guaranteed that \(\sum n_r \le 10^5\), \(\sum n_g \le 10^5\), \(\sum n_b \le 10^5\) (the sum for all test cases).
|
For each test case, print a line contains one integer — the minimum value which Xenia wants to find.
|
In the first test case, Xenia has the following gems:If she picks the red gem with weight \(7\), the green gem with weight \(6\), and the blue gem with weight \(4\), she will achieve the most balanced selection with \((x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14\).
|
Input: 5 2 2 3 7 8 6 3 3 1 4 1 1 1 1 1 1000000000 2 2 2 1 2 5 4 6 7 2 2 2 1 2 3 4 6 7 3 4 1 3 2 1 7 3 3 4 6 | Output: 14 1999999996000000002 24 24 14
|
Medium
| 5 | 638 | 891 | 100 | 13 |
628 |
E
|
628E
|
E. Zbazi in Zeydabad
| 2,300 |
data structures; implementation
|
A tourist wants to visit country Zeydabad for Zbazi (a local game in Zeydabad).The country Zeydabad is a rectangular table consisting of n rows and m columns. Each cell on the country is either 'z' or '.'.The tourist knows this country is named Zeydabad because there are lots of ''Z-pattern""s in the country. A ''Z-pattern"" is a square which anti-diagonal is completely filled with 'z' and its upper and lower rows are also completely filled with 'z'. All other cells of a square can be arbitrary. Note that a ''Z-pattern"" can consist of only one cell (see the examples).So he wants to count the number of ''Z-pattern""s in the country (a necessary skill for Zbazi).Now your task is to help tourist with counting number of ''Z-pattern""s.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
|
The first line contains two integers n, m (1 ≤ n, m ≤ 3000) — the number of rows and columns respectively.Each of the next n lines contains m characters 'z' or '.' — the description of Zeydabad.
|
Print the only integer a — the number of ''Z-pattern""s in Zeydabad.
|
Input: 4 4zzzzzzz..z..zzzz | Output: 16
|
Expert
| 2 | 990 | 194 | 68 | 6 |
|
1,805 |
B
|
1805B
|
B. The String Has a Target
| 800 |
greedy; strings
|
You are given a string \(s\). You can apply this operation to the string exactly once: choose index \(i\) and move character \(s_i\) to the beginning of the string (removing it at the old position). For example, if you apply the operation with index \(i=4\) to the string ""abaacd"" with numbering from \(1\), you get the string ""aabacd"". What is the lexicographically minimal\(^{\dagger}\) string you can obtain by this operation?\(^{\dagger}\)A string \(a\) is lexicographically smaller than a string \(b\) of the same length if and only if the following holds: in the first position where \(a\) and \(b\) differ, the string \(a\) has a letter that appears earlier in the alphabet than the corresponding letter in \(b\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10 ^ 5\)) — the length of the string.The second line of each test case contains the string \(s\) of length \(n\), consisting of lowercase English letters.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10 ^ 5\).
|
For each test case, on a separate line print the lexicographically smallest string that can be obtained after applying the operation to the original string exactly once.
|
In the first test case, you need to move the last character to the beginning.In the second case, you need to move the second letter ""a"".In the third set you need to apply the operation with \(i=1\), then the string will not change.
|
Input: 43cba4acac5abbcb4aaba | Output: acb aacc abbcb aaab
|
Beginner
| 2 | 724 | 481 | 169 | 18 |
1,861 |
A
|
1861A
|
A. Prime Deletion
| 800 |
constructive algorithms; math
|
A prime number is a positive integer that has exactly two different positive divisors: \(1\) and the integer itself. For example, \(2\), \(3\), \(13\) and \(101\) are prime numbers; \(1\), \(4\), \(6\) and \(42\) are not.You are given a sequence of digits from \(1\) to \(9\), in which every digit from \(1\) to \(9\) appears exactly once.You are allowed to do the following operation several (maybe zero) times: choose any digit from the sequence and delete it. However, you cannot perform this operation if the sequence consists of only two digits.Your goal is to obtain a sequence which represents a prime number. Note that you cannot reorder the digits in the sequence.Print the resulting sequence, or report that it is impossible to perform the operations so that the resulting sequence is a prime number.
|
The first line contains one integer \(t\) (\(1 \le t \le 5000\)) — the number of test cases.Each test case consists of one line containing a string of \(9\) digits (without any characters between them). Each digit from \(1\) to \(9\) appears in this string exactly once.
|
For each test case, print the answer on a separate line as follows: if it is impossible to perform the described operations, print \(-1\); otherwise, print any sequence that represents a prime number, which can be obtained from the given string performing several (maybe zero) operations described in the statement. If there are multiple such sequences, you can print any one of them.
|
Input: 4123456789987654321243567918576318429 | Output: 167 53 3571 57638429
|
Beginner
| 2 | 810 | 270 | 384 | 18 |
|
1,540 |
D
|
1540D
|
D. Inverse Inversions
| 3,200 |
binary search; brute force; data structures
|
You were playing with permutation \(p\) of length \(n\), but you lost it in Blair, Alabama!Luckily, you remember some information about the permutation. More specifically, you remember an array \(b\) of length \(n\), where \(b_i\) is the number of indices \(j\) such that \(j < i\) and \(p_j > p_i\).You have the array \(b\), and you want to find the permutation \(p\). However, your memory isn't perfect, and you constantly change the values of \(b\) as you learn more. For the next \(q\) seconds, one of the following things happen: \(1\) \(i\) \(x\) — you realize that \(b_i\) is equal to \(x\); \(2\) \(i\) — you need to find the value of \(p_i\). If there's more than one answer, print any. It can be proven that there's always at least one possible answer under the constraints of the problem. Answer the queries, so you can remember the array!
|
The first line contains a single integer \(n\) (\(1 \leq n \leq 10^5\)) — the size of permutation.The second line contains \(n\) integers \(b_1, b_2 \ldots, b_n\) (\(0 \leq b_i < i\)) — your initial memory of the array \(b\).The third line contains a single integer \(q\) (\(1 \leq q \leq 10^5\)) — the number of queries.The next \(q\) lines contain the queries, each with one of the following formats: \(1\) \(i\) \(x\) (\(0 \leq x < i \leq n\)), representing a query of type \(1\). \(2\) \(i\) (\(1 \leq i \leq n\)), representing a query of type \(2\). It is guaranteed that there's at least one query of type \(2\).
|
For each query of type \(2\), print one integer — the answer to the query.
|
For the first sample, there's initially only one possible permutation that satisfies the constraints: \([1, 2, 3]\), as it must have \(0\) inversions.After the query of type \(1\), the array \(b\) is \([0, 1, 0]\). The only permutation \(p\) that produces this array is \([2, 1, 3]\). With this permutation, \(b_2\) is equal to \(1\) as \(p_1 > p_2\).
|
Input: 3 0 0 0 7 2 1 2 2 2 3 1 2 1 2 1 2 2 2 3 | Output: 1 2 3 2 1 3
|
Master
| 3 | 850 | 618 | 74 | 15 |
1,431 |
F
|
1431F
|
F. Neural Network Problem
| 2,100 |
*special; binary search; greedy
|
You want to train a neural network model for your graduation work. There are \(n\) images in the dataset, the \(i\)-th image's size is \(a_i\) bytes.You don't have any powerful remote servers to train this model so you have to do it on your local machine. But there is a problem: the total size of the dataset is too big for your machine, so you decided to remove some images — though you don't want to make the dataset too weak so you can remove no more than \(k\) images from it. Note that you can only remove images, you can't change their order.You want to remove these images optimally so you came up with a metric (you're a data scientist after all) that allows to measure the result of removals. Consider the array \(b_1, b_2, \ldots, b_m\) after removing at most \(k\) images (\(n - k \le m \le n\)). The data from this array will be uploaded to the machine in blocks of \(x\) consecutive elements each. More precisely: elements with indices from \(1\) to \(x\) (\(b_1, b_2, \ldots, b_x\)) belong to the first block; elements with indices from \(x + 1\) to \(2x\) (\(b_{x + 1}, b_{x + 2}, \ldots, b_{2x}\)) belong to the second block; elements with indices from \(2x + 1\) to \(3x\) (\(b_{2x + 1}, b_{2x + 2}, \ldots, b_{3x}\)) belong to the third block; and so on. There will be \(cnt = \left\lceil\frac{m}{x}\right\rceil\) blocks in total. Note that if \(m\) is not divisible by \(x\) then the last block contains less than \(x\) elements, and it's okay.Let \(w(i)\) be the total size of the \(i\)-th block — that is, the sum of sizes of images inside this block. For example, the size of the first block \(w(1)\) is \(b_1 + b_2 + \ldots + b_x\), the size of the second block \(w(2)\) is \(b_{x + 1} + b_{x + 2} + \ldots + b_{2x}\).The value of the metric you came up with is the maximum block size over the blocks of the resulting dataset. In other words, the value of the metric is \(\max\limits_{i=1}^{cnt} w(i)\).You don't want to overload your machine too much, so you have to remove at most \(k\) images in a way that minimizes the value of the metric described above.
|
The first line of the input contains three integers \(n\), \(k\) and \(x\) (\(1 \le n \le 10^5\); \(1 \le k, x \le n\)) — the number of images in the dataset, the maximum number of images you can remove and the length of each block (except maybe for the last one), respectively.The second line of the input contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^5\)), where \(a_i\) is the size of the \(i\)-th image.
|
Print one integer: the minimum possible value of the metric described in the problem statement after removing no more than \(k\) images from the dataset.
|
In the first example, you can remove the whole array so the answer is \(0\).In the second example, you can remove the first and the last elements of \(a\) and obtain \(b = [1, 5, 5]\). The size of the first (and the only) block is \(11\). So the answer is \(11\).In the third example, you can remove the second element of \(a\) and obtain \(b = [3, 1, 3, 1, 2]\). The size of the first block is \(8\) and the size of the second block is \(2\). So the answer is \(8\).In the fourth example, you can keep the array \(a\) unchanged and obtain \(b = [2, 2, 1, 2, 2, 1]\). The size of the first block is \(5\) as well as the size of the second block. So the answer is \(5\).
|
Input: 5 5 4 1 1 5 4 5 | Output: 0
|
Hard
| 3 | 2,084 | 431 | 153 | 14 |
1,970 |
F3
|
1970F3
|
F3. Playing Quidditch (Hard)
| 2,300 |
implementation
|
This afternoon, you decided to enjoy the first days of Spring by taking a walk outside. As you come near the Quidditch field, you hear screams. Once again, there is a conflict about the score: the two teams are convinced that they won the game! To prevent this problem from happening one more time, you decide to get involved in the refereeing of the matches.Now, you will stay in the stadium to watch the game and count the score. At the end of the game, you will decide the winner.Today, two teams are competing: the red Gryffindor (R) and the blue Ravenclaw (B) team. Each team is composed of \(P\) players (\(1 \leq P \leq 10\)).The field is a rectangle of \(N\) lines and \(M\) columns (\(3 \leq N, M \leq 99\), \(N\) and \(M\) are odd). All the positions are integers, and several entities are allowed to be at the same position in the field. At the beginning of the game, the field contains goals for the two teams (each team can own between one and five goals), the players, and exactly one Quaffle. In this version of the problem, one Bludger and a Golden Snitch can be present.A game is composed of \(T\) steps (\(0 \leq T \leq 10000\)). At each step, one entity on the field (a player or a ball) performs one action. All entities can move. A player can also catch a ball or throw the Quaffle that it is carrying. To catch a ball, a player must be located on the same cell as it. The Quaffle does not perform any action while it is being carried; it only follows the movements of the player. If a player carrying the Quaffle decides to throw it, the Quaffle is simply put at the current position of the player. If a player is on the same cell as a Bludger (either after a movement from the player or the Bludger), the player is eliminated. If the player is eliminated while it is carrying the Quaffle, the Quaffle remains on the cell containing both the player and the Bludger after the move. It is guaranteed that this never occurs while the player is in a cell containing a goal.To win a point, a player must leave the Quaffle at a goal of the other team. When it does, the team of the player wins one point, and the Quaffle instantly moves to the middle of the field (the cell at the \((M+1)/2\)-th column of the \((N+1)/2\)-th line of the field, starting from 1). There is no goal in the middle of the field. If a player puts the ball in its own goal, the other team wins the point. If a player catches the Golden Snitch, their team wins 10 points and the game is over.
|
On the first line, the integers \(N\) and \(M\).The description of the field follows: \(N\) lines of \(M\) pairs of characters separated by spaces. Each pair of characters represents a position on the field. It can be either: .. to represent an empty cell R0, ..., R9, B0, ..., B9 to represent a player. The first character is the team of the player, and the second is the number of the player in the team. Each pair of characters is unique, but it is not guaranteed that all the pairs appear in the grid. RG or BG to represent a goal. The blue team tries to put the ball in a red goal (RG) while the red team tries to put the ball in a blue goal (BG). .Q to represent the Quaffle, which is the ball that the players use to score goals. .B to represent the Bludger. .S to represent the Golden Snitch. The next line contains \(T\), the number of steps that compose the game. \(T\) lines follow, each describing one action. It contains several pieces of information separated by a space. First, a pair of characters representing the entity that must perform the action. Second, the description of the action: U, D, L, R indicate that the entity moves on the grid. It can move to the top of the grid (U), to the bottom (D), to the left (L), or to the right (R). Each entity moves by only one cell at a time. C indicates that the player catches the ball (only a player can catch a ball). Then, there is a space followed by a pair of characters: the description of the ball caught by the player. This information is needed since several balls can be in the same cell. T indicates that the player throws the Quaffle that it is carrying. All the actions performed by the entities are guaranteed to be valid: the players stay in the field, don't catch a ball if they are not in the same cell, don't release the Quaffle if they are not carrying it, ...
|
You must output the description of the main events of the game, one event per line. More precisely: Each time a team scores, you must print t RED GOAL or t BLUE GOAL, depending on the team who scored, where t is the current time (the position of the action in the list of actions, starting from 0). In the case where a player scores in the wrong goal (a red player scores in the red goal, or a blue player scores in the blue goal), you must print the name of the team who wins one point, that is, the other team. Each time a player is eliminated, you must print t p ELIMINATED, where t is the current time and p is the player who is eliminated. The format to print the player is the same as in the input. If the Golden Snitch is caught, you must print t RED CATCH GOLDEN SNITCH or t BLUE CATCH GOLDEN SNITCH, depending on the team who caught the Golden Snitch, where t is the current time. The events must be printed in ascending order of t. If several players are eliminated at the same time, the events must be written is alphabetical order: B0, ..., B9, R0, ... R9.At the end of the game, you must print the final score as: FINAL SCORE: r b, where r is the score of the red team and b is the score of the blue team.
|
In the first example, the red player takes the Quaffle, move it and throw it. The blue player catches the ball, goes to the red goal and scores.In the second example, the red player takes the ball and scores in the goal of their own team: the blue team wins a point.In the third example, the Bludger goes at the position of R0: R0 is eliminated. Then, B0 moves to the position of the Bludger: B0 is eliminated too.In the fourth example, a red player catches the Golden Snitch. Their team wins 10 points, and the game ends.You can find one more example in the easy version of the problem
|
Input: 3 5.. .. R0 .. ..RG .. .Q .. BG.. .. B0 .. ..12R0 DR0 C .QR0 RR0 TR0 DB0 RB0 UB0 C .QB0 LB0 LB0 LB0 T | Output: 11 BLUE GOAL FINAL SCORE: 0 1
|
Expert
| 1 | 2,483 | 1,843 | 1,218 | 19 |
1,041 |
D
|
1041D
|
D. Glider
| 1,700 |
binary search; data structures; two pointers
|
A plane is flying at a constant height of \(h\) meters above the ground surface. Let's consider that it is flying from the point \((-10^9, h)\) to the point \((10^9, h)\) parallel with \(Ox\) axis.A glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may start only when the plane's coordinates are integers). After jumping from the plane, he will fly in the same direction as the plane, parallel to \(Ox\) axis, covering a unit of distance every second. Naturally, he will also descend; thus his second coordinate will decrease by one unit every second.There are ascending air flows on certain segments, each such segment is characterized by two numbers \(x_1\) and \(x_2\) (\(x_1 < x_2\)) representing its endpoints. No two segments share any common points. When the glider is inside one of such segments, he doesn't descend, so his second coordinate stays the same each second. The glider still flies along \(Ox\) axis, covering one unit of distance every second. If the glider jumps out at \(1\), he will stop at \(10\). Otherwise, if he jumps out at \(2\), he will stop at \(12\). Determine the maximum distance along \(Ox\) axis from the point where the glider's flight starts to the point where his flight ends if the glider can choose any integer coordinate to jump from the plane and start his flight. After touching the ground the glider stops altogether, so he cannot glide through an ascending airflow segment if his second coordinate is \(0\).
|
The first line contains two integers \(n\) and \(h\) \((1 \le n \le 2\cdot10^{5}, 1 \le h \le 10^{9})\) — the number of ascending air flow segments and the altitude at which the plane is flying, respectively.Each of the next \(n\) lines contains two integers \(x_{i1}\) and \(x_{i2}\) \((1 \le x_{i1} < x_{i2} \le 10^{9})\) — the endpoints of the \(i\)-th ascending air flow segment. No two segments intersect, and they are given in ascending order.
|
Print one integer — the maximum distance along \(Ox\) axis that the glider can fly from the point where he jumps off the plane to the point where he lands if he can start his flight at any integer coordinate.
|
In the first example if the glider can jump out at \((2, 4)\), then the landing point is \((12, 0)\), so the distance is \(12-2 = 10\).In the second example the glider can fly from \((16,10)\) to \((34,0)\), and the distance is \(34-16=18\).In the third example the glider can fly from \((-100,1000000000)\) to \((1999999899,0)\), so the distance is \(1999999899-(-100)=1999999999\).
|
Input: 3 42 57 910 11 | Output: 10
|
Medium
| 3 | 1,523 | 449 | 208 | 10 |
62 |
B
|
62B
|
B. Tyndex.Brome
| 1,800 |
binary search; implementation
|
Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck!
|
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105.
|
On each n line of the output file print a single number: the value of the error function when the current potential address is chosen.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
|
Input: 2 10codeforcescodeforcescodehorses | Output: 012
|
Medium
| 2 | 1,685 | 463 | 265 | 0 |
|
501 |
D
|
501D
|
D. Misha and Permutations Summation
| 2,000 |
data structures
|
Let's define the sum of two permutations p and q of numbers 0, 1, ..., (n - 1) as permutation , where Perm(x) is the x-th lexicographically permutation of numbers 0, 1, ..., (n - 1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.For example, Perm(0) = (0, 1, ..., n - 2, n - 1), Perm(n! - 1) = (n - 1, n - 2, ..., 1, 0)Misha has two permutations, p and q. Your task is to find their sum.Permutation a = (a0, a1, ..., an - 1) is called to be lexicographically smaller than permutation b = (b0, b1, ..., bn - 1), if for some k following conditions hold: a0 = b0, a1 = b1, ..., ak - 1 = bk - 1, ak < bk.
|
The first line contains an integer n (1 ≤ n ≤ 200 000).The second line contains n distinct integers from 0 to n - 1, separated by a space, forming permutation p.The third line contains n distinct integers from 0 to n - 1, separated by spaces, forming permutation q.
|
Print n distinct integers from 0 to n - 1, forming the sum of the given permutations. Separate the numbers by spaces.
|
Permutations of numbers from 0 to 1 in the lexicographical order: (0, 1), (1, 0).In the first sample Ord(p) = 0 and Ord(q) = 0, so the answer is .In the second sample Ord(p) = 0 and Ord(q) = 1, so the answer is .Permutations of numbers from 0 to 2 in the lexicographical order: (0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0).In the third sample Ord(p) = 3 and Ord(q) = 5, so the answer is .
|
Input: 20 10 1 | Output: 0 1
|
Hard
| 1 | 646 | 265 | 117 | 5 |
2,039 |
H2
|
2039H2
|
H2. Cool Swap Walk (Hard Version)
| 3,500 |
constructive algorithms; constructive algorithms; constructive algorithms; implementation; sortings
|
This is the hard version of the problem. The only difference is the maximum number of operations you can perform. You can only make hacks if both versions are solved.You are given an array \(a\) of size \(n\).A cool swap walk is the following process: In an \(n \times n\) grid, we note the cells in row \(i\) and column \(j\) as \((i, j)\). You need to walk from \((1,1)\) to \((n,n)\), taking only steps to the right or down. Formally, if you are in \((x,y)\) currently, you can step to either \((x+1,y)\) or \((x,y+1)\), but you can not step beyond the boundaries of the grid. When you step in \((i,j)\), you must swap \(a_i\) and \(a_j\) when \(i \neq j\).You can perform at most \(n+4\) cool swap walks. Sort the array \(a_1, a_2, \ldots, a_n\) in non-decreasing order. We can show that it's always possible to do so.
|
The first line contains an integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.The first line of each test case contains an integer \(n\) (\(2 \leq n \leq 500\)) — the size of the array.The second line of each test case contains \(n\) integers \(a_1,a_2,\ldots ,a_n\) (\(1 \le a_i \le n\)) — the elements of the array.It is guaranteed that the sum of \(n^2\) over all test cases does not exceed \(2.5 \cdot 10^5\).
|
For each test case, your output should consist of several lines: The first line contains an integer \(k\) (\(0 \leq k \leq n+4\)), representing the number of cool swap walks you perform. Each of the next \(k\) lines contains a string \(s\) of length \(2n-2\) consisting only of R and D, representing the path (letters are case sensitive). For all \(1 \le i \le 2n-2\), if \(s_i=\) R, you walk right in the \(i\)-th step, otherwise you walk down in the \(i\)-th step.
|
In the first test case, the array \(a\) is already non-decreasing, so you don't need to perform any walk.In the second test case, \(a=[2,1,3]\) initially.In the first walk: In the \(1\)-st step, you step right to \((1,2)\). Then, \(a=[1,2,3]\). Note that although the array \(a\) is already non-decreasing, you can not stop until you reach \((n,n)\). In the \(2\)-nd step, you step right to \((1,3)\). Then, \(a=[3,2,1]\). In the \(3\)-rd step, you step down to \((2,3)\). Then, \(a=[3,1,2]\). In the \(4\)-th step, you step down to \((3,3)\). Then, \(a=[3,1,2]\).In the second walk: In the \(1\)-st step, you step down to \((2,1)\). Then, \(a=[1,3,2]\). In the \(2\)-nd step, you step right to \((2,2)\). Then, \(a=[1,3,2]\). In the \(3\)-rd step, you step down to \((3,2)\). Then, \(a=[1,2,3]\). In the \(4\)-th step, you step down to \((3,3)\). Then, \(a=[1,2,3]\).After the two cool swap walks above, we get \(a=[1,2,3]\), which is non-decreasing.
|
Input: 321 232 1 343 2 3 4 | Output: 0 2 RRDD DRDR 3 RRDRDD DRDDRR DDRRRD
|
Master
| 5 | 822 | 426 | 466 | 20 |
774 |
C
|
774C
|
C. Maximum Number
| 1,200 |
*special; constructive algorithms; greedy; implementation
|
Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below. So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted. The battery of the newest device allows to highlight at most n sections on the display. Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer.
|
The first line contains the integer n (2 ≤ n ≤ 100 000) — the maximum number of sections which can be highlighted on the display.
|
Print the maximum integer which can be shown on the display of Stepan's newest device.
|
Input: 2 | Output: 1
|
Easy
| 4 | 679 | 129 | 86 | 7 |
|
1,742 |
D
|
1742D
|
D. Coprime
| 1,100 |
brute force; greedy; number theory
|
Given an array of \(n\) positive integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 1000\)). Find the maximum value of \(i + j\) such that \(a_i\) and \(a_j\) are coprime,\(^{\dagger}\) or \(-1\) if no such \(i\), \(j\) exist.For example consider the array \([1, 3, 5, 2, 4, 7, 7]\). The maximum value of \(i + j\) that can be obtained is \(5 + 7\), since \(a_5 = 4\) and \(a_7 = 7\) are coprime.\(^{\dagger}\) Two integers \(p\) and \(q\) are coprime if the only positive integer that is a divisor of both of them is \(1\) (that is, their greatest common divisor is \(1\)).
|
The input consists of multiple test cases. The first line contains an integer \(t\) (\(1 \leq t \leq 10\)) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer \(n\) (\(2 \leq n \leq 2\cdot10^5\)) — the length of the array.The following line contains \(n\) space-separated positive integers \(a_1\), \(a_2\),..., \(a_n\) (\(1 \leq a_i \leq 1000\)) — the elements of the array.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot10^5\).
|
For each test case, output a single integer — the maximum value of \(i + j\) such that \(i\) and \(j\) satisfy the condition that \(a_i\) and \(a_j\) are coprime, or output \(-1\) in case no \(i\), \(j\) satisfy the condition.
|
For the first test case, we can choose \(i = j = 3\), with sum of indices equal to \(6\), since \(1\) and \(1\) are coprime.For the second test case, we can choose \(i = 7\) and \(j = 5\), with sum of indices equal to \(7 + 5 = 12\), since \(7\) and \(4\) are coprime.
|
Input: 633 2 171 3 5 2 4 7 751 2 3 4 532 2 465 4 3 15 12 1651 2 2 3 6 | Output: 6 12 9 -1 10 7
|
Easy
| 3 | 574 | 536 | 226 | 17 |
1,444 |
C
|
1444C
|
C. Team-Building
| 2,500 |
data structures; dfs and similar; dsu; graphs
|
The new academic year has started, and Berland's university has \(n\) first-year students. They are divided into \(k\) academic groups, however, some of the groups might be empty. Among the students, there are \(m\) pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.Alice is the curator of the first years, she wants to host an entertaining game to make everyone know each other. To do that, she will select two different academic groups and then divide the students of those groups into two teams. The game requires that there are no acquaintance pairs inside each of the teams.Alice wonders how many pairs of groups she can select, such that it'll be possible to play a game after that. All students of the two selected groups must take part in the game.Please note, that the teams Alice will form for the game don't need to coincide with groups the students learn in. Moreover, teams may have different sizes (or even be empty).
|
The first line contains three integers \(n\), \(m\) and \(k\) (\(1 \le n \le 500\,000\); \(0 \le m \le 500\,000\); \(2 \le k \le 500\,000\)) — the number of students, the number of pairs of acquaintances and the number of groups respectively.The second line contains \(n\) integers \(c_1, c_2, \dots, c_n\) (\(1 \le c_i \le k\)), where \(c_i\) equals to the group number of the \(i\)-th student.Next \(m\) lines follow. The \(i\)-th of them contains two integers \(a_i\) and \(b_i\) (\(1 \le a_i, b_i \le n\)), denoting that students \(a_i\) and \(b_i\) are acquaintances. It's guaranteed, that \(a_i \neq b_i\), and that no (unordered) pair is mentioned more than once.
|
Print a single integer — the number of ways to choose two different groups such that it's possible to select two teams to play the game.
|
The acquaintances graph for the first example is shown in the picture below (next to each student there is their group number written).In that test we can select the following groups: Select the first and the second groups. For instance, one team can be formed from students \(1\) and \(4\), while other team can be formed from students \(2\) and \(3\). Select the second and the third group. For instance, one team can be formed \(3\) and \(6\), while other team can be formed from students \(4\) and \(5\). We can't select the first and the third group, because there is no way to form the teams for the game. In the second example, we can select any group pair. Please note, that even though the third group has no students, we still can select it (with some other group) for the game.
|
Input: 6 8 3 1 1 2 2 3 3 1 3 1 5 1 6 2 5 2 6 3 4 3 5 5 6 | Output: 2
|
Expert
| 4 | 994 | 670 | 136 | 14 |
1,178 |
H
|
1178H
|
H. Stock Exchange
| 3,500 |
binary search; flows; graphs
|
Warning: This problem has an unusual memory limit!Bob decided that he will not waste his prime years implementing GUI forms for a large corporation and instead will earn his supper on the Stock Exchange Reykjavik. The Stock Exchange Reykjavik is the only actual stock exchange in the world. The only type of transaction is to take a single share of stock \(x\) and exchange it for a single share of stock \(y\), provided that the current price of share \(x\) is at least the current price of share \(y\). There are \(2n\) stocks listed on the SER that are of interest to Bob, numbered from \(1\) to \(2n\). Bob owns a single share of stocks \(1\) through \(n\) and would like to own a single share of each of \(n+1\) through \(2n\) some time in the future.Bob managed to forecast the price of each stock — in time \(t \geq 0\), the stock \(i\) will cost \(a_i \cdot \lfloor t \rfloor + b_i\). The time is currently \(t = 0\). Help Bob find the earliest moment in time in which he can own a single share of each of \(n+1\) through \(2n\), and the minimum number of stock exchanges he has to perform in order to do that.You may assume that the Stock Exchange has an unlimited amount of each stock at any point in time.
|
The first line contains a single integer \(n\) (\(1 \leq n \leq 2200\)) — the number stocks currently owned by Bob.Each of the next \(2n\) lines contains integers \(a_i\) and \(b_i\) (\(0 \leq a_i, b_i \leq 10^9\)), representing the stock price of stock \(i\).
|
If it is impossible for Bob to achieve his goal, output a single integer \(-1\).Otherwise, output two integers \(T\) and \(E\), where \(T\) is the minimum time in which he can achieve his goal, and \(E\) is the minimum number of exchanges in which he can achieve his goal at time \(T\).
|
In the first example, Bob simply waits until time \(t = 3\), when both stocks cost exactly the same amount.In the second example, the optimum strategy is to exchange stock \(2\) for stock \(1\) at time \(t = 1\), then exchange one share of stock \(1\) for stock \(3\) at time \(t = 5\) (where both cost \(15\)) and then at time \(t = 6\) exchange the second on for the stock number \(4\) (when they cost \(18\) and \(17\), respectively). Note that he can achieve his goal also with only two exchanges, but this would take total time of \(t = 9\), when he would finally be able to exchange the share number \(2\) for the share number \(3\). In the third example, Bob can never achieve his goal, as the second stock is always strictly more expensive than the first one.
|
Input: 1 3 10 1 16 | Output: 3 1
|
Master
| 3 | 1,216 | 260 | 286 | 11 |
295 |
C
|
295C
|
C. Greg and Friends
| 2,100 |
combinatorics; dp; graphs; shortest paths
|
One day Greg and his friends were walking in the forest. Overall there were n people walking, including Greg. Soon he found himself in front of a river. The guys immediately decided to get across the river. Luckily, there was a boat by the river bank, just where the guys were standing. We know that the boat can hold people with the total weight of at most k kilograms.Greg immediately took a piece of paper and listed there the weights of all people in his group (including himself). It turned out that each person weights either 50 or 100 kilograms. Now Greg wants to know what minimum number of times the boat needs to cross the river to transport the whole group to the other bank. The boat needs at least one person to navigate it from one bank to the other. As the boat crosses the river, it can have any non-zero number of passengers as long as their total weight doesn't exceed k.Also Greg is wondering, how many ways there are to transport everybody to the other side in the minimum number of boat rides. Two ways are considered distinct if during some ride they have distinct sets of people on the boat.Help Greg with this problem.
|
The first line contains two integers n, k (1 ≤ n ≤ 50, 1 ≤ k ≤ 5000) — the number of people, including Greg, and the boat's weight limit. The next line contains n integers — the people's weights. A person's weight is either 50 kilos or 100 kilos.You can consider Greg and his friends indexed in some way.
|
In the first line print an integer — the minimum number of rides. If transporting everyone to the other bank is impossible, print an integer -1.In the second line print the remainder after dividing the number of ways to transport the people in the minimum number of rides by number 1000000007 (109 + 7). If transporting everyone to the other bank is impossible, print integer 0.
|
In the first test Greg walks alone and consequently, he needs only one ride across the river.In the second test you should follow the plan: transport two 50 kg. people; transport one 50 kg. person back; transport one 100 kg. person; transport one 50 kg. person back; transport two 50 kg. people. That totals to 5 rides. Depending on which person to choose at step 2, we can get two distinct ways.
|
Input: 1 5050 | Output: 11
|
Hard
| 4 | 1,142 | 304 | 378 | 2 |
14 |
D
|
14D
|
D. Two Paths
| 1,900 |
dfs and similar; dp; graphs; shortest paths; trees; two pointers
|
As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.
|
The first line contains an integer n (2 ≤ n ≤ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≤ ai, bi ≤ n).
|
Output the maximum possible profit.
|
Input: 41 22 33 4 | Output: 1
|
Hard
| 6 | 833 | 265 | 35 | 0 |
|
995 |
A
|
995A
|
A. Tesla
| 2,100 |
constructive algorithms; implementation
|
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with \(4\) rows and \(n\) (\(n \le 50\)) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having \(k\) (\(k \le 2n\)) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most \(20000\) times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
|
The first line of the input contains two space-separated integers \(n\) and \(k\) (\(1 \le n \le 50\), \(1 \le k \le 2n\)), representing the number of columns and the number of cars, respectively.The next four lines will contain \(n\) integers each between \(0\) and \(k\) inclusive, representing the initial state of the parking lot. The rows are numbered \(1\) to \(4\) from top to bottom and the columns are numbered \(1\) to \(n\) from left to right.In the first and last line, an integer \(1 \le x \le k\) represents a parking spot assigned to car \(x\) (you can only move this car to this place), while the integer \(0\) represents a empty space (you can't move any car to this place).In the second and third line, an integer \(1 \le x \le k\) represents initial position of car \(x\), while the integer \(0\) represents an empty space (you can move any car to this place).Each \(x\) between \(1\) and \(k\) appears exactly once in the second and third line, and exactly once in the first and fourth line.
|
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most \(20000\) car moves, then print \(m\), the number of moves, on the first line. On the following \(m\) lines, print the moves (one move per line) in the format \(i\) \(r\) \(c\), which corresponds to Allen moving car \(i\) to the neighboring space at row \(r\) and column \(c\).If it is not possible for Allen to move all the cars to the correct spaces with at most \(20000\) car moves, print a single line with the integer \(-1\).
|
In the first sample test case, all cars are in front of their spots except car \(5\), which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most \(20000\) will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
|
Input: 4 51 2 0 41 2 0 45 0 0 30 5 0 3 | Output: 61 1 12 1 24 1 43 4 45 3 25 4 2
|
Hard
| 2 | 1,368 | 1,011 | 528 | 9 |
981 |
H
|
981H
|
H. K Paths
| 3,100 |
combinatorics; data structures; dp; fft; math
|
You are given a tree of \(n\) vertices. You are to select \(k\) (not necessarily distinct) simple paths in such a way that it is possible to split all edges of the tree into three sets: edges not contained in any path, edges that are a part of exactly one of these paths, and edges that are parts of all selected paths, and the latter set should be non-empty.Compute the number of ways to select \(k\) paths modulo \(998244353\).The paths are enumerated, in other words, two ways are considered distinct if there are such \(i\) (\(1 \leq i \leq k\)) and an edge that the \(i\)-th path contains the edge in one way and does not contain it in the other.
|
The first line contains two integers \(n\) and \(k\) (\(1 \leq n, k \leq 10^{5}\)) — the number of vertices in the tree and the desired number of paths.The next \(n - 1\) lines describe edges of the tree. Each line contains two integers \(a\) and \(b\) (\(1 \le a, b \le n\), \(a \ne b\)) — the endpoints of an edge. It is guaranteed that the given edges form a tree.
|
Print the number of ways to select \(k\) enumerated not necessarily distinct simple paths in such a way that for each edge either it is not contained in any path, or it is contained in exactly one path, or it is contained in all \(k\) paths, and the intersection of all paths is non-empty. As the answer can be large, print it modulo \(998244353\).
|
In the first example the following ways are valid: \(((1,2), (1,2))\), \(((1,2), (1,3))\), \(((1,3), (1,2))\), \(((1,3), (1,3))\), \(((1,3), (2,3))\), \(((2,3), (1,3))\), \(((2,3), (2,3))\). In the second example \(k=1\), so all \(n \cdot (n - 1) / 2 = 5 \cdot 4 / 2 = 10\) paths are valid.In the third example, the answer is \(\geq 998244353\), so it was taken modulo \(998244353\), don't forget it!
|
Input: 3 21 22 3 | Output: 7
|
Master
| 5 | 651 | 367 | 348 | 9 |
2,046 |
E1
|
2046E1
|
E1. Cheops and a Contest (Easy Version)
| 2,900 |
constructive algorithms; greedy
|
This is the easy version of the problem. The difference between the versions is that in this version, \(m\) equals \(2\). You can hack only if you solved all versions of this problem. There is a problem-solving competition in Ancient Egypt with \(n\) participants, numbered from \(1\) to \(n\). Each participant comes from a certain city; the cities are numbered from \(1\) to \(m\). There is at least one participant from each city.The \(i\)-th participant has strength \(a_i\), specialization \(s_i\), and wisdom \(b_i\), so that \(b_i \ge a_i\). Each problem in the competition will have a difficulty \(d\) and a unique topic \(t\). The \(i\)-th participant will solve the problem if \(a_i \ge d\), i.e., their strength is not less than the problem's difficulty, or \(s_i = t\), and \(b_i \ge d\), i.e., their specialization matches the problem's topic, and their wisdom is not less than the problem's difficulty. Cheops wants to choose the problems in such a way that each participant from city \(i\) will solve strictly more problems than each participant from city \(j\), for all \(i < j\).Please find a set of at most \(5n\) problems, where the topics of all problems are distinct, so that Cheops' will is satisfied, or state that it is impossible.
|
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\), \(m\) (\(2 \mathbf{=} m \le n \le 3 \cdot {10}^5\)) — the number of participants and the number of cities.The following \(n\) lines describe the participants. The \(i\)-th line contains three integers —\(a_i\), \(b_i\), \(s_i\) (\(0 \le a_i, b_i, s_i \le {10}^9\), \(a_i \le b_i\)) — strength, wisdom, and specialization of the \(i\)-th participant, respectively.The next \(m\) lines describe the cities. In the \(i\)-th line, the first number is an integer \(k_i\) (\(1 \le k_i \le n\)) — the number of participants from the \(i\)-th city. It is followed by \(k_i\) integers \(q_{i, 1}, q_{i, 2}, \ldots, q_{i, k_i}\) — (\(1 \le q_{i, j} \le n\), \(1 \le j \le k_i\)) — the indices of the participants from this city. It is guaranteed that each participant is mentioned exactly once.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(3 \cdot 10^5\).
|
For each test case, if there exists a set of problems that satisfies Cheops' conditions, then in the first line output a single integer \(p\) (\(1 \le p \le 5n\)) — the number of problems in your solution.Then output \(p\) lines, each containing two integers \(d\) and \(t\) (\(0 \le d, t \le {10}^9\)) — the difficulty and topic of the respective problem. The topics must be distinct.If there is no set of problems that meets Cheops' wishes, print \(-1\) instead.
|
Input: 25 25 7 16 7 23 9 25 10 34 4 12 1 23 3 4 52 21 2 11 2 11 21 1 | Output: 7 6 4 6 5 5 6 5 7 4 8 4 9 7 1 -1
|
Master
| 2 | 1,255 | 1,100 | 464 | 20 |
|
1,576 |
A
|
1576A
|
A. Communication Routing Challenge
| 0 |
*special
|
In optical communication networks, appropriate path planning can improve the utilization of communication resources and bring a smooth communication experience to users. The following figure shows an inter-satellite optical communication network. User messages are sent from one terrestrial base station (nodes \(4\) to \(7\)) and transmitted through satellites (nodes \(0\) to \(3\)) in space to another terrestrial base station (nodes \(4\) to \(7\)). In the preceding figures, there are communication connections (edges for short) between base stations and satellites and between satellites. The base stations and satellites are referred to as nodes. User messages are transmitted on these edges and referred to as flows. Some users may make video calls with friends, and some users may send short messages to their family members. Therefore, the message traffic (called flow rate) of each user differs. There are many parallel edges (for example, edges \(0\), \(1\), and \(2\)) between two nodes, and the capacity of each edge also differs. Larger capacity indicates that more user messages can be transmitted, as well as shorter transmission distance indicates lower latency and better communication quality. Nodes also have their internal structure. As shown below, some edges inside a node cannot communicate with each other because these edges (constrained edge pair) are not fully connected. For example, edge \(5\) and edge \(7\) inside node \(2\) cannot communicate with each other, and therefore flows cannot pass through node \(2\) by traversing the two unconnected edges. Now, in the input network, the source node, target node, and required flow rate for each user flow are specified. Because network resources are limited, paths may not be successfully calculated for all user flows. We hope that you can provide a solution with the highest score.Note, that all edges are undirected, so flows may come in both directions, edges has both capacity and length (named distance), several flows may use the same edge, flows may come through the same edge in opposite directions simultaneously, for the purpose of this problem, there is no difference between satellites and base stations, so flows may come through several base stations before reaching the destination station. Constraints The capacity of each edge is limited. The total rate of all flows carried by an edge cannot exceed the capacity of the edge. The capacity limits the total flows in both directions. The calculated flow path does not allow loops or cycles. Due to the hardware limitation inside satellites, the number of flows passing through a node (including source and target node) cannot exceed the site flow limit (\(\mathit{SFL}\)) of the node. The value of \(\mathit{SFL}\) is \(200\). There are multiple parallel edges between two nodes, which may belong to different groups. Links in each group are managed by the same chip on a node, and there is a group flow limit (\(\mathit{GFL}\)). The total number of different flows on all the edges in a group cannot exceed the \(\mathit{GFL}\) of the group. The value of \(\mathit{GFL}\) is \(100\). By default, all edges are connected to each other in each node. But there are some constrained edge pairs — the pairs of edges inside specified nodes that cannot communicate with each other. You can make no more than \(2\) submissions on each \(5\) minutes interval.
|
The first line contains four integers separated by space: \(\mathit{NodeCount}\), \(\mathit{EdgeCount}\), \(\mathit{ConstrainedCount}\), and \(\mathit{FlowCount}\). \(8 \le \mathit{NodeCount} \le 1400\), \(15 \le \mathit{EdgeCount} \le 15000\), \(3 \le \mathit{ConstrainedCount} \le 3600\), \(1 \le \mathit{FlowCount} \le 14000\). The next \(\mathit{EdgeCount}\) lines contain information about the network. Each line contains six integers: \(\mathit{EdgeID}\), \(\mathit{GroupID}\), \(\mathit{StartNodeID}\), \(\mathit{EndNodeID}\), \(\mathit{Distance}\), and \(\mathit{Capacity}\). \(0 \le \mathit{EdgeID} < \mathit{EdgeCount}\), \(0 \le \mathit{GroupID} \le 4500\), \(0 \le \mathit{StartNodeID}, \mathit{EndNodeID} < \mathit{NodeCount}\), \(\mathit{StartNodeID} \ne \mathit{EndNodeID}\), \(100 \le \mathit{Distance} \le 10000\), \(1 < \mathit{Capacity} \le 10^5\). It's guaranteed that only multiple edges may share the same \(\mathit{GroupID}\).The next \(\mathit{ConstrainedCount}\) lines contain information about the edge pairs that are not connected in the specified nodes of the network. All other edges are connected to each other by default. Each line contains three integers: \(\mathit{NodeID}\), \(\mathit{EdgeID}_1\), and \(\mathit{EdgeID}_2\). \(0 \le \mathit{NodeID} < \mathit{NodeCount}\), \(0 \le \mathit{EdgeID}_1, \mathit{EdgeID}_2 < \mathit{EdgeCount}\), \(\mathit{EdgeID}_1 \ne \mathit{EdgeID}_2\). The next \(\mathit{FlowCount}\) lines contain information about the flows to be calculated. Each line contains four integers: \(\mathit{FlowID}\), \(\mathit{SourceNode}\), \(\mathit{TargetNode}\), and \(\mathit{FlowRate}\). \(0 \le \mathit{FlowID} < \mathit{FlowCount}\), \(0 \le \mathit{SourceNode}, \mathit{TargetNode} < \mathit{NodeCount}\), \(\mathit{SourceNode} \ne \mathit{TargetNode}\), \(2 \le \mathit{FlowRate} \le 12000\) Don't forget that the \(\mathit{SFL}\) and \(\mathit{GFL}\) mentioned above are also important parameters.For the simplicity, both \(\mathit{EdgeID}\) and \(\mathit{FlowID}\) of the \(i\)-th (\(0\)-indexed) edge (flow) is always equal to \(i\).
|
In the first line, output the number of your success flows.Next, each line output edge information about the path that a flow passes through. The format is as follows: \(\mathit{FlowID}\ \mathit{EdgeID}_1\ \mathit{EdgeID}_2\ \mathit{EdgeID}_3\ \dots\ \mathit{EdgeID}_n\).There is no requirement on the output sequence between flow paths, but edges in one flow must be outputted in order, from source node to target node. Please output all successfully calculated flow paths. For other flows that are not output, the checker determines that you have not found appropriate paths for the flows by default.
|
The total distance of a flow path is \(620\) (\(120 + 100 + 100 + 300 = 620\)). (Note: 0 9 10 12 13 is also a valid output result.)
|
Input: 8 15 3 1 0 0 0 1 100 1050 1 1 0 1 200 2200 2 1 0 1 200 99400 3 2 0 3 100 450 4 3 0 3 500 1120 5 4 1 2 1000 40000 6 5 2 3 600 10000 7 5 2 3 600 10000 8 6 1 4 120 2500 9 6 1 4 120 450 10 7 1 5 170 1250 11 8 2 5 200 2500 12 9 3 5 100 1250 13 10 3 6 300 1150 14 11 3 7 300 1100 2 5 7 2 6 7 2 6 11 0 4 6 100 | Output: 1 0 8 0 3 13
|
Beginner
| 1 | 3,397 | 2,097 | 602 | 15 |
1,337 |
B
|
1337B
|
B. Kana and Dragon Quest game
| 900 |
greedy; implementation; math
|
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic. One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon. The dragon has a hit point of \(x\) initially. When its hit point goes to \(0\) or under \(0\), it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells. Void Absorption Assume that the dragon's current hit point is \(h\), after casting this spell its hit point will become \(\left\lfloor \frac{h}{2} \right\rfloor + 10\). Here \(\left\lfloor \frac{h}{2} \right\rfloor\) denotes \(h\) divided by two, rounded down. Lightning Strike This spell will decrease the dragon's hit point by \(10\). Assume that the dragon's current hit point is \(h\), after casting this spell its hit point will be lowered to \(h-10\).Due to some reasons Kana can only cast no more than \(n\) Void Absorptions and \(m\) Lightning Strikes. She can cast the spells in any order and doesn't have to cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.
|
The first line contains a single integer \(t\) (\(1 \leq t \leq 1000\)) — the number of test cases.The next \(t\) lines describe test cases. For each test case the only line contains three integers \(x\), \(n\), \(m\) (\(1\le x \le 10^5\), \(0\le n,m\le30\)) — the dragon's intitial hit point, the maximum number of Void Absorptions and Lightning Strikes Kana can cast respectively.
|
If it is possible to defeat the dragon, print ""YES"" (without quotes). Otherwise, print ""NO"" (without quotes).You can print each letter in any case (upper or lower).
|
One possible casting sequence of the first test case is shown below: Void Absorption \(\left\lfloor \frac{100}{2} \right\rfloor + 10=60\). Lightning Strike \(60-10=50\). Void Absorption \(\left\lfloor \frac{50}{2} \right\rfloor + 10=35\). Void Absorption \(\left\lfloor \frac{35}{2} \right\rfloor + 10=27\). Lightning Strike \(27-10=17\). Lightning Strike \(17-10=7\). Lightning Strike \(7-10=-3\).
|
Input: 7 100 3 4 189 3 4 64 2 3 63 2 3 30 27 7 10 9 1 69117 21 2 | Output: YES NO NO YES YES YES YES
|
Beginner
| 3 | 1,232 | 382 | 168 | 13 |
1,442 |
C
|
1442C
|
C. Graph Transpositions
| 2,400 |
dfs and similar; graphs; greedy; shortest paths
|
You are given a directed graph of \(n\) vertices and \(m\) edges. Vertices are numbered from \(1\) to \(n\). There is a token in vertex \(1\).The following actions are allowed: Token movement. To move the token from vertex \(u\) to vertex \(v\) if there is an edge \(u \to v\) in the graph. This action takes \(1\) second. Graph transposition. To transpose all the edges in the graph: replace each edge \(u \to v\) by an edge \(v \to u\). This action takes increasingly more time: \(k\)-th transposition takes \(2^{k-1}\) seconds, i.e. the first transposition takes \(1\) second, the second one takes \(2\) seconds, the third one takes \(4\) seconds, and so on. The goal is to move the token from vertex \(1\) to vertex \(n\) in the shortest possible time. Print this time modulo \(998\,244\,353\).
|
The first line of input contains two integers \(n, m\) (\(1 \le n, m \le 200\,000\)).The next \(m\) lines contain two integers each: \(u, v\) (\(1 \le u, v \le n; u \ne v\)), which represent the edges of the graph. It is guaranteed that all ordered pairs \((u, v)\) are distinct.It is guaranteed that it is possible to move the token from vertex \(1\) to vertex \(n\) using the actions above.
|
Print one integer: the minimum required time modulo \(998\,244\,353\).
|
The first example can be solved by transposing the graph and moving the token to vertex \(4\), taking \(2\) seconds.The best way to solve the second example is the following: transpose the graph, move the token to vertex \(2\), transpose the graph again, move the token to vertex \(3\), transpose the graph once more and move the token to vertex \(4\).
|
Input: 4 4 1 2 2 3 3 4 4 1 | Output: 2
|
Expert
| 4 | 798 | 392 | 70 | 14 |
1,779 |
B
|
1779B
|
B. MKnez's ConstructiveForces Task
| 900 |
constructive algorithms; math
|
MKnez wants to construct an array \(s_1,s_2, \ldots , s_n\) satisfying the following conditions: Each element is an integer number different from \(0\); For each pair of adjacent elements their sum is equal to the sum of the whole array. More formally, \(s_i \neq 0\) must hold for each \(1 \leq i \leq n\). Moreover, it must hold that \(s_1 + s_2 + \cdots + s_n = s_i + s_{i+1}\) for each \(1 \leq i < n\).Help MKnez to construct an array with these properties or determine that it does not exist.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \leq t \leq 100\)). The description of the test cases follows.The only line of each test case contains a single integer \(n\) (\(2 \leq n \leq 1000\)) — the length of the array.
|
For each test case, print ""YES"" if an array of length \(n\) satisfying the conditions exists. Otherwise, print ""NO"". If the answer is ""YES"", on the next line print a sequence \(s_1,s_2, \ldots, s_n\) satisfying the conditions. Each element should be a non-zero integer in the range \([-5000,5000]\), i. e. \(-5000 \leq s_i \leq 5000\) and \(s_i \neq 0\) should hold for each \(1 \leq i \leq n\).It can be proved that if a solution exists then there also exists one which satisfies the additional constraints on the range.If there are several correct answers, print any of them.
|
In the first test case, \([9,5]\) is a valid answer since \(9+5\) (the sum of the two adjacent elements \(s_1+s_2\)) is equal to \(9+5\) (the sum of all elements). Other solutions include \([6,-9], [-1,-2], [-5000,5000], \ldots\)For the second test case, let us show why some arrays do not satisfy the constraints: \([1,1,1]\) — \(s_1+s_2 = 1+1 = 2\) and \(s_1+s_2+s_3=1+1+1 = 3\) differ; \([1,-1,1]\) — \(s_1+s_2=1+(-1)=0\) and \(s_1+s_2+s_3=1+(-1)+1 = 1\) differ; \([0,0,0]\) — The array \(s\) cannot contain a \(0\). This is not a proof, but it can be shown that the answer is ""NO"".
|
Input: 2 2 3 | Output: YES 9 5 NO
|
Beginner
| 2 | 498 | 277 | 583 | 17 |
862 |
F
|
862F
|
F. Mahmoud and Ehab and the final stage
| 2,900 |
data structures; strings
|
Mahmoud and Ehab solved Dr. Evil's questions so he gave them the password of the door of the evil land. When they tried to open the door using it, the door gave them a final question to solve before they leave (yes, the door is digital, Dr. Evil is modern). If they don't solve it, all the work will be useless and they won't leave the evil land forever. Will you help them?Mahmoud and Ehab are given n strings s1, s2, ... , sn numbered from 1 to n and q queries, Each query has one of the following forms: 1 a b (1 ≤ a ≤ b ≤ n), For all the intervals [l;r] where (a ≤ l ≤ r ≤ b) find the maximum value of this expression:(r - l + 1) * LCP(sl, sl + 1, ... , sr - 1, sr) where LCP(str1, str2, str3, ... ) is the length of the longest common prefix of the strings str1, str2, str3, ... . 2 x y (1 ≤ x ≤ n) where y is a string, consisting of lowercase English letters. Change the string at position x to y.
|
The first line of input contains 2 integers n and q (1 ≤ n ≤ 105, 1 ≤ q ≤ 105) – The number of strings and the number of queries, respectively.The second line contains n strings stri consisting of lowercase English letters.The next q lines describe the queries and may have one of the 2 forms: 1 a b (1 ≤ a ≤ b ≤ n). 2 x y (1 ≤ x ≤ n), where y is a string consisting of lowercase English letters.the total length of all strings in input won't exceed 105
|
For each query of first type output its answer in a new line.
|
Input: 5 9mahmoud mahmoudbadawy drmahmoud drevil mahmoud1 1 51 1 21 2 32 3 mahmoud2 4 mahmoud2 2 mahmouu1 1 51 2 31 1 1 | Output: 14141330127
|
Master
| 2 | 903 | 453 | 61 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.