contest_id
int32 1
2.13k
| index
stringclasses 62
values | problem_id
stringlengths 2
6
| title
stringlengths 0
67
| rating
int32 0
3.5k
| tags
stringlengths 0
139
| statement
stringlengths 0
6.96k
| input_spec
stringlengths 0
2.32k
| output_spec
stringlengths 0
1.52k
| note
stringlengths 0
5.06k
| sample_tests
stringlengths 0
1.02k
| difficulty_category
stringclasses 6
values | tag_count
int8 0
11
| statement_length
int32 0
6.96k
| input_spec_length
int16 0
2.32k
| output_spec_length
int16 0
1.52k
| contest_year
int16 0
21
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,773 |
J
|
1773J
|
J. Jumbled Trees
| 2,900 |
constructive algorithms; math
|
You are given an undirected connected graph with \(n\) vertices and \(m\) edges. Each edge has an associated counter, initially equal to \(0\). In one operation, you can choose an arbitrary spanning tree and add any value \(v\) to all edges of this spanning tree. Determine if it's possible to make every counter equal to its target value \(x_i\) modulo prime \(p\), and provide a sequence of operations that achieves it.
|
The first line contains three integers \(n\), \(m\), and \(p\) β the number of vertices, the number of edges, and the prime modulus (\(1 \le n \le 500\); \(1 \le m \le 1000\); \(2 \le p \le 10^9\), \(p\) is prime).Next \(m\) lines contain three integers \(u_i\), \(v_i\), \(x_i\) each β the two endpoints of the \(i\)-th edge and the target value of that edge's counter (\(1 \le u_i, v_i \le n\); \(0 \le x_i < p\); \(u_i \neq v_i\)). The graph is connected. There are no loops, but there may be multiple edges between the same two vertices.
|
If the target values on counters cannot be achieved, print -1. Otherwise, print \(t\) β the number of operations, followed by \(t\) lines, describing the sequence of operations. Each line starts with integer \(v\) (\(0 \le v < p\)) β the counter increment for this operation. Then, in the same line, followed by \(n - 1\) integers \(e_1\), \(e_2\), ... \(e_{n - 1}\) (\(1 \le e_i \le m\)) β the edges of the spanning tree.The number of operations \(t\) should not exceed \(2m\). You don't need to minimize \(t\). Any correct answer within the \(2m\) bound is accepted. You are allowed to repeat spanning trees.
|
Input: 3 3 101 1 2 30 2 3 40 3 1 50 | Output: 3 10 1 2 20 1 3 30 2 3
|
Master
| 2 | 421 | 541 | 610 | 17 |
|
2,048 |
D
|
2048D
|
D. Kevin and Competition Memories
| 1,600 |
binary search; brute force; data structures; greedy; sortings; two pointers
|
Kevin used to get into Rio's Memories, and in Rio's Memories, a series of contests was once held. Kevin remembers all the participants and all the contest problems from that time, but he has forgotten the specific rounds, the distribution of problems, and the exact rankings.There are \( m \) problems in total, with the \( i \)-th problem having a difficulty of \( b_i \). Let each contest consist of \( k \) problems, resulting in a total of \( \lfloor \frac{m}{k} \rfloor \) contests. This means that you select exactly \( \lfloor \frac{m}{k} \rfloor \cdot k \) problems for the contests in any combination you want, with each problem being selected at most once, and the remaining \(m\bmod k\) problems are left unused. For example, if \(m = 17\) and \(k = 3\), you should create exactly \(5\) contests consisting of \(3\) problems each, and exactly \(2\) problems will be left unused.There are \( n \) participants in the contests, with Kevin being the \(1\)-st participant. The \( i \)-th participant has a rating of \( a_i \). During the contests, each participant solves all problems with a difficulty not exceeding their rating, meaning the \( i \)-th participant solves the \( j \)-th problem if and only if \( a_i \geq b_j \). In each contest, Kevin's rank is one plus the number of participants who solve more problems than he does.For each \( k = 1, 2, \ldots, m \), Kevin wants to know the minimum sum of his ranks across all \( \lfloor \frac{m}{k} \rfloor \) contests. In other words, for some value of \(k\), after selecting the problems for each contest, you calculate the rank of Kevin in each contest and sum up these ranks over all \( \lfloor \frac{m}{k} \rfloor \) contests. Your goal is to minimize this value.Note that contests for different values of \(k\) are independent. It means that for different values of \(k\), you can select the distribution of problems into the contests independently.
|
Each test contains multiple test cases. The first line contains the number of test cases \( t \) (\( 1 \le t \le 5\cdot 10^4 \)).The first line of each test case contains two integers \( n \) and \( m \) (\( 1 \le n, m \leq 3\cdot 10^5 \)) β the number of participants and the number of problems.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 rating of each participant.The third line of each test case contains \( m \) integers \( b_1, b_2, \ldots, b_m \) (\( 0 \le b_i \le 10^9 \)) β the difficulty of each problem.It is guaranteed that both the sum of \( n \) and the sum of \( m \) over all test cases do not exceed \( 3 \cdot 10^5 \).
|
For each test case, output \(m\) integers β the minimum sum of Kevin's ranks for each \( k = 1, 2, \ldots, m\).
|
For the first test case:When \(k=1\), since each contest only contains one problem, the distribution is in fact unique. For example, in the contest which only includes the third problem (which has a difficulty of \(4\)), all participants except the \(2\)-nd can solve it. Since no one solves strictly more problems than Kevin, his ranking in this contest is \(1\). Similarly, in all \(4\) contests, Kevin's rankings are \(1,3,1,2\), and the sum is \(7\).When \(k=2\), one optimal way is to choose the \(1\)-st and the \(3\)-rd problem to form a contest, while the \(2\)-nd and \(4\)-th for another. In the former contest, \(4\) participants respectively solve \(2,1,2,2\) problems, so Kevin's ranking is \(1\); in the latter one, they respectively solve \(0,0,2,1\), since there are \(2\) participants (\(3\)-rd and \(4\)-th) solve more problems than Kevin, his ranking is \(1+2=3\). Thus the answer is \(1+3=4\). It can be proven that there's no way to achieve a lower sum.When \(k=3\), we can simply choose the \(1\)-st, the \(3\)-rd, and the \(4\)-th problem to make a contest, and Kevin has a ranking of \(2\), which is optimal.When \(k=4\), since there's only one contest, the distribution is also unique, and Kevin's ranking is \(3\).
|
Input: 44 44 3 7 52 5 4 65 55 0 4 8 61 3 9 2 76 71 1 4 5 1 41 9 1 9 8 1 07 61 9 1 9 8 1 01 1 4 5 1 4 | Output: 7 4 2 3 6 2 1 1 2 7 3 2 1 1 1 1 15 9 5 4 4 4
|
Medium
| 6 | 1,919 | 713 | 111 | 20 |
47 |
C
|
47C
|
C. Crossword
| 2,000 |
implementation
|
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplΠ΅ type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular ""eight"" or infinity sign, not necessarily symmetrical.The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.Help Vasya β compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
|
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
|
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
|
Input: NODBAAYARDAIRWAYNEWTONBURN | Output: BAA...U.I...R.R...NEWTON..A..O..YARD
|
Hard
| 1 | 797 | 117 | 513 | 0 |
|
1,684 |
C
|
1684C
|
C. Column Swapping
| 1,400 |
brute force; constructive algorithms; greedy; implementation; sortings
|
You are given a grid with \(n\) rows and \(m\) columns, where each cell has a positive integer written on it. Let's call a grid good, if in each row the sequence of numbers is sorted in a non-decreasing order. It means, that for each \(1 \le i \le n\) and \(2 \le j \le m\) the following holds: \(a_{i,j} \ge a_{i, j-1}\).You have to to do the following operation exactly once: choose two columns with indexes \(i\) and \(j\) (not necessarily different), \(1 \le i, j \le m\), and swap them.You are asked to determine whether it is possible to make the grid good after the swap and, if it is, find the columns that need to be swapped.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 100\)). Description of the test cases follows.The first line of each test case contains two integers \(n\) and \(m\) (\(1 \le n, m \le 2 \cdot 10^5\)) β the number of rows and columns respectively.Each of the next \(n\) rows contains \(m\) integers, \(j\)-th element of \(i\)-th row is \(a_{i,j}\) (\(1 \le a_{i,j} \le 10^9\)) β the number written in the \(j\)-th cell of the \(i\)-th row.It's guaranteed that the sum of \(n \cdot m\) over all test cases does not exceed \(2 \cdot 10^5\).
|
If after the swap it is impossible to get a good grid, output \(-1\).In the other case output \(2\) integers β the indices of the columns that should be swapped to get a good grid.If there are multiple solutions, print any.
|
In the first test case the grid is initially good, so we can, for example, swap the first column with itself.In the second test case it is impossible to make the grid good.In the third test case it is needed to swap the first and the second column, then the grid becomes good.
|
Input: 52 31 2 31 1 12 24 12 32 22 11 12 36 2 15 4 32 112 | Output: 1 1 -1 1 2 1 3 1 1
|
Easy
| 5 | 634 | 598 | 223 | 16 |
1,970 |
C3
|
1970C3
|
C3. Game on Tree (Hard)
| 1,900 |
dfs and similar; dp; games; trees
|
This is the hard version of the problem. The only difference in this version is the constraint on \(t\).Ron and Hermione are playing a game on a tree of \(n\) nodes that are initially inactive. The game consists of \(t\) rounds, each of which starts with a stone on exactly one node, which is considered as activated. A move consists of picking an inactive neighbor of the node with a stone on it and moving the stone there (thus activating this neighbor). Ron makes the first move, after which he alternates with Hermione until no valid move is available. The player that cannot make a move loses the round. If both players play optimally, who wins each round of this game? Note that all the rounds are played with the same tree; only the starting node changes. Moreover, after each round, all active nodes are considered inactive again.
|
The first line contains integers \(n\) (\(2 \leq n \leq 2\times 10^5\)), \(t\) (\(1 \leq t \leq n\)), the number of nodes in the tree and the number of rounds, respectively.The next \(n-1\) lines contain two integers \(1 \leq u, v \leq n\) each, corresponding to an edge of the tree.The next line contains \(t\) integers \(1 \leq u_1 , \dots , u_t \leq n\), corresponding to the node where the stone is initially put.
|
The output consists of \(t\) lines, each line being either ""Ron"" or ""Hermione"".
|
Input: 5 21 21 33 43 51 2 | Output: Ron Ron
|
Hard
| 4 | 838 | 417 | 83 | 19 |
|
1,779 |
F
|
1779F
|
F. Xorcerer's Stones
| 2,500 |
bitmasks; constructive algorithms; dp; trees
|
Misha had been banned from playing chess for good since he was accused of cheating with an engine. Therefore, he retired and decided to become a xorcerer.One day, while taking a walk in a park, Misha came across a rooted tree with nodes numbered from \(1\) to \(n\). The root of the tree is node \(1\). For each \(1\le i\le n\), node \(i\) contains \(a_i\) stones in it. Misha has recently learned a new spell in his xorcery class and wants to test it out. A spell consists of: Choose some node \(i\) (\(1 \leq i \leq n\)). Calculate the bitwise XOR \(x\) of all \(a_j\) such that node \(j\) is in the subtree of \(i\) (\(i\) belongs to its own subtree). Set \(a_j\) equal to \(x\) for all nodes \(j\) in the subtree of \(i\). Misha can perform at most \(2n\) spells and he wants to remove all stones from the tree. More formally, he wants \(a_i=0\) to hold for each \(1\leq i \leq n\). Can you help him perform the spells?A tree with \(n\) nodes is a connected acyclic graph which contains \(n-1\) edges. The subtree of node \(i\) is the set of all nodes \(j\) such that \(i\) lies on the simple path from \(1\) (the root) to \(j\). We consider \(i\) to be contained in its own subtree.
|
The first line contains a single integer \(n\) (\(2 \leq n \leq 2\cdot 10^5\)) β the size of the treeThe second line contains an array of integers \(a_1,a_2,\ldots, a_n\) (\(0 \leq a_i \leq 31\)), describing the number of stones in each node initially.The third line contains an array of integers \(p_2,p_3,\ldots, p_n\) (\(1 \leq p_i \leq i-1\)), where \(p_i\) means that there is an edge connecting \(p_i\) and \(i\).
|
If there is not a valid sequence of spells, output \(-1\).Otherwise, output a single integer \(q\) (\(0 \leq q \leq 2n\)) in the first line β the number of performed spells.In the second line output a sequence of integers \(v_1,v_2,\ldots,v_q\) (\(1 \leq v_i \leq n\)) β the \(i\)-th spell will be performed on the subtree of node \(v_i\). Please note that order matters.If multiple solutions exist, output any. You don't have to minimize the number of operations.
|
Please refer to the following pictures for an explanation of the third test. Only the first \(4\) spells are shown since the last \(2\) do nothing. The first picture represents the tree initially with the number of stones for each node written above it in green. Changes applied by the current spell are highlighted in red.
|
Input: 2 13 13 1 | Output: 1 1
|
Expert
| 4 | 1,187 | 419 | 464 | 17 |
1,137 |
E
|
1137E
|
E. Train Car Selection
| 2,700 |
data structures; greedy
|
Vasya likes to travel by train, but doesn't like when the car he travels in is located in the tail of the train.Vasya gets on the train at the station. The train consists of \(n\) cars indexed from \(1\) to \(n\) counting from the locomotive (head of the train). Three types of events occur while the train is moving: Some number of cars are added to the head of the train; Some number of cars are added to the tail of the train; Vasya recalculates the values of the convenience of the cars (read more about it below). At each moment of time we will index the cars from the head of the train, starting from \(1\). Note that when adding new cars to the head of the train, the indexing of the old ones may shift.To choose which car to go in, Vasya will use the value \(A_i\) for each car (where \(i\) is a car index), which is calculated as follows: At the beginning of the trip \(A_i=0\), as well as for the new cars at the time of their addition. During the next recalculation Vasya chooses some positive integers \(b\) and \(s\) and adds to all \(A_i\) value \(b + (i - 1) \cdot s\). Vasya hasn't decided yet where he will get on the train and where will get off the train, so after each event of one of the three types he wants to know the least index of the car, such that its value \(A_i\) is minimal. Since there is a lot of cars, Vasya asked you to write a program that answers his question.
|
The first line contains two integers \(n\) and \(m\) (\(1 \leq n \leq 10^9\), \(1 \leq m \leq 300\,000\)), the number of cars in the train at the time of departure from the station and the number of stations, respectively.Next \(m\) lines contain the descriptions of events. Each event is one of the following three types: ""\(1\) \(k\)"" (\(1 \le k \le 10^9\)), add \(k\) cars to the head of the train ""\(2\) \(k\)"" (\(1 \le k \le 10^9\)), add \(k\) cars to the tail of the train ""\(3\) \(b\) \(s\)"" (\(1 \le b, s \le 10^9\)), recalculate the convenience of all train cars. It is guaranteed that at any time the train length does not exceed \(10^9\). Also it's guaranteed that the integers \(A_i\) will not grow too high. Formally, it's guaranteed that if we sum the largest addition over all events of the \(3\)-rd type (that is, \(b + (n - 1) \cdot s\), where \(n\) is the number of cars at that moment) then the acquired sum would be at most \(10^{18}\).
|
After each of the \(m\) queries print two integers: \(j\) and \(A_j\) β the number of the car closest to the head of the train, such that its value \(A_j\) is minimal, and the value \(A_j\) itself.
|
Initially the train consists of one car with \(A_1 = 0\), let's denote train as \([0]\) for simplicity. After adding one car to the head, train is \([0, 0]\). After recalculation of values with parameters \(b=1, s=1\), train is \([1, 2]\). After another recalculation of values with the parameters \(b=1, s=1\), train is \([2, 4]\). After adding one car to the end, train is \([2, 4, 0]\). After another adding one car to the end, train is \([2, 4, 0, 0]\). After recalculation of values with parameters \(b=1\), \(s=1\), train is \([3, 6, 3, 4]\). After adding one car to the end, train is \([3, 6, 3, 4, 0]\). After recalculation of values with parameters \(b=1\), \(s=5\), train is \([4, 12, 14, 20, 21]\).
|
Input: 1 8 1 1 3 1 1 3 1 1 2 1 2 1 3 1 1 2 1 3 1 5 | Output: 1 0 1 1 1 2 3 0 3 0 1 3 5 0 1 4
|
Master
| 2 | 1,397 | 962 | 197 | 11 |
761 |
B
|
761B
|
B. Dasha and friends
| 1,300 |
brute force; implementation; math
|
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation:The track is the circle with length L, in distinct points of which there are n barriers. Athlete always run the track in counterclockwise direction if you look on him from above. All barriers are located at integer distance from each other along the track. Her friends the parrot Kefa and the leopard Sasha participated in competitions and each of them ran one lap. Each of the friends started from some integral point on the track. Both friends wrote the distance from their start along the track to each of the n barriers. Thus, each of them wrote n integers in the ascending order, each of them was between 0 and L - 1, inclusively. Consider an example. Let L = 8, blue points are barriers, and green points are Kefa's start (A) and Sasha's start (B). Then Kefa writes down the sequence [2, 4, 6], and Sasha writes down [1, 5, 7]. There are several tracks in the country, all of them have same length and same number of barriers, but the positions of the barriers can differ among different tracks. Now Dasha is interested if it is possible that Kefa and Sasha ran the same track or they participated on different tracks. Write the program which will check that Kefa's and Sasha's tracks coincide (it means that one can be obtained from the other by changing the start position). Note that they always run the track in one direction β counterclockwise, if you look on a track from above.
|
The first line contains two integers n and L (1 β€ n β€ 50, n β€ L β€ 100) β the number of barriers on a track and its length. The second line contains n distinct integers in the ascending order β the distance from Kefa's start to each barrier in the order of its appearance. All integers are in the range from 0 to L - 1 inclusively.The second line contains n distinct integers in the ascending order β the distance from Sasha's start to each barrier in the order of its overcoming. All integers are in the range from 0 to L - 1 inclusively.
|
Print ""YES"" (without quotes), if Kefa and Sasha ran the coinciding tracks (it means that the position of all barriers coincides, if they start running from the same points on the track). Otherwise print ""NO"" (without quotes).
|
The first test is analyzed in the statement.
|
Input: 3 82 4 61 5 7 | Output: YES
|
Easy
| 3 | 1,554 | 538 | 229 | 7 |
1,748 |
D
|
1748D
|
D. ConstructOR
| 2,100 |
bitmasks; chinese remainder theorem; combinatorics; constructive algorithms; math; number theory
|
You are given three integers \(a\), \(b\), and \(d\). Your task is to find any integer \(x\) which satisfies all of the following conditions, or determine that no such integers exist: \(0 \le x \lt 2^{60}\); \(a|x\) is divisible by \(d\); \(b|x\) is divisible by \(d\). Here, \(|\) denotes the bitwise OR operation.
|
Each test contains multiple test cases. The first line of input contains one integer \(t\) (\(1 \le t \le 10^4\)) β the number of test cases. Each test case consists of one line, containing three integers \(a\), \(b\), and \(d\) (\(1 \le a,b,d \lt 2^{30}\)).
|
For each test case print one integer. If there exists an integer \(x\) which satisfies all of the conditions from the statement, print \(x\). Otherwise, print \(-1\).If there are multiple solutions, you may print any of them.
|
In the first test case, \(x=18\) is one of the possible solutions, since \(39|18=55\) and \(12|18=30\), both of which are multiples of \(d=5\).In the second test case, \(x=14\) is one of the possible solutions, since \(8|14=6|14=14\), which is a multiple of \(d=14\).In the third and fourth test cases, we can show that there are no solutions.
|
Input: 812 39 56 8 14100 200 2003 4 62 2 218 27 3420 666 69987654321 123456789 999999999 | Output: 18 14 -1 -1 0 11 25599 184470016815529983
|
Hard
| 6 | 315 | 258 | 225 | 17 |
1,936 |
A
|
1936A
|
A. Bitwise Operation Wizard
| 1,700 |
bitmasks; constructive algorithms; greedy; interactive; math
|
This is an interactive problem.There is a secret sequence \(p_0, p_1, \ldots, p_{n-1}\), which is a permutation of \(\{0,1,\ldots,n-1\}\).You need to find any two indices \(i\) and \(j\) such that \(p_i \oplus p_j\) is maximized, where \(\oplus\) denotes the bitwise XOR operation.To do this, you can ask queries. Each query has the following form: you pick arbitrary indices \(a\), \(b\), \(c\), and \(d\) (\(0 \le a,b,c,d < n\)). Next, the jury calculates \(x = (p_a \mid p_b)\) and \(y = (p_c \mid p_d)\), where \(|\) denotes the bitwise OR operation. Finally, you receive the result of comparison between \(x\) and \(y\). In other words, you are told if \(x < y\), \(x > y\), or \(x = y\).Please find any two indices \(i\) and \(j\) (\(0 \le i,j < n\)) such that \(p_i \oplus p_j\) is maximum among all such pairs, using at most \(3n\) queries. If there are multiple pairs of indices satisfying the condition, you may output any one of them.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^3\)). The description of the test cases follows.
|
In the first test case, the hidden permutation is \(p=[0,3,1,2]\).For the query ""? 0 2 3 1"", the jury return ""<"" because \((p_0 \mid p_2) = (0 \mid 1) =1 < (p_3 \mid p_1) = (2 \mid 3) = 3\).For the query ""? 1 1 2 3"", the jury return ""="" because \((p_1 \mid p_1) = (3\mid 3)= 3 = (p_2 \mid p_3) = (1 \mid 2)=3\).For the query ""? 1 2 0 3"", the jury return "">"" because \((p_1 \mid p_2) = (3 \mid 1) = 3 > (p_0 \mid p_3) = (0\mid 2)=2\).The answer \(i = 3\) and \(j = 2\) is valid: \((p_3 \oplus p_2) = (2 \oplus 1) = 3\) is indeed equal to the maximum possible value of \(p_i \oplus p_j\). Another valid answer would be \(i=0\) and \(j=1\). As the number of queries does not exceed \(3n=12\), the answer is considered correct.In the second test case, \(n = 2\), so \(p\) is either \([0, 1]\) or \([1, 0]\). In any case, \(p_0 \oplus p_1 = 1\) is maximum possible.
|
Input: 2 4 < = > 2 | Output: ? 0 2 3 1 ? 1 1 2 3 ? 1 2 0 3 ! 3 2 ! 0 1
|
Medium
| 5 | 945 | 161 | 0 | 19 |
|
137 |
B
|
137B
|
B. Permutation
| 1,000 |
greedy
|
""Hey, it's homework time"" β thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).
|
The first line of the input data contains an integer n (1 β€ n β€ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 β€ ai β€ 5000, 1 β€ i β€ n).
|
Print the only number β the minimum number of changes needed to get the permutation.
|
The first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.
|
Input: 33 1 2 | Output: 0
|
Beginner
| 1 | 753 | 203 | 84 | 1 |
1,245 |
C
|
1245C
|
C. Constanze's Machine
| 1,400 |
dp
|
Constanze is the smartest girl in her village but she has bad eyesight.One day, she was able to invent an incredible machine! When you pronounce letters, the machine will inscribe them onto a piece of paper. For example, if you pronounce 'c', 'o', 'd', and 'e' in that order, then the machine will inscribe ""code"" onto the paper. Thanks to this machine, she can finally write messages without using her glasses.However, her dumb friend Akko decided to play a prank on her. Akko tinkered with the machine so that if you pronounce 'w', it will inscribe ""uu"" instead of ""w"", and if you pronounce 'm', it will inscribe ""nn"" instead of ""m""! Since Constanze had bad eyesight, she was not able to realize what Akko did.The rest of the letters behave the same as before: if you pronounce any letter besides 'w' and 'm', the machine will just inscribe it onto a piece of paper.The next day, I received a letter in my mailbox. I can't understand it so I think it's either just some gibberish from Akko, or Constanze made it using her machine. But since I know what Akko did, I can just list down all possible strings that Constanze's machine would have turned into the message I got and see if anything makes sense.But I need to know how much paper I will need, and that's why I'm asking you for help. Tell me the number of strings that Constanze's machine would've turned into the message I got.But since this number can be quite large, tell me instead its remainder when divided by \(10^9+7\).If there are no strings that Constanze's machine would've turned into the message I got, then print \(0\).
|
Input consists of a single line containing a string \(s\) (\(1 \leq |s| \leq 10^5\)) β the received message. \(s\) contains only lowercase Latin letters.
|
Print a single integer β the number of strings that Constanze's machine would've turned into the message \(s\), modulo \(10^9+7\).
|
For the first example, the candidate strings are the following: ""ouuokarinn"", ""ouuokarim"", ""owokarim"", and ""owokarinn"".For the second example, there is only one: ""banana"".For the third example, the candidate strings are the following: ""nm"", ""mn"" and ""nnn"".For the last example, there are no candidate strings that the machine can turn into ""amanda"", since the machine won't inscribe 'm'.
|
Input: ouuokarinn | Output: 4
|
Easy
| 1 | 1,601 | 153 | 130 | 12 |
1,707 |
D
|
1707D
|
D. Partial Virtual Trees
| 3,000 |
combinatorics; dfs and similar; dp; math; trees
|
Kawashiro Nitori is a girl who loves competitive programming. One day she found a rooted tree consisting of \(n\) vertices. The root is vertex \(1\). As an advanced problem setter, she quickly thought of a problem.Kawashiro Nitori has a vertex set \(U=\{1,2,\ldots,n\}\). She's going to play a game with the tree and the set. In each operation, she will choose a vertex set \(T\), where \(T\) is a partial virtual tree of \(U\), and change \(U\) into \(T\).A vertex set \(S_1\) is a partial virtual tree of a vertex set \(S_2\), if \(S_1\) is a subset of \(S_2\), \(S_1 \neq S_2\), and for all pairs of vertices \(i\) and \(j\) in \(S_1\), \(\operatorname{LCA}(i,j)\) is in \(S_1\), where \(\operatorname{LCA}(x,y)\) denotes the lowest common ancestor of vertices \(x\) and \(y\) on the tree. Note that a vertex set can have many different partial virtual trees.Kawashiro Nitori wants to know for each possible \(k\), if she performs the operation exactly \(k\) times, in how many ways she can make \(U=\{1\}\) in the end? Two ways are considered different if there exists an integer \(z\) (\(1 \le z \le k\)) such that after \(z\) operations the sets \(U\) are different.Since the answer could be very large, you need to find it modulo \(p\). It's guaranteed that \(p\) is a prime number.
|
The first line contains two integers \(n\) and \(p\) (\(2 \le n \le 2000\), \(10^8 + 7 \le p \le 10^9+9\)). It's guaranteed that \(p\) is a prime number.Each of the next \(n-1\) lines contains two integers \(u_i\), \(v_i\) (\(1 \leq u_i, v_i \leq n\)), representing an edge between \(u_i\) and \(v_i\).It is guaranteed that the given edges form a tree.
|
The only line contains \(n-1\) integers β the answer modulo \(p\) for \(k=1,2,\ldots,n-1\).
|
In the first test case, when \(k=1\), the only possible way is: \(\{1,2,3,4\} \to \{1\}\). When \(k=2\), there are \(6\) possible ways: \(\{1,2,3,4\} \to \{1,2\} \to \{1\}\); \(\{1,2,3,4\} \to \{1,2,3\} \to \{1\}\); \(\{1,2,3,4\} \to \{1,2,4\} \to \{1\}\); \(\{1,2,3,4\} \to \{1,3\} \to \{1\}\); \(\{1,2,3,4\} \to \{1,3,4\} \to \{1\}\); \(\{1,2,3,4\} \to \{1,4\} \to \{1\}\). When \(k=3\), there are \(6\) possible ways: \(\{1,2,3,4\} \to \{1,2,3\} \to \{1,2\} \to \{1\}\); \(\{1,2,3,4\} \to \{1,2,3\} \to \{1,3\} \to \{1\}\); \(\{1,2,3,4\} \to \{1,2,4\} \to \{1,2\} \to \{1\}\); \(\{1,2,3,4\} \to \{1,2,4\} \to \{1,4\} \to \{1\}\); \(\{1,2,3,4\} \to \{1,3,4\} \to \{1,3\} \to \{1\}\); \(\{1,2,3,4\} \to \{1,3,4\} \to \{1,4\} \to \{1\}\).
|
Input: 4 998244353 1 2 2 3 1 4 | Output: 1 6 6
|
Master
| 5 | 1,289 | 352 | 91 | 17 |
1,660 |
A
|
1660A
|
A. Vasya and Coins
| 800 |
greedy; math
|
Vasya decided to go to the grocery store. He found in his wallet \(a\) coins of \(1\) burle and \(b\) coins of \(2\) burles. He does not yet know the total cost of all goods, so help him find out \(s\) (\(s > 0\)): the minimum positive integer amount of money he cannot pay without change or pay at all using only his coins.For example, if \(a=1\) and \(b=1\) (he has one \(1\)-burle coin and one \(2\)-burle coin), then: he can pay \(1\) burle without change, paying with one \(1\)-burle coin, he can pay \(2\) burle without change, paying with one \(2\)-burle coin, he can pay \(3\) burle without change by paying with one \(1\)-burle coin and one \(2\)-burle coin, he cannot pay \(4\) burle without change (moreover, he cannot pay this amount at all). So for \(a=1\) and \(b=1\) the answer is \(s=4\).
|
The first line of the input contains an integer \(t\) (\(1 \le t \le 10^4\)) β the number of test cases in the test.The description of each test case consists of one line containing two integers \(a_i\) and \(b_i\) (\(0 \le a_i, b_i \le 10^8\)) β the number of \(1\)-burle coins and \(2\)-burles coins Vasya has respectively.
|
For each test case, on a separate line print one integer \(s\) (\(s > 0\)): the minimum positive integer amount of money that Vasya cannot pay without change or pay at all.
|
The first test case of the example is clarified into the main part of the statement. In the second test case, Vasya has only \(1\) burle coins, and he can collect either any amount from \(1\) to \(4\), but \(5\) can't. In the second test case, Vasya has only \(2\) burle coins, and he cannot pay \(1\) burle without change. In the fourth test case you don't have any coins, and he can't even pay \(1\) burle.
|
Input: 51 14 00 20 02314 2374 | Output: 4 5 1 1 7063
|
Beginner
| 2 | 804 | 325 | 172 | 16 |
1,375 |
F
|
1375F
|
F. Integer Game
| 2,600 |
constructive algorithms; games; interactive; math
|
This is an interactive problem.Anton and Harris are playing a game to decide which of them is the king of problemsetting.There are three piles of stones, initially containing \(a\), \(b\), and \(c\) stones, where \(a\), \(b\), and \(c\) are distinct positive integers. On each turn of the game, the following sequence of events takes place: The first player chooses a positive integer \(y\) and provides it to the second player. The second player adds \(y\) stones to one of the piles, with the condition that he cannot choose the same pile in two consecutive turns. The second player loses if, at any point, two of the piles contain the same number of stones. The first player loses if \(1000\) turns have passed without the second player losing.Feeling confident in his skills, Anton decided to let Harris choose whether he wants to go first or second. Help Harris defeat Anton and become the king of problemsetting!
|
The first line of input contains three distinct positive integers \(a\), \(b\), and \(c\) (\(1 \le a, b, c \le 10^9\)) β the initial number of stones in piles \(1\), \(2\), and \(3\) respectively.
|
In the sample input, the piles initially have \(5\), \(2\), and \(6\) stones. Harris decides to go first and provides the number \(2\) to Anton. Anton adds \(2\) stones to the third pile, which results in \(5\), \(2\), and \(8\).In the next turn, Harris chooses \(3\). Note that Anton cannot add the stones to the third pile since he chose the third pile in the previous turn. Anton realizes that he has no valid moves left and reluctantly recognizes Harris as the king.
|
Input: 5 2 6 3 0 | Output: First 2 3
|
Expert
| 4 | 918 | 196 | 0 | 13 |
|
1,893 |
D
|
1893D
|
D. Colorful Constructive
| 2,600 |
constructive algorithms; data structures; greedy
|
You have \(n\) colored cubes, the \(i\)-th cube has color \(a_i\).You need to distribute all the cubes on shelves. There are a total of \(m\) shelves, the \(i\)-th shelf can hold \(s_i\) cubes. Also, \(s_1 + s_2 + \ldots + s_m = n\).Suppose on a shelf of size \(k\) there are cubes of colors \(c_1, c_2, \ldots, c_k\), in this order. Then we define the colorfulness of the shelf as the minimum distance between two different cubes of the same color on the shelf. If all the cubes on the shelf have different colors, then the colorfulness is considered to be equal to the size of the shelf, that is, the number \(k\).More formally, the colorfulness of \(c_1, c_2, \ldots, c_k\) is defined as follows: If all the colors \(c_1, c_2, \ldots, c_k\) are different, the colorfulness is considered to be \(k\). Otherwise, the colorfulness is considered to be the smallest integer \(x \geq 1\) such that there exists an index \(i\) \((1 \le i \le k - x)\) such that \(c_i = c_{i+x}\).For each shelf, you are given the minimum required colorfulness, that is, you are given numbers \(d_1, d_2, \ldots, d_m\), which mean that shelf \(i\) must have a colorfulness \(\geq d_i\) for all \(i\).Distribute the available cubes among the shelves to ensure the required colorfulness, or report that it is impossible.
|
Each test contains multiple test cases. The first line contains a single integer \(t\) \((1 \leq t \leq 10^4)\) β the number of test cases. The description of the test cases follows.The first line of each test case contains two integers \(n, m\) \((1 \leq m \leq n \leq 2 \cdot 10^5)\) β the number of cubes and the number of shelves to distribute them to.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) \((1 \leq a_i \leq n)\) β the colors of the cubes.The third line of each test case contains \(m\) integers \(s_1, s_2, \ldots, s_m\) \((1 \leq s_i \leq n)\) β the sizes of the shelves. It's guaranteed, that \(s_1 + \ldots + s_m = n\).The fourth line of each test case contains \(m\) integers \(d_1, d_2, \ldots, d_m\) \((1 \leq d_i \leq s_i)\) β the minimum required colorfulness of the shelves.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, if it is impossible to distribute the cubes on the shelves satisfying all the requirements, output a single number \(-1\). Otherwise, output \(m\) lines, where the \(i\)-th line should contain \(s_i\) numbers representing the colors of the cubes on the \(i\)-th shelf, in the appropriate order.
|
Input: 610 31 1 1 1 2 2 2 3 3 46 2 24 1 18 27 7 7 7 8 8 8 84 42 25 15 4 3 2 1537 31 2 2 2 2 3 41 2 41 2 412 76 6 6 6 6 6 6 6 6 7 8 92 2 2 2 2 1 11 2 2 2 1 1 120 211 20 15 6 8 18 12 16 8 20 10 12 3 12 20 11 15 8 17 178 123 5 | Output: 1 3 4 2 1 3 1 1 2 2 8 7 8 7 8 7 8 7 2 4 5 3 1 -1 6 6 7 6 8 6 9 6 6 6 6 6 12 17 20 15 8 20 16 11 15 20 17 12 10 8 3 18 12 11 8 6
|
Expert
| 3 | 1,296 | 927 | 314 | 18 |
|
1,716 |
A
|
1716A
|
A. 2-3 Moves
| 800 |
greedy; math
|
You are standing at the point \(0\) on a coordinate line. Your goal is to reach the point \(n\). In one minute, you can move by \(2\) or by \(3\) to the left or to the right (i. e., if your current coordinate is \(x\), it can become \(x-3\), \(x-2\), \(x+2\) or \(x+3\)). Note that the new coordinate can become negative.Your task is to find the minimum number of minutes required to get from the point \(0\) to the point \(n\).You have to answer \(t\) independent test cases.
|
The first line of the input contains one integer \(t\) (\(1 \le t \le 10^4\)) β the number of test cases. Then \(t\) lines describing the test cases follow.The \(i\)-th of these lines contains one integer \(n\) (\(1 \le n \le 10^9\)) β the goal of the \(i\)-th test case.
|
For each test case, print one integer β the minimum number of minutes required to get from the point \(0\) to the point \(n\) for the corresponding test case.
|
Input: 413412 | Output: 2 1 2 4
|
Beginner
| 2 | 476 | 271 | 158 | 17 |
|
748 |
C
|
748C
|
C. Santa Claus and Robot
| 1,400 |
constructive algorithms; math
|
Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p1, p2, ..., pm with integer coordinates, do the following: denote its initial location by p0. First, the robot will move from p0 to p1 along one of the shortest paths between them (please notice that since the robot moves only along the grid lines, there can be several shortest paths). Then, after it reaches p1, it'll move to p2, again, choosing one of the shortest ways, then to p3, and so on, until he has visited all points in the given order. Some of the points in the sequence may coincide, in that case Robot will visit that point several times according to the sequence order.While Santa was away, someone gave a sequence of points to Robot. This sequence is now lost, but Robot saved the protocol of its unit movements. Please, find the minimum possible length of the sequence.
|
The first line of input contains the only positive integer n (1 β€ n β€ 2Β·105) which equals the number of unit segments the robot traveled. The second line contains the movements protocol, which consists of n letters, each being equal either L, or R, or U, or D. k-th letter stands for the direction which Robot traveled the k-th unit segment in: L means that it moved to the left, R β to the right, U β to the top and D β to the bottom. Have a look at the illustrations for better explanation.
|
The only line of input should contain the minimum possible length of the sequence.
|
The illustrations to the first three tests are given below. The last example illustrates that each point in the sequence should be counted as many times as it is presented in the sequence.
|
Input: 4RURD | Output: 2
|
Easy
| 2 | 916 | 492 | 82 | 7 |
1,131 |
A
|
1131A
|
A. Sea Battle
| 800 |
math
|
In order to make the ""Sea Battle"" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of \(w_1\) and a height of \(h_1\), while the second rectangle has a width of \(w_2\) and a height of \(h_2\), where \(w_1 \ge w_2\). In this game, exactly one ship is used, made up of two rectangles. There are no other ships on the field.The rectangles are placed on field in the following way: the second rectangle is on top the first rectangle; they are aligned to the left, i.e. their left sides are on the same line; the rectangles are adjacent to each other without a gap. See the pictures in the notes: the first rectangle is colored red, the second rectangle is colored blue.Formally, let's introduce a coordinate system. Then, the leftmost bottom cell of the first rectangle has coordinates \((1, 1)\), the rightmost top cell of the first rectangle has coordinates \((w_1, h_1)\), the leftmost bottom cell of the second rectangle has coordinates \((1, h_1 + 1)\) and the rightmost top cell of the second rectangle has coordinates \((w_2, h_1 + h_2)\).After the ship is completely destroyed, all cells neighboring by side or a corner with the ship are marked. Of course, only cells, which don't belong to the ship are marked. On the pictures in the notes such cells are colored green.Find out how many cells should be marked after the ship is destroyed. The field of the game is infinite in any direction.
|
Four lines contain integers \(w_1, h_1, w_2\) and \(h_2\) (\(1 \leq w_1, h_1, w_2, h_2 \leq 10^8\), \(w_1 \ge w_2\)) β the width of the first rectangle, the height of the first rectangle, the width of the second rectangle and the height of the second rectangle. You can't rotate the rectangles.
|
Print exactly one integer β the number of cells, which should be marked after the ship is destroyed.
|
In the first example the field looks as follows (the first rectangle is red, the second rectangle is blue, green shows the marked squares): In the second example the field looks as:
|
Input: 2 1 2 1 | Output: 12
|
Beginner
| 1 | 1,485 | 294 | 100 | 11 |
277 |
A
|
277A
|
A. Learning Languages
| 1,400 |
dfs and similar; dsu
|
The ""BerCorp"" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
|
The first line contains two integers n and m (2 β€ n, m β€ 100) β the number of employees and the number of languages.Then n lines follow β each employee's language list. At the beginning of the i-th line is integer ki (0 β€ ki β€ m) β the number of languages the i-th employee knows. Next, the i-th line contains ki integers β aij (1 β€ aij β€ m) β the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.The numbers in the lines are separated by single spaces.
|
Print a single integer β the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
|
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
|
Input: 5 51 22 2 32 3 42 4 51 5 | Output: 0
|
Easy
| 2 | 704 | 568 | 177 | 2 |
1,765 |
H
|
1765H
|
H. Hospital Queue
| 2,200 |
binary search; graphs; greedy; implementation
|
There are \(n\) people (numbered from \(1\) to \(n\)) signed up for a doctor's appointment. The doctor has to choose in which order he will appoint these people. The \(i\)-th patient should be appointed among the first \(p_i\) people. There are also \(m\) restrictions of the following format: the \(i\)-th restriction is denoted by two integers \((a_i, b_i)\) and means that the patient with the index \(a_i\) should be appointed earlier than the patient with the index \(b_i\).For example, if \(n = 4\), \(p = [2, 3, 2, 4]\), \(m = 1\), \(a = [3]\) and \(b = [1]\), then the only order of appointment of patients that does not violate the restrictions is \([3, 1, 2, 4]\). For \(n =3\), \(p = [3, 3, 3]\), \(m = 0\), \(a = []\) and \(b = []\), any order of appointment is valid.For each patient, calculate the minimum position in the order that they can have among all possible orderings that don't violate the restrictions.
|
The first line contains two integers \(n\) and \(m\) (\(1 \le n \le 2000\); \(0 \le m \le 2000\)).The second line contains \(n\) integers \(p_1, p_2, \dots, p_n\) (\(1 \le p_i \le n\)).Then \(m\) lines follow. The \(i\)-th of them contains two integers \(a_i\) and \(b_i\) (\(1 \le a_i, b_i \le n\); \(a_i \ne b_i\)). All pairs of \((a_i, b_i)\) are distinct (i. e. if \(i \ne j\), then either \(a_i \ne a_j\), \(b_i \ne b_j\), or both).Additional constraint on the input: there is at least one valid order of patients.
|
Print \(n\) integers, where \(i\)-th integer is equal to the minimum position of \(i\)-th patient in the order, among all valid orders. Positions in the order are numbered from \(1\) to \(n\).
|
In the first example, \([3, 1, 2, 4]\) the only one valid order, so the minimum position of each patient is equal to their position in this order.In the second example, any order is valid, so any patient can be appointed first.In the third example, there are three valid orders: \([4, 2, 3, 1, 5]\), \([3, 4, 2, 1, 5]\) and \([4, 3, 2, 1, 5]\).
|
Input: 4 1 2 3 2 4 3 1 | Output: 2 3 1 4
|
Hard
| 4 | 926 | 519 | 192 | 17 |
1,033 |
A
|
1033A
|
A. King Escape
| 1,000 |
dfs and similar; graphs; implementation
|
Alice and Bob are playing chess on a huge chessboard with dimensions \(n \times n\). Alice has a single piece left β a queen, located at \((a_x, a_y)\), while Bob has only the king standing at \((b_x, b_y)\). Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to seize the victory for himself β he needs to march his king to \((c_x, c_y)\) in order to claim the victory for himself. As Alice is distracted by her sense of superiority, she no longer moves any pieces around, and it is only Bob who makes any turns.Bob will win if he can move his king from \((b_x, b_y)\) to \((c_x, c_y)\) without ever getting in check. Remember that a king can move to any of the \(8\) adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen. Find whether Bob can win or not.
|
The first line contains a single integer \(n\) (\(3 \leq n \leq 1000\)) β the dimensions of the chessboard.The second line contains two integers \(a_x\) and \(a_y\) (\(1 \leq a_x, a_y \leq n\)) β the coordinates of Alice's queen.The third line contains two integers \(b_x\) and \(b_y\) (\(1 \leq b_x, b_y \leq n\)) β the coordinates of Bob's king.The fourth line contains two integers \(c_x\) and \(c_y\) (\(1 \leq c_x, c_y \leq n\)) β the coordinates of the location that Bob wants to get to.It is guaranteed that Bob's king is currently not in check and the target location is not in check either.Furthermore, the king is not located on the same square as the queen (i.e. \(a_x \neq b_x\) or \(a_y \neq b_y\)), and the target does coincide neither with the queen's position (i.e. \(c_x \neq a_x\) or \(c_y \neq a_y\)) nor with the king's position (i.e. \(c_x \neq b_x\) or \(c_y \neq b_y\)).
|
Print ""YES"" (without quotes) if Bob can get from \((b_x, b_y)\) to \((c_x, c_y)\) without ever getting in check, otherwise print ""NO"".You can print each letter in any case (upper or lower).
|
In the diagrams below, the squares controlled by the black queen are marked red, and the target square is marked blue.In the first case, the king can move, for instance, via the squares \((2, 3)\) and \((3, 2)\). Note that the direct route through \((2, 2)\) goes through check. In the second case, the queen watches the fourth rank, and the king has no means of crossing it. In the third case, the queen watches the third file.
|
Input: 84 41 33 1 | Output: YES
|
Beginner
| 3 | 887 | 893 | 193 | 10 |
2,120 |
D
|
2120D
|
D. Matrix game
| 1,800 |
combinatorics; math
|
Aryan and Harshith play a game. They both start with three integers \(a\), \(b\), and \(k\). Aryan then gives Harshith two integers \(n\) and \(m\). Harshith then gives Aryan a matrix \(X\) with \(n\) rows and \(m\) columns, such that each of the elements of \(X\) is between \(1\) and \(k\)(inclusive). After that, Aryan wins if he can find a submatrix\(^{\text{β}}\) \(Y\) of \(X\) with \(a\) rows and \(b\) columns such that all elements of \(Y\) are equal.For example, when \(a=2, b=2, k=6, n=3\) and \(m=3\), if Harshith gives Aryan the matrix below, it is a win for Aryan as it has a submatrix of size \(2\times 2\) with all elements equal to \(1\) as shown below. Example of a matrix where Aryan wins Aryan gives you the values of \(a\), \(b\), and \(k\). He asks you to find the lexicographically minimum tuple \((n,m)\) that he should give to Harshith such that Aryan always wins. Help Aryan win the game. Assume that Harshith plays optimally. The values of \(n\) and \(m\) can be large, so output them modulo \(10^9+7\). A tuple \((n_1, m_1)\) is said to be lexicographically smaller than \((n_2, m_2)\) if either \(n_1<n_2\) or \(n_1=n_2\) and \(m_1<m_2\).\(^{\text{β}}\)A submatrix of a matrix is obtained by removing some rows and/or columns from the original matrix.
|
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. Each test case contains a single line with three space-separated integers \(a, b\) and \(k\) (\(1\leq a,b,k\leq 10^5\)).It is guaranteed that the sum of \(\max(a, b, k)\) over all test cases does not exceed \(10^5\).
|
For each test case, output a single line containing two space-separated integers \(n\) and \(m\), denoting the answer to the problem. The values of \(n\) and \(m\) can be large, so output them modulo \(10^9+7\).
|
For the first test case, every \(n\times m\) matrix contains a \(1\times 1\) submatrix with all elements equal. \((1,1)\) is the lexicographically minimum tuple among all of them.For the second test case, it can be verified that whatever \(3\times 7\) matrix Harshith gives to Aryan, Aryan can always win by finding a \(2\times 2\) submatrix with all elements equal. \((3,7)\) is also the lexicographically minimum tuple among all possible tuples where Aryan always wins.
|
Input: 31 1 52 2 290000 80000 70000 | Output: 1 1 3 7 299929959 603196135
|
Medium
| 2 | 1,280 | 378 | 211 | 21 |
1,045 |
I
|
1045I
|
I. Palindrome Pairs
| 1,600 |
hashing; strings
|
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say ""aab"" and ""abcac"", and you concatenate them into ""aababcac"", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation ""aabccbaa""). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices \((i,j)\) is considered the same as the pair \((j,i)\).
|
The first line contains a positive integer \(N\) (\(1 \le N \le 100\,000\)), representing the length of the input array.Eacg of the next \(N\) lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array. The total number of characters in the input array will be less than \(1\,000\,000\).
|
Output one number, representing how many palindrome pairs there are in the array.
|
The first example: aa \(+\) bb \(\to\) abba. The second example: aab \(+\) abcac \(=\) aababcac \(\to\) aabccbaa aab \(+\) aa \(=\) aabaa abcac \(+\) aa \(=\) abcacaa \(\to\) aacbcaa dffe \(+\) ed \(=\) dffeed \(\to\) fdeedf dffe \(+\) aade \(=\) dffeaade \(\to\) adfaafde ed \(+\) aade \(=\) edaade \(\to\) aeddea
|
Input: 3aabbcd | Output: 1
|
Medium
| 2 | 1,156 | 342 | 81 | 10 |
257 |
B
|
257B
|
B. Playing Cubes
| 1,300 |
games; greedy; implementation
|
Petya and Vasya decided to play a little. They found n red cubes and m blue cubes. The game goes like that: the players take turns to choose a cube of some color (red or blue) and put it in a line from left to right (overall the line will have n + m cubes). Petya moves first. Petya's task is to get as many pairs of neighbouring cubes of the same color as possible. Vasya's task is to get as many pairs of neighbouring cubes of different colors as possible. The number of Petya's points in the game is the number of pairs of neighboring cubes of the same color in the line, the number of Vasya's points in the game is the number of neighbouring cubes of the different color in the line. Your task is to calculate the score at the end of the game (Petya's and Vasya's points, correspondingly), if both boys are playing optimally well. To ""play optimally well"" first of all means to maximize the number of one's points, and second β to minimize the number of the opponent's points.
|
The only line contains two space-separated integers n and m (1 β€ n, m β€ 105) β the number of red and blue cubes, correspondingly.
|
On a single line print two space-separated integers β the number of Petya's and Vasya's points correspondingly provided that both players play optimally well.
|
In the first test sample the optimal strategy for Petya is to put the blue cube in the line. After that there will be only red cubes left, so by the end of the game the line of cubes from left to right will look as [blue, red, red, red]. So, Petya gets 2 points and Vasya gets 1 point. If Petya would choose the red cube during his first move, then, provided that both boys play optimally well, Petya would get 1 point and Vasya would get 2 points.
|
Input: 3 1 | Output: 2 1
|
Easy
| 3 | 982 | 129 | 158 | 2 |
1,025 |
A
|
1025A
|
A. Doggo Recoloring
| 900 |
implementation; sortings
|
Panic is rising in the committee for doggo standardization β the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive.The committee rules strictly prohibit even the smallest diversity between doggos and hence all the puppies should be of the same color. Thus Slava, the committee employee, has been assigned the task to recolor some puppies into other colors in order to eliminate the difference and make all the puppies have one common color.Unfortunately, due to bureaucratic reasons and restricted budget, there's only one operation Slava can perform: he can choose a color \(x\) such that there are currently at least two puppies of color \(x\) and recolor all puppies of the color \(x\) into some arbitrary color \(y\). Luckily, this operation can be applied multiple times (including zero).For example, if the number of puppies is \(7\) and their colors are represented as the string ""abababc"", then in one operation Slava can get the results ""zbzbzbc"", ""bbbbbbc"", ""aaaaaac"", ""acacacc"" and others. However, if the current color sequence is ""abababc"", then he can't choose \(x\)='c' right now, because currently only one puppy has the color 'c'.Help Slava and the committee determine whether it is possible to standardize all the puppies, i.e. after Slava's operations all the puppies should have the same color.
|
The first line contains a single integer \(n\) (\(1 \le n \le 10^5\)) β the number of puppies.The second line contains a string \(s\) of length \(n\) consisting of lowercase Latin letters, where the \(i\)-th symbol denotes the \(i\)-th puppy's color.
|
If it's possible to recolor all puppies into one color, print ""Yes"".Otherwise print ""No"".Output the answer without quotation signs.
|
In the first example Slava can perform the following steps: take all puppies of color 'a' (a total of two) and recolor them into 'b'; take all puppies of color 'd' (a total of two) and recolor them into 'c'; take all puppies of color 'b' (three puppies for now) and recolor them into 'c'. In the second example it's impossible to recolor any of the puppies.In the third example all the puppies' colors are the same; thus there's no need to recolor anything.
|
Input: 6aabddc | Output: Yes
|
Beginner
| 2 | 1,452 | 250 | 135 | 10 |
1,957 |
E
|
1957E
|
E. Carousel of Combinations
| 2,400 |
brute force; combinatorics; dp; math; number theory
|
You are given an integer \(n\). The function \(C(i,k)\) represents the number of distinct ways you can select \(k\) distinct numbers from the set {\(1, 2, \ldots, i\)} and arrange them in a circle\(^\dagger\).Find the value of $$$\( \sum\limits_{i=1}^n \sum\limits_{j=1}^i \left( C(i,j) \bmod j \right). \)\( Here, the operation \)x \bmod y\( denotes the remainder from dividing \)x\( by \)y\(.Since this value can be very large, find it modulo \)10^9+7\(.\)^\dagger\( In a circular arrangement, sequences are considered identical if one can be rotated to match the other. For instance, \)[1, 2, 3]\( and \)[2, 3, 1]$$$ are equivalent in a circle.
|
The first line contains a single integer \(t\) (\(1 \leq t \leq 10^5\)) β the number of test cases.The only line of each test case contains a single integer \(n\) (\(1 \le n \le 10^6\)).
|
For each test case, output a single integer on a new line β the value of the expression to be calculated modulo \(10^9+7\).
|
In the first test case, \(C(1,1) \bmod 1 = 0\).In the second test case: \(C(1,1)=1\) (the arrangements are: \([1]\)); \(C(2,1)=2\) (the arrangements are: \([1]\), \([2]\)); \(C(2,2)=1\) (the arrangements are: \([1, 2]\)); \(C(3,1)=3\) (the arrangements are: \([1]\), \([2]\), \([3]\)); \(C(3,2)=3\) (the arrangements are: \([1, 2]\), \([2, 3]\), \([3, 1]\)); \(C(3,3)=2\) (the arrangements are: \([1, 2, 3]\), \([1, 3, 2]\)). In total, \(\left(C(1,1) \bmod 1\right) + \left(C(2,1) \bmod 1\right) + \left(C(2,2) \bmod 2\right) + \left(C(3,1) \bmod 1\right) + \left(C(3,2) \bmod 2\right) + \left(C(3,3) \bmod 3\right) = 4\).
|
Input: 4136314159 | Output: 0 4 24 78926217
|
Expert
| 5 | 647 | 186 | 123 | 19 |
868 |
A
|
868A
|
A. Bark to Unlock
| 900 |
brute force; implementation; strings
|
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not.
|
The first line contains two lowercase English letters β the password on the phone.The second line contains single integer n (1 β€ n β€ 100) β the number of words Kashtanka knows.The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct.
|
Print ""YES"" if Kashtanka can bark several words in a line forming a string containing the password, and ""NO"" otherwise.You can print each letter in arbitrary case (upper or lower).
|
In the first example the password is ""ya"", and Kashtanka can bark ""oy"" and then ""ah"", and then ""ha"" to form the string ""oyahha"" which contains the password. So, the answer is ""YES"".In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark ""ht"" and then ""tp"" producing ""http"", but it doesn't contain the password ""hp"" as a substring.In the third example the string ""hahahaha"" contains ""ah"" as a substring.
|
Input: ya4ahoytoha | Output: YES
|
Beginner
| 3 | 684 | 317 | 184 | 8 |
42 |
D
|
42D
|
D. Strange town
| 2,300 |
constructive algorithms; math
|
Volodya has recently visited a very odd town. There are N tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing tour has the same total price! That is, if we choose any city sightseeing tour β a cycle which visits every attraction exactly once β the sum of the costs of the tour roads is independent of the tour. Volodya is curious if you can find such price system with all road prices not greater than 1000.
|
Input contains just one natural number (3 β€ N β€ 20) β the number of town attractions.
|
Output should contain N rows containing N positive integer numbers each β the adjacency matrix of the prices graph (thus, j-th number in i-th row should be equal to the price of the road between the j-th and the i-th attraction). Diagonal numbers should be equal to zero. All numbers should not be greater than 1000. All prices should be positive and pairwise distinct. If there are several solutions, output any of them.
|
Input: 3 | Output: 0 3 4 3 0 5 4 5 0
|
Expert
| 2 | 615 | 85 | 421 | 0 |
|
1,116 |
A2
|
1116A2
|
A2. Generate equal superposition of four basis states
| 0 |
*special
|
You are given \(N\) qubits in the zero state \(|0...0 \rangle\). You are also given four distinct bit vectors which describe four different basis states on \(N\) qubits \(|\psi_i \rangle\).Your task is to generate a state which is an equal superposition of the given basis states:$$$\(|S \rangle = \frac{1}{2} \big( |\psi_0 \rangle + |\psi_1 \rangle + |\psi_2 \rangle + |\psi_3 \rangle \big)\)\(You have to implement an operation which takes the following inputs: an array of \)N\( (\)2 \le N \le 16\() qubits, a two-dimensional array of Boolean values \)bits\( representing the basis states \)|\psi_i \rangle\(. \)bits\( will have exactly 4 elements, each of \)bits[i]\( describing the basis state \)|\psi_i \rangle\(. Each of \)bits[i]\( will have \)N\( elements, \)bits[i][j]\( giving the state of qubit \)j\( in the basis state \)|\psi_i \rangle\(. Bit values true and false corresponding to \)|1 \rangle\( and \)|0 \rangle\( states, respectively; for example, for \)N = 2\( an array [false, true] will represent the basis state \)|01\rangle\(. Each pair of \)bits[i]\( and \)bits[j]\( will differ in at least one position for \)i \neq j$$$.The operation doesn't have an output; its ""output"" is the state in which it leaves the qubits.Your code should have the following signature:namespace Solution { open Microsoft.Quantum.Primitive; open Microsoft.Quantum.Canon; operation Solve (qs : Qubit[], bits : Bool[][]) : Unit { // your code here }}
|
Beginner
| 1 | 1,449 | 0 | 0 | 11 |
||||
1,290 |
E
|
1290E
|
E. Cartesian Tree
| 3,300 |
data structures
|
Ildar is the algorithm teacher of William and Harris. Today, Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be \(x\); Remove element on the position \(x\) from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position \(x\) which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence \(4, 2, 7, 3, 5, 6, 1\): After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence \(a\).In the \(i\)-th round, he inserts an element with value \(i\) somewhere in \(a\). Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence \(a\)?Node \(v\) is in the node \(u\) subtree if and only if \(v = u\) or \(v\) is in the subtree of one of the vertex \(u\) children. The size of the subtree of node \(u\) is the number of nodes \(v\) such that \(v\) is in the subtree of \(u\).Ildar will do \(n\) rounds in total. The homework is the sequence of answers to the \(n\) questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence \(a\) from William. However, he has no idea how to find the answers to the \(n\) questions. Help Harris!
|
The first line contains a single integer \(n\) (\(1 \le n \le 150000\)).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le n\)). It is guarenteed that each integer from \(1\) to \(n\) appears in the sequence exactly once.
|
Print \(n\) lines, \(i\)-th line should contain a single integer β the answer to the \(i\)-th question.
|
After the first round, the sequence is \(1\). The tree is The answer is \(1\).After the second round, the sequence is \(2, 1\). The tree is The answer is \(2+1=3\).After the third round, the sequence is \(2, 1, 3\). The tree is The answer is \(2+1+3=6\).After the fourth round, the sequence is \(2, 4, 1, 3\). The tree is The answer is \(1+4+1+2=8\).After the fifth round, the sequence is \(2, 4, 1, 5, 3\). The tree is The answer is \(1+3+1+5+1=11\).
|
Input: 5 2 4 1 5 3 | Output: 1 3 6 8 11
|
Master
| 1 | 1,848 | 253 | 103 | 12 |
1,866 |
A
|
1866A
|
A. Ambitious Kid
| 800 |
math
|
Chaneka, Pak Chanek's child, is an ambitious kid, so Pak Chanek gives her the following problem to test her ambition.Given an array of integers \([A_1, A_2, A_3, \ldots, A_N]\). In one operation, Chaneka can choose one element, then increase or decrease the element's value by \(1\). Chaneka can do that operation multiple times, even for different elements.What is the minimum number of operations that must be done to make it such that \(A_1 \times A_2 \times A_3 \times \ldots \times A_N = 0\)?
|
The first line contains a single integer \(N\) (\(1 \leq N \leq 10^5\)).The second line contains \(N\) integers \(A_1, A_2, A_3, \ldots, A_N\) (\(-10^5 \leq A_i \leq 10^5\)).
|
An integer representing the minimum number of operations that must be done to make it such that \(A_1 \times A_2 \times A_3 \times \ldots \times A_N = 0\).
|
In the first example, initially, \(A_1\times A_2\times A_3=2\times(-6)\times5=-60\). Chaneka can do the following sequence of operations: Decrease the value of \(A_1\) by \(1\). Then, \(A_1\times A_2\times A_3=1\times(-6)\times5=-30\) Decrease the value of \(A_1\) by \(1\). Then, \(A_1\times A_2\times A_3=0\times(-6)\times5=0\) In the third example, Chaneka does not have to do any operations, because from the start, it already holds that \(A_1\times A_2\times A_3\times A_4\times A_5=0\times(-1)\times0\times1\times0=0\)
|
Input: 3 2 -6 5 | Output: 2
|
Beginner
| 1 | 497 | 174 | 155 | 18 |
1,712 |
A
|
1712A
|
A. Wonderful Permutation
| 800 |
greedy; implementation
|
God's Blessing on This PermutationForces!A Random PebbleYou are given a permutation \(p_1,p_2,\ldots,p_n\) of length \(n\) and a positive integer \(k \le n\). In one operation you can choose two indices \(i\) and \(j\) (\(1 \le i < j \le n\)) and swap \(p_i\) with \(p_j\).Find the minimum number of operations needed to make the sum \(p_1 + p_2 + \ldots + p_k\) as small as possible.A permutation is an array consisting of \(n\) distinct integers from \(1\) to \(n\) in arbitrary order. For example, \([2,3,1,5,4]\) is a permutation, but \([1,2,2]\) is not a permutation (\(2\) appears twice in the array) and \([1,3,4]\) is also not a permutation (\(n=3\) but there is \(4\) in the array).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 100\)). Description of the test cases follows.The first line of each test case contains two integers \(n\) and \(k\) (\(1 \le k \le n \le 100\)).The second line of each test case contains \(n\) integers \(p_1,p_2,\ldots,p_n\) (\(1 \le p_i \le n\)). It is guaranteed that the given numbers form a permutation of length \(n\).
|
For each test case print one integer β the minimum number of operations needed to make the sum \(p_1 + p_2 + \ldots + p_k\) as small as possible.
|
In the first test case, the value of \(p_1 + p_2 + \ldots + p_k\) is initially equal to \(2\), but the smallest possible value is \(1\). You can achieve it by swapping \(p_1\) with \(p_3\), resulting in the permutation \([1, 3, 2]\).In the second test case, the sum is already as small as possible, so the answer is \(0\).
|
Input: 43 12 3 13 31 2 34 23 4 1 21 11 | Output: 1 0 2 0
|
Beginner
| 2 | 691 | 434 | 145 | 17 |
2,129 |
D
|
2129D
|
D. Permutation Blackhole
| 2,600 |
brute force; combinatorics; dp; implementation; math
|
For a permutation \(p_1, p_2, \ldots, p_n\) of length \(n\), the corresponding coloring sequence \(s\) can be obtained by the following coloring process: Initially, there are \(n\) white cells indexed from \(1\) to \(n\) from left to right. At second \(0\), the score of each cell is \(0\). At second \(i\) (\(1 \le i \le n\)), If \(i > 1\), find the nearest black cell to the cell \(p_i\), and increase the score of that cell by \(1\). In case there are multiple nearest black cells, choose the cell with the lowest index. Cell \(y\) is called the nearest black cell to cell \(x\) only if cell \(y\) is black and there is no black cell \(z\) satisfying \(|x-z|<|x-y|\). Color the cell \(p_i\) black. After all cells are colored black, denoting \(s_i\) as the score of cell \(i\) (\(1 \le i \le n\)), we get the coloring sequence \(s\).You might want to read the notes for a better understanding.You are given an incomplete coloring sequence \(s\), where some \(s_i\) are already fixed, while others are not yet determined. Count how many different permutations \(p\) can produce this coloring sequence. Since the answer may be large, you need to output it modulo \(998\,244\,353\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^3\)). The description of the test cases follows. For each test case, the first line contains an integer \(n\) (\(2 \leq n \leq 100\)).The second line contains \(n\) integers \(s_1, s_2, \ldots, s_n\) (\(-1 \leq s_i \leq n-1\)). Here, \(s_i=-1\) means \(s_i\) has not been determined. And \(s_i \neq -1\) means \(s_i\) has already been fixed.It is guaranteed that the sum of \(n^2\) over all test cases does not exceed \(10^4\).
|
For each test case, output the total of different permutations \(p_1, p_2, \ldots, p_n\) that can produce the coloring sequence, modulo \(998\,244\,353\).
|
In the first test case, \(p=[3,1,2]\) and \(p=[3,2,1]\) can produce the coloring sequence \(s=[-1,-1,1]\).For \(p=[3,1,2]\), the coloring process is shown as the following picture. The grid at seconds \(0\), \(1\), \(2\), and \(3\) respectively when \(p=[3,1,2]\). For \(p=[3,2,1]\), the coloring process is shown as the following picture. The grid at seconds \(0\), \(1\), \(2\), and \(3\) respectively when \(p=[3,2,1]\).
|
Input: 93-1 -1 13-1 -1 -14-1 2 -1 04-1 0 1 -15-1 3 -1 0 -154 4 4 4 451 0 1 2 06-1 1 -1 -1 3 013-1 -1 -1 -1 -1 -1 2 -1 -1 -1 -1 -1 -1 | Output: 2 6 4 3 8 0 4 10 867303072
|
Expert
| 5 | 1,182 | 540 | 154 | 21 |
1,055 |
C
|
1055C
|
C. Lucky Days
| 1,900 |
math; number theory
|
Bob and Alice are often participating in various programming competitions. Like many competitive programmers, Alice and Bob have good and bad days. They noticed, that their lucky and unlucky days are repeating with some period. For example, for Alice days \([l_a; r_a]\) are lucky, then there are some unlucky days: \([r_a + 1; l_a + t_a - 1]\), and then there are lucky days again: \([l_a + t_a; r_a + t_a]\) and so on. In other words, the day is lucky for Alice if it lies in the segment \([l_a + k t_a; r_a + k t_a]\) for some non-negative integer \(k\).The Bob's lucky day have similar structure, however the parameters of his sequence are different: \(l_b\), \(r_b\), \(t_b\). So a day is a lucky for Bob if it lies in a segment \([l_b + k t_b; r_b + k t_b]\), for some non-negative integer \(k\).Alice and Bob want to participate in team competitions together and so they want to find out what is the largest possible number of consecutive days, which are lucky for both Alice and Bob.
|
The first line contains three integers \(l_a\), \(r_a\), \(t_a\) (\(0 \le l_a \le r_a \le t_a - 1, 2 \le t_a \le 10^9\)) and describes Alice's lucky days.The second line contains three integers \(l_b\), \(r_b\), \(t_b\) (\(0 \le l_b \le r_b \le t_b - 1, 2 \le t_b \le 10^9\)) and describes Bob's lucky days.It is guaranteed that both Alice and Bob have some unlucky days.
|
Print one integer: the maximum number of days in the row that are lucky for both Alice and Bob.
|
The graphs below correspond to the two sample tests and show the lucky and unlucky days of Alice and Bob as well as the possible solutions for these tests.
|
Input: 0 2 51 3 5 | Output: 2
|
Hard
| 2 | 991 | 371 | 95 | 10 |
1,038 |
E
|
1038E
|
E. Maximum Matching
| 2,400 |
bitmasks; brute force; dfs and similar; dp; graphs
|
You are given \(n\) blocks, each of them is of the form [color\(_1\)|value|color\(_2\)], where the block can also be flipped to get [color\(_2\)|value|color\(_1\)]. A sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is valid if the left color of the B is the same as the right color of the A and the right color of the B is the same as the left color of C.The value of the sequence is defined as the sum of the values of the blocks in this sequence.Find the maximum possible value of the valid sequence that can be constructed from the subset of the given blocks. The blocks from the subset can be reordered and flipped if necessary. Each block can be used at most once in the sequence.
|
The first line of input contains a single integer \(n\) (\(1 \le n \le 100\)) β the number of given blocks.Each of the following \(n\) lines describes corresponding block and consists of \(\mathrm{color}_{1,i}\), \(\mathrm{value}_i\) and \(\mathrm{color}_{2,i}\) (\(1 \le \mathrm{color}_{1,i}, \mathrm{color}_{2,i} \le 4\), \(1 \le \mathrm{value}_i \le 100\,000\)).
|
Print exactly one integer β the maximum total value of the subset of blocks, which makes a valid sequence.
|
In the first example, it is possible to form a valid sequence from all blocks.One of the valid sequences is the following:[4|2|1] [1|32|2] [2|8|3] [3|16|3] [3|4|4] [4|1|2]The first block from the input ([2|1|4] \(\to\) [4|1|2]) and second ([1|2|4] \(\to\) [4|2|1]) are flipped.In the second example, the optimal answers can be formed from the first three blocks as in the following (the second or the third block from the input is flipped):[2|100000|1] [1|100000|1] [1|100000|2]In the third example, it is not possible to form a valid sequence of two or more blocks, so the answer is a sequence consisting only of the first block since it is the block with the largest value.
|
Input: 62 1 41 2 43 4 42 8 33 16 31 32 2 | Output: 63
|
Expert
| 5 | 794 | 365 | 106 | 10 |
1,089 |
A
|
1089A
|
A. Alice the Fan
| 2,200 |
dp
|
Alice is a big fan of volleyball and especially of the very strong ""Team A"".Volleyball match consists of up to five sets. During each set teams score one point for winning a ball. The first four sets are played until one of the teams scores at least 25 points and the fifth set is played until one of the teams scores at least 15 points. Moreover, if one of the teams scores 25 (or 15 in the fifth set) points while the other team scores 24 (or 14 in the fifth set), the set is played until the absolute difference between teams' points becomes two. The match ends when one of the teams wins three sets. The match score is the number of sets won by each team.Alice found a book containing all the results of all matches played by ""Team A"". The book is old, and some parts of the book became unreadable. Alice can not read the information on how many sets each of the teams won, she can not read the information on how many points each of the teams scored in each set, she even does not know the number of sets played in a match. The only information she has is the total number of points scored by each of the teams in all the sets during a single match.Alice wonders what is the best match score ""Team A"" could achieve in each of the matches. The bigger is the difference between the number of sets won by ""Team A"" and their opponent, the better is the match score. Find the best match score or conclude that no match could end like that. If there is a solution, then find any possible score for each set that results in the best match score.
|
The first line contains a single integer \(m\) (\(1 \le m \le 50\,000\)) β the number of matches found by Alice in the book.Each of the next \(m\) lines contains two integers \(a\) and \(b\) (\(0 \le a, b \le 200\)) β the number of points scored by ""Team A"" and the number of points scored by their opponents respectively.
|
Output the solution for every match in the same order as they are given in the input. If the teams could not score \(a\) and \(b\) points respectively, output ""Impossible"".Otherwise, output the match score formatted as ""\(x\):\(y\)"", where \(x\) is the number of sets won by ""Team A"" and \(y\) is the number of sets won by their opponent. The next line should contain the set scores in the order they were played. Each set score should be printed in the same format as the match score, with \(x\) being the number of points scored by ""Team A"" in this set, and \(y\) being the number of points scored by their opponent.
|
Input: 6 75 0 90 90 20 0 0 75 78 50 80 100 | Output: 3:0 25:0 25:0 25:0 3:1 25:22 25:22 15:25 25:21 Impossible 0:3 0:25 0:25 0:25 3:0 25:11 28:26 25:13 3:2 25:17 0:25 25:22 15:25 15:11
|
Hard
| 1 | 1,551 | 324 | 626 | 10 |
|
1,252 |
H
|
1252H
|
H. Twin Buildings
| 1,800 |
greedy; implementation
|
As you might already know, space has always been a problem in ICPC Jakarta. To cope with this, ICPC Jakarta is planning to build two new buildings. These buildings should have a shape of a rectangle of the same size. Now, their problem is to find land to build the buildings.There are \(N\) lands available for sale. The \(i^{th}\) land has a rectangular shape of size \(L_i \times W_i\). For a good feng shui, the building's side should be parallel to the land's sides.One way is to build the two buildings on two different lands, one on each land (not necessarily with the same orientation). A building of size \(A \times B\) can be build on the \(i^{th}\) land if and only if at least one of the following is satisfied: \(A \le L_i\) and \(B \le W_i\), or \(A \le W_i\) and \(B \le L_i\). Alternatively, it is also possible to build two buildings of \(A \times B\) on the \(i^{th}\) land with the same orientation. Formally, it is possible to build two buildings of \(A \times B\) on the \(i^{th}\) land if and only if at least one of the following is satisfied: \(A \times 2 \le L_i\) and \(B \le W_i\), or \(A \times 2 \le W_i\) and \(B \le L_i\), or \(A \le L_i\) and \(B \times 2 \le W_i\), or \(A \le W_i\) and \(B \times 2 \le L_i\). Your task in this problem is to help ICPC Jakarta to figure out the largest possible buildings they can build given \(N\) available lands. Note that ICPC Jakarta has to build two buildings of \(A \times B\); output the largest possible for \(A \times B\).
|
Input begins with a line containing an integer: \(N\) (\(1 \le N \le 100\,000\)) representing the number of available lands. The next \(N\) lines each contains two integers: \(L_i\) \(W_i\) (\(1 \le L_i, W_i \le 10^9\)) representing the size of the land.
|
Output in a line a number representing the largest building that ICPC Jakarta can build with exactly one decimal point (see sample input/output for clarity).
|
Explanation for the sample input/output #1Two buildings of \(2.5 \times 5\) can be built both on the first land.Explanation for the sample input/output #2Two buildings of \(2 \times 4\) can be built each on the first and second lands.Explanation for the sample input/output #3Two buildings of \(7 \times 6\) can be built each on the second and third lands.
|
Input: 2 5 5 3 4 | Output: 12.5
|
Medium
| 2 | 1,498 | 254 | 157 | 12 |
1,184 |
C2
|
1184C2
|
C2. Heidi and the Turing Test (Medium)
| 2,200 |
data structures
|
The Cybermen solved that first test much quicker than the Daleks. Luckily for us, the Daleks were angry (shocking!) and they destroyed some of the Cybermen.After the fighting stopped, Heidi gave them another task to waste their time on.There are \(n\) points on a plane. Given a radius \(r\), find the maximum number of points that can be covered by an \(L^1\)-ball with radius \(r\).An \(L^1\)-ball with radius \(r\) and center \((x_0, y_0)\) in a 2D-plane is defined as the set of points \((x, y)\) such that the Manhattan distance between \((x_0, y_0)\) and \((x, y)\) is at most \(r\).Manhattan distance between \((x_0, y_0)\) and \((x, y)\) is defined as \(|x - x_0| + |y - y_0|\).
|
The first line contains two integers \(n, r\) (\(1 \le n \le 300\,000, 1 \le r \le 10^6\)), the number of points and the radius of the ball, respectively. Each of the next \(n\) lines contains integers \(x_i, y_i\) (\(-10^6 \leq x_i, y_i \leq 10^6\)), describing the coordinates of the \(i\)-th point.It is guaranteed, that all points are distinct.
|
Print one integer β the maximum number points that an \(L^1\)-ball with radius \(r\) can cover.
|
In the first example, a ball centered at \((1, 0)\) covers the points \((1, 1)\), \((1, -1)\), \((2, 0)\).In the second example, a ball centered at \((0, 0)\) covers all the points.Note that \(x_0\) and \(y_0\) need not be integer.
|
Input: 5 1 1 1 1 -1 -1 1 -1 -1 2 0 | Output: 3
|
Hard
| 1 | 686 | 348 | 95 | 11 |
1,778 |
A
|
1778A
|
A. Flip Flop Sum
| 800 |
greedy; implementation
|
You are given an array of \(n\) integers \(a_1, a_2, \ldots, a_n\). The integers are either \(1\) or \(-1\). You have to perform the following operation exactly once on the array \(a\): Choose an index \(i\) (\(1 \leq i < n\)) and flip the signs of \(a_i\) and \(a_{i+1}\). Here, flipping the sign means \(-1\) will be \(1\) and \(1\) will be \(-1\). What is the maximum possible value of \(a_1 + a_2 + \ldots + a_n\) after applying the above operation?
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 500\)). Description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(2 \le n \le 10^5\)), the length of the array \(a\).The next line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(a_i = 1\) or \(a_i = -1\)).The sum of \(n\) over all cases doesn't exceed \(10^5\).
|
For each test case, print the maximum possible sum of the array \(a\) you can get in a separate line.
|
In the first case, we can choose index \(4\) and flip the signs of \(a_4\) and \(a_5\). After this operation, the sum will be \(-1+1+1+1+1 = 3\). We can't make the sum larger than this.In the third case, the only option is to choose the index \(1\).
|
Input: 45-1 1 1 -1 -151 1 -1 -1 -121 141 -1 -1 1 | Output: 3 3 -2 4
|
Beginner
| 2 | 453 | 425 | 101 | 17 |
1,254 |
A
|
1254A
|
A. Feeding Chicken
| 1,700 |
constructive algorithms; greedy; implementation
|
Long is a huge fan of CFC (Codeforces Fried Chicken). But the price of CFC is increasing, so he decides to breed the chicken on his own farm.His farm is presented by a rectangle grid with \(r\) rows and \(c\) columns. Some of these cells contain rice, others are empty. \(k\) chickens are living on his farm. The number of chickens is not greater than the number of cells with rice on the farm.Long wants to give his chicken playgrounds by assigning these farm cells to his chickens. He would like to satisfy the following requirements: Each cell of the farm is assigned to exactly one chicken. Each chicken is assigned at least one cell. The set of cells assigned to every chicken forms a connected area. More precisely, if two cells \((x, y)\) and \((u, v)\) are assigned to the same chicken, this chicken is able to walk from \((x, y)\) to \((u, v)\) by passing only its cells and moving from each cell to another cell sharing a side. Long also wants to prevent his chickens from fighting for food. Hence he wants the difference between the maximum and the minimum number of cells with rice assigned to a chicken to be as small as possible. Please help him.
|
Each test contains multiple test cases. The first line contains the number of test cases \(T\) (\(1 \le T \le 2 \cdot 10^4\)). Description of the test cases follows.The first line of each test case contains three integers \(r\), \(c\) and \(k\) (\(1 \leq r, c \leq 100, 1 \leq k \leq 62\)), representing the size of Long's farm and the number of chickens Long has. Each of the next \(r\) lines contains \(c\) characters, each is either ""."" or ""R"", representing an empty cell or a cell with rice. It is guaranteed that the number of chickens is not greater than the number of cells with rice on the farm.It is guaranteed that the sum of \(r \cdot c\) over all test cases does not exceed \(2 \cdot 10^4\).
|
For each test case, print \(r\) lines with \(c\) characters on each line. Each character should be either a lowercase English character, an uppercase English character, or a digit. Two characters should be equal if and only if the two corresponding cells are assigned to the same chicken. Uppercase and lowercase characters are considered different, so ""A"" and ""a"" belong to two different chickens.If there are multiple optimal answers, print any.
|
These pictures explain the sample output. Each color represents one chicken. Cells filled with patterns (not solid colors) contain rice.In the first test case, each chicken has one cell with rice. Hence, the difference between the maximum and the minimum number of cells with rice assigned to a chicken is \(0\).In the second test case, there are \(4\) chickens with \(3\) cells of rice, and \(2\) chickens with \(2\) cells of rice. Hence, the difference between the maximum and the minimum number of cells with rice assigned to a chicken is \(3 - 2 = 1\).In the third test case, each chicken has \(3\) cells with rice. In the last test case, since there are \(62\) chicken with exactly \(62\) cells of rice, each chicken must be assigned to exactly one cell. The sample output is one of the possible way.
|
Input: 4 3 5 3 ..R.. ...R. ....R 6 4 6 R..R R..R RRRR RRRR R..R R..R 5 5 4 RRR.. R.R.. RRR.. R..R. R...R 2 31 62 RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR | Output: 11122 22223 33333 aacc aBBc aBBc CbbA CbbA CCAA 11114 22244 32444 33344 33334 abcdefghijklmnopqrstuvwxyzABCDE FGHIJKLMNOPQRSTUVWXYZ0123456789
|
Medium
| 3 | 1,160 | 707 | 451 | 12 |
1,234 |
C
|
1234C
|
C. Pipes
| 1,500 |
dp; implementation
|
You are given a system of pipes. It consists of two rows, each row consists of \(n\) pipes. The top left pipe has the coordinates \((1, 1)\) and the bottom right β \((2, n)\).There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types: Types of pipes You can turn each of the given pipes \(90\) degrees clockwise or counterclockwise arbitrary (possibly, zero) number of times (so the types \(1\) and \(2\) can become each other and types \(3, 4, 5, 6\) can become each other).You want to turn some pipes in a way that the water flow can start at \((1, 0)\) (to the left of the top left pipe), move to the pipe at \((1, 1)\), flow somehow by connected pipes to the pipe at \((2, n)\) and flow right to \((2, n + 1)\).Pipes are connected if they are adjacent in the system and their ends are connected. Here are examples of connected pipes: Examples of connected pipes Let's describe the problem using some example: The first example input And its solution is below: The first example answer As you can see, the water flow is the poorly drawn blue line. To obtain the answer, we need to turn the pipe at \((1, 2)\) \(90\) degrees clockwise, the pipe at \((2, 3)\) \(90\) degrees, the pipe at \((1, 6)\) \(90\) degrees, the pipe at \((1, 7)\) \(180\) degrees and the pipe at \((2, 7)\) \(180\) degrees. Then the flow of water can reach \((2, n + 1)\) from \((1, 0)\).You have to answer \(q\) independent queries.
|
The first line of the input contains one integer \(q\) (\(1 \le q \le 10^4\)) β the number of queries. Then \(q\) queries follow.Each query consists of exactly three lines. The first line of the query contains one integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β the number of pipes in each row. The next two lines contain a description of the first and the second rows correspondingly. Each row description consists of \(n\) digits from \(1\) to \(6\) without any whitespaces between them, each digit corresponds to the type of pipe in the corresponding cell. See the problem statement to understand which digits correspond to which types of pipes.It is guaranteed that the sum of \(n\) over all queries does not exceed \(2 \cdot 10^5\).
|
For the \(i\)-th query print the answer for it β ""YES"" (without quotes) if it is possible to turn some pipes in a way that the water flow can reach \((2, n + 1)\) from \((1, 0)\), and ""NO"" otherwise.
|
The first query from the example is described in the problem statement.
|
Input: 6 7 2323216 1615124 1 3 4 2 13 24 2 12 34 3 536 345 2 46 54 | Output: YES YES YES NO YES NO
|
Medium
| 2 | 1,478 | 736 | 203 | 12 |
1,776 |
D
|
1776D
|
D. Teamwork
| 2,800 |
constructive algorithms; greedy; math
|
As soon as SWERC starts, your experienced \(3\)-person team immediately realizes that the contest features \(a\) easy problems, \(b\) medium problems, and \(c\) hard problems. Solving a problem will take any of you \(2\), \(3\), or \(4\) time units, depending on whether the problem is easy, medium, or hard. Regardless of the difficulty of the problem, the last time unit spent to solve it has to be spent using your shared computer.You organize your efforts so that each of you starts (and ends) solving problems at integer time units. Any given problem can be solved by only one contestant; it requires a contiguous amount of time (which depends on the difficulty of the problem). None of the \(3\) of you can solve more than one problem at a time, but you can start solving a new problem immediately after finishing one. Similarly, the shared computer cannot be used by more than one of you at a time, but any of you can start using the computer (to complete the problem currently being solved) immediately after someone else stops using it.Given that the contest lasts \(l\) time units, find the maximum number of problems that your team can solve. Additionally, find one way to solve the maximum number of problems.
|
The input has a single line. It contains four integers \(a\), \(b\), \(c\), \(l\) (\(0 \leq a, b, c, \leq 10^4\), \(0 \le l \le 10^5\)) β the number of easy, medium, and hard problems, and the duration of the contest.
|
On the first line, print a single integer \(n\) β the maximum number of problems that your team can solve.Then, on the \(j\)-th of the following \(n\) lines, print three integers \(x_j\), \(p_j\), \(q_j\) (\(1 \leq x \leq 3\), \(0 \leq p_j < q_j \leq l\)) β the contestant that solves the \(j\)-th problem, and the start and end time for solving the \(j\)-th problem (measured as time units elapsed from the beginning of the contest). The difference \(q_j - p_j\) is \(2\), \(3\), or \(4\), depending on the difficulty of the problem.The last \(n\) lines are to be provided in increasing order of end time: \(q_1 < q_2 < \cdots < q_n\). If there are multiple ways to solve \(n\) problems, output any of them.
|
In the first sample, the first contestant solves an easy problem between time \(0\) and time \(2\) while the second contestant solves a medium problem between time \(0\) and time \(3\).In the second sample, the first contestant solves an easy problem between time \(0\) and time \(2\), and then also solves a medium problem between time \(2\) and time \(5\). In the meantime, the second contestant solves another medium problem between time \(0\) and time \(3\), while the third contestant solves a hard problem between time \(0\) and time \(4\).In the third sample, the contest only has medium and hard problems, and there is not enough time to solve any of them.
|
Input: 2 1 1 3 | Output: 2 1 0 2 2 0 3
|
Master
| 3 | 1,221 | 217 | 708 | 17 |
1,603 |
A
|
1603A
|
A. Di-visible Confusion
| 1,300 |
constructive algorithms; math; number theory
|
YouKn0wWho has an integer sequence \(a_1, a_2, \ldots, a_n\). He will perform the following operation until the sequence becomes empty: select an index \(i\) such that \(1 \le i \le |a|\) and \(a_i\) is not divisible by \((i + 1)\), and erase this element from the sequence. Here \(|a|\) is the length of sequence \(a\) at the moment of operation. Note that the sequence \(a\) changes and the next operation is performed on this changed sequence.For example, if \(a=[3,5,4,5]\), then he can select \(i = 2\), because \(a_2 = 5\) is not divisible by \(i+1 = 3\). After this operation the sequence is \([3,4,5]\).Help YouKn0wWho determine if it is possible to erase the whole sequence using the aforementioned operation.
|
The first line contains a single integer \(t\) (\(1 \le t \le 10\,000\)) β the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^5\)).The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^9\)).It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(3 \cdot 10^5\).
|
For each test case, print ""YES"" (without quotes) if it is possible to erase the whole sequence using the aforementioned operation, print ""NO"" (without quotes) otherwise. You can print each letter in any register (upper or lower).
|
In the first test case, YouKn0wWho can perform the following operations (the erased elements are underlined): \([1, \underline{2}, 3] \rightarrow [\underline{1}, 3] \rightarrow [\underline{3}] \rightarrow [\,].\)In the second test case, it is impossible to erase the sequence as \(i\) can only be \(1\), and when \(i=1\), \(a_1 = 2\) is divisible by \(i + 1 = 2\).
|
Input: 5 3 1 2 3 1 2 2 7 7 10 384836991 191890310 576823355 782177068 404011431 818008580 954291757 160449218 155374934 840594328 8 6 69 696 69696 696969 6969696 69696969 696969696 | Output: YES NO YES YES NO
|
Easy
| 3 | 718 | 388 | 233 | 16 |
1,097 |
H
|
1097H
|
H. Mateusz and an Infinite Sequence
| 3,400 |
bitmasks; brute force; dp; strings
|
A Thue-Morse-Radecki-Mateusz sequence (Thorse-Radewoosh sequence in short) is an infinite sequence constructed from a finite sequence \(\mathrm{gen}\) of length \(d\) and an integer \(m\), obtained in the following sequence of steps: In the beginning, we define the one-element sequence \(M_0=(0)\). In the \(k\)-th step, \(k \geq 1\), we define the sequence \(M_k\) to be the concatenation of the \(d\) copies of \(M_{k-1}\). However, each of them is altered slightly β in the \(i\)-th of them (\(1 \leq i \leq d\)), each element \(x\) is changed to \((x+\mathrm{gen}_i) \pmod{m}\). For instance, if we pick \(\mathrm{gen} = (0, \color{blue}{1}, \color{green}{2})\) and \(m = 4\): \(M_0 = (0)\), \(M_1 = (0, \color{blue}{1}, \color{green}{2})\), \(M_2 = (0, 1, 2, \color{blue}{1, 2, 3}, \color{green}{2, 3, 0})\), \(M_3 = (0, 1, 2, 1, 2, 3, 2, 3, 0, \color{blue}{1, 2, 3, 2, 3, 0, 3, 0, 1}, \color{green}{2, 3, 0, 3, 0, 1, 0, 1, 2})\), and so on. As you can see, as long as the first element of \(\mathrm{gen}\) is \(0\), each consecutive step produces a sequence whose prefix is the sequence generated in the previous step. Therefore, we can define the infinite Thorse-Radewoosh sequence \(M_\infty\) as the sequence obtained by applying the step above indefinitely. For the parameters above, \(M_\infty = (0, 1, 2, 1, 2, 3, 2, 3, 0, 1, 2, 3, 2, 3, 0, 3, 0, 1, \dots)\).Mateusz picked a sequence \(\mathrm{gen}\) and an integer \(m\), and used them to obtain a Thorse-Radewoosh sequence \(M_\infty\). He then picked two integers \(l\), \(r\), and wrote down a subsequence of this sequence \(A := ((M_\infty)_l, (M_\infty)_{l+1}, \dots, (M_\infty)_r)\).Note that we use the \(1\)-based indexing both for \(M_\infty\) and \(A\).Mateusz has his favorite sequence \(B\) with length \(n\), and would like to see how large it is compared to \(A\). Let's say that \(B\) majorizes sequence \(X\) of length \(n\) (let's denote it as \(B \geq X\)) if and only if for all \(i \in \{1, 2, \dots, n\}\), we have \(B_i \geq X_i\).He now asks himself how many integers \(x\) in the range \([1, |A| - n + 1]\) there are such that \(B \geq (A_x, A_{x+1}, A_{x+2}, \dots, A_{x+n-1})\). As both sequences were huge, answering the question using only his pen and paper turned out to be too time-consuming. Can you help him automate his research?
|
The first line contains two integers \(d\) and \(m\) (\(2 \leq d \leq 20\), \(2 \leq m \leq 60\)) β the length of the sequence \(\mathrm{gen}\) and an integer used to perform the modular operations. The second line contains \(d\) integers \(\mathrm{gen}_i\) (\(0 \leq \mathrm{gen}_i < m\)). It's guaranteed that the first element of the sequence \(\mathrm{gen}\) is equal to zero.The third line contains one integer \(n\) (\(1 \leq n \leq 30000\)) β the length of the sequence \(B\). The fourth line contains \(n\) integers \(B_i\) (\(0 \leq B_i < m\)). The fifth line contains two integers \(l\) and \(r\) (\(1 \leq l \leq r \leq 10^{18}\), \(r-l+1 \geq n\)).
|
Print a single integer β the answer to the problem.
|
Thorse-Radewoosh sequence in the first example is the standard Thue-Morse sequence, so the sequence \(A\) is as follows: \(11010011001011010010\). Here are the places where the sequence \(B\) majorizes \(A\):
|
Input: 2 2 0 1 4 0 1 1 0 2 21 | Output: 6
|
Master
| 4 | 2,327 | 660 | 51 | 10 |
305 |
E
|
305E
|
E. Playing with String
| 2,300 |
games
|
Two people play the following string game. Initially the players have got some string s. The players move in turns, the player who cannot make a move loses. Before the game began, the string is written on a piece of paper, one letter per cell. An example of the initial situation at s = ""abacaba"" A player's move is the sequence of actions: The player chooses one of the available pieces of paper with some string written on it. Let's denote it is t. Note that initially, only one piece of paper is available. The player chooses in the string t = t1t2... t|t| character in position i (1 β€ i β€ |t|) such that for some positive integer l (0 < i - l; i + l β€ |t|) the following equations hold: ti - 1 = ti + 1, ti - 2 = ti + 2, ..., ti - l = ti + l. Player cuts the cell with the chosen character. As a result of the operation, he gets three new pieces of paper, the first one will contain string t1t2... ti - 1, the second one will contain a string consisting of a single character ti, the third one contains string ti + 1ti + 2... t|t|. An example of making action (i = 4) with string s = Β«abacabaΒ» Your task is to determine the winner provided that both players play optimally well. If the first player wins, find the position of character that is optimal to cut in his first move. If there are multiple positions, print the minimal possible one.
|
The first line contains string s (1 β€ |s| β€ 5000). It is guaranteed that string s only contains lowercase English letters.
|
If the second player wins, print in the single line ""Second"" (without the quotes). Otherwise, print in the first line ""First"" (without the quotes), and in the second line print the minimal possible winning move β integer i (1 β€ i β€ |s|).
|
In the first sample the first player has multiple winning moves. But the minimum one is to cut the character in position 2. In the second sample the first player has no available moves.
|
Input: abacaba | Output: First2
|
Expert
| 1 | 1,348 | 122 | 241 | 3 |
1,386 |
A
|
1386A
|
A. Colors
| 2,700 |
*special; binary search; constructive algorithms; interactive
|
Linda likes to change her hair color from time to time, and would be pleased if her boyfriend Archie would notice the difference between the previous and the new color. Archie always comments on Linda's hair color if and only if he notices a difference β so Linda always knows whether Archie has spotted the difference or not.There is a new hair dye series in the market where all available colors are numbered by integers from \(1\) to \(N\) such that a smaller difference of the numerical values also means less visual difference.Linda assumes that for these series there should be some critical color difference \(C\) (\(1 \le C \le N\)) for which Archie will notice color difference between the current color \(\mathrm{color}_{\mathrm{new}}\) and the previous color \(\mathrm{color}_{\mathrm{prev}}\) if \(\left|\mathrm{color}_{\mathrm{new}} - \mathrm{color}_{\mathrm{prev}}\right| \ge C\) and will not if \(\left|\mathrm{color}_{\mathrm{new}} - \mathrm{color}_{\mathrm{prev}}\right| < C\).Now she has bought \(N\) sets of hair dye from the new series β one for each of the colors from \(1\) to \(N\), and is ready to set up an experiment. Linda will change her hair color on a regular basis and will observe Archie's reaction β whether he will notice the color change or not. Since for the proper dye each set should be used completely, each hair color can be obtained no more than once.Before the experiment, Linda was using a dye from a different series which is not compatible with the new one, so for the clearness of the experiment Archie's reaction to the first used color is meaningless.Her aim is to find the precise value of \(C\) in a limited number of dyes. Write a program which finds the value of \(C\) by experimenting with the given \(N\) colors and observing Archie's reactions to color changes.
|
Comments to the example input line by line: \(N = 7\). Answer to the first query is meaningless (can also be \(0\)). \(C \leq 5\). \(3 < C \leq 5\). It would be wise to check difference \(4\). However, this can not be done in the next query since \(4 + 4 = 8\) and \(4 - 4 = 0\) both are outside the allowed interval \(1 \le P \le 7\). \(3 < C \leq 5\). \(3 < C \leq 4\). Therefore, \(C = 4\).
|
Input: 1 7 1 1 0 0 1 | Output: ? 2 ? 7 ? 4 ? 1 ? 5 = 4
|
Master
| 4 | 1,816 | 0 | 0 | 13 |
||
1,137 |
C
|
1137C
|
C. Museums Tour
| 2,500 |
dp; graphs; implementation
|
In the country \(N\), there are \(n\) cities connected by \(m\) one-way roads. Although this country seems unremarkable, there are two interesting facts about it. At first, a week lasts \(d\) days here. At second, there is exactly one museum in each city of the country \(N\).Travel agency ""Open museums"" is developing a new program for tourists interested in museums. Agency's employees know which days each of the museums is open. The tour should start in the capital β the city number \(1\), and the first day of the tour must be on the first day of a week. Each day a tourist will be in some city, watching the exposition in its museum (in case museum is open today), and by the end of the day, the tour either ends or the tourist goes into another city connected by a road with the current one. The road system of \(N\) is designed in such a way that traveling by a road always takes one night and also all the roads are one-way. It's allowed to visit a city multiple times during the trip.You should develop such route for the trip that the number of distinct museums, possible to visit during it, is maximum.
|
The first line contains three integers \(n\), \(m\) and \(d\) (\(1 \leq n \leq 100\,000\), \(0 \leq m \leq 100\,000\), \(1 \leq d \leq 50\)), the number of cities, the number of roads and the number of days in a week.Each of next \(m\) lines contains two integers \(u_i\) and \(v_i\) (\(1 \le u_i, v_i \le n\), \(u_i \ne v_i\)), denoting a one-way road from the city \(u_i\) to the city \(v_i\).The next \(n\) lines contain the museums' schedule. The schedule of the museum located in the \(i\)-th city is described in the \(i\)-th of these lines. Each line consists of exactly \(d\) characters ""0"" or ""1"", the \(j\)-th character of the string equals to ""1"" if the museum is open at the \(j\)-th day of a week, and ""0"", otherwise.It's guaranteed that for each pair of cities \((u, v)\) there exists no more than one road leading from \(u\) to \(v\).
|
Print a single integer β the maximum number of distinct museums, that it's possible to visit, starting a trip in the first city on the first day of the week.
|
Explanation of the first example The maximum number of distinct museums to visit is \(3\). It's possible to visit \(3\) museums, for example, in the way described below. Day 1. Now it's the 1st day of a week, and the tourist is in the city \(1\). The museum there is closed. At night the tourist goes to the city number \(2\). Day 2. Now it's the 2nd day of a week, and the tourist is in the city \(2\). The museum there is open, and the tourist visits it. At night the tourist goes to the city number \(4\). Day 3. Now it's the 3rd day of a week, and the tourist is in the city \(4\). The museum there is open, and the tourist visits it. At night the tourist goes to the city number \(1\). Day 4. Now it's the 1st day of a week, and the tourist is in the city \(1\). The museum there is closed. At night the tourist goes to the city number \(2\). Day 5. Now it's the 2nd of a week number \(2\), and the tourist is in the city \(2\). The museum there is open, but the tourist has already visited it. At night the tourist goes to the city number \(3\). Day 6. Now it's the 3rd day of a week, and the tourist is in the city \(3\). The museum there is open, and the tourist visits it. After this, the tour is over. Explanation of the second example The maximum number of distinct museums to visit is \(2\). It's possible to visit \(2\) museums, for example, in the way described below. Day 1. Now it's the 1st day of a week, and the tourist is in the city \(1\). The museum there is open, and the tourist visits it. At night the tourist goes to the city number \(2\). Day 2. Now it's the 2nd day of a week, and the tourist is in the city \(2\). The museum there is closed. At night the tourist goes to the city number \(3\). Day 3. Now it's the 3rd day of a week, and the tourist is in the city \(3\). The museum there is open, and the tourist visits it. After this, the tour is over.
|
Input: 4 5 3 3 1 1 2 2 4 4 1 2 3 011 110 111 001 | Output: 3
|
Expert
| 3 | 1,117 | 857 | 157 | 11 |
2,053 |
D
|
2053D
|
D. Refined Product Optimality
| 1,700 |
binary search; data structures; greedy; math; schedules; sortings
|
As a tester, when my solution has a different output from the example during testing, I suspect the author first.β Chris, a commentAlthough Iris occasionally sets a problem where the solution is possibly wrong, she still insists on creating problems with her imagination; after all, everyone has always been on the road with their stubbornness... And like ever before, Iris has set a problem to which she gave a wrong solution, but Chris is always supposed to save it! You are going to play the role of Chris now: Chris is given two arrays \(a\) and \(b\), both consisting of \(n\) integers. Iris is interested in the largest possible value of \(P = \prod\limits_{i=1}^n \min(a_i, b_i)\) after an arbitrary rearrangement of \(b\). Note that she only wants to know the maximum value of \(P\), and no actual rearrangement is performed on \(b\). There will be \(q\) modifications. Each modification can be denoted by two integers \(o\) and \(x\) (\(o\) is either \(1\) or \(2\), \(1 \leq x \leq n\)). If \(o = 1\), then Iris will increase \(a_x\) by \(1\); otherwise, she will increase \(b_x\) by \(1\). Iris asks Chris the maximum value of \(P\) for \(q + 1\) times: once before any modification, then after every modification. Since \(P\) might be huge, Chris only needs to calculate it modulo \(998\,244\,353\). Chris soon worked out this problem, but he was so tired that he fell asleep. Besides saying thanks to Chris, now it is your turn to write a program to calculate the answers for given input data.Note: since the input and output are large, you may need to optimize them for this problem.For example, in C++, it is enough to use the following lines at the start of the main() function:int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr);}
|
Each test contains multiple test cases. The first line of input contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) β the number of test cases. The description of test cases follows.The first line of each test case contains two integers \(n\) and \(q\) (\(1 \leq n \leq 2\cdot 10^5\), \(1 \leq q \leq 2\cdot 10^5\)) β the length of the array and the number of operations.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 5\cdot 10^8\)) β the array \(a\).The third line of each test case contains \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(1 \leq b_i \leq 5\cdot 10^8\)) β the array \(b\).Then \(q\) lines follow, each line contains two integers \(o\) and \(x\) (\(o \in \{1, 2\}\), \(1 \leq x \leq n\)), representing an operation.It's guaranteed that the sum of \(n\) and the sum of \(q\) over all test cases does not exceed \(4\cdot 10^5\), respectively.
|
For each test case, output \(q + 1\) integers in a line, representing the answers that Chris will calculate, modulo \(998\,244\,353\).
|
In the first test case: Before the modifications, Chris can rearrange \(b\) to \([1, 2, 3]\) so that \(P = \prod\limits_{i=1}^n \min(a_i, b_i) = 1 \cdot 1 \cdot 2 = 2\). We can prove that this is the maximum possible value. For example, if Chris rearranges \(b = [2, 3, 1]\), \(P\) will be equal \(1 \cdot 1 \cdot 1 = 1 < 2\), which is not optimal. After the first modification, Chris can rearrange \(b\) to \([1, 2, 3]\) so that \(P = 1 \cdot 1 \cdot 3 = 3\), which is maximized. After the second modification, Chris can rearrange \(b\) to \([2, 2, 3]\) so that \(P = 1 \cdot 1 \cdot 3 = 3\), which is maximized. After the third modification, Chris can rearrange \(b\) to \([2, 2, 3]\) so that \(P = 6\), which is maximized. After the fourth modification, Chris can rearrange \(b\) to \([2, 2, 4]\) so that \(P = 6\), which is maximized.
|
Input: 43 41 1 23 2 11 32 31 12 16 81 4 2 7 3 57 6 5 6 3 32 51 61 51 51 52 32 31 613 87 7 6 6 5 5 5 2 2 3 4 5 11 4 1 9 6 6 9 1 5 1 3 8 42 22 112 42 41 71 12 121 55 310000000 20000000 30000000 40000000 5000000010000000 20000000 30000000 40000000 500000001 12 22 1 | Output: 2 3 3 6 6 840 840 1008 1344 1680 2016 2016 2016 2352 2116800 2646000 3528000 3528000 3528000 4233600 4838400 4838400 4838400 205272023 205272023 205272023 264129429
|
Medium
| 6 | 1,788 | 914 | 134 | 20 |
513 |
F1
|
513F1
|
F1. Scaygerboss
| 2,700 |
flows
|
Cthulhu decided to catch Scaygerboss. Scaygerboss found it out and is trying to hide in a pack of his scaygers. Each scayger except Scaygerboss is either a male or a female. Scaygerboss's gender is ""other"".Scaygers are scattered on a two-dimensional map divided into cells. A scayger looks nerdy and loveable if it is staying in the same cell with exactly one scayger of a gender that is different from its own gender. Cthulhu will not be able to catch Scaygerboss if all the scaygers on the map look nerdy and loveable.The scaygers can move around at different speeds. For each scayger, we are given the time it takes this scayger to move from a cell to an adjacent cell. Cells are adjacent if they share a common side. At any point of time, each cell that does not contain an obstacle can be occupied by an arbitrary number of scaygers. Scaygers cannot move to cells with obstacles.Calculate minimal time in order to make all scaygers look nerdy and loveable if they move optimally toward this goal.
|
The first line contains 4 integers: n, m, males, females (0 β€ males, females β€ nΒ·m). n and m are dimensions of the map; males and females are numbers of male scaygers and female scaygers.Next n lines describe the map. Each of these lines contains m characters. Character '.' stands for a free cell; character '#' stands for a cell with an obstacle.The next line contains 3 integers r, c, and t (1 β€ r β€ n, 1 β€ c β€ m, 1 β€ t β€ 109): the current coordinates of Scaygerboss and the time it takes Scaygerboss to move to an adjacent cell. The next males lines contain coordinates and times of male scaygers in the same format as for Scaygerboss. The next females lines contain coordinates and times of female scaygers in the same format as for Scaygerboss. (The coordinates and times adhere to the same limits as for Scaygerboss.) All scaygers reside in cells without obstacles.The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem F1 (14 points), the constraints 1 β€ n, m β€ 11 will hold. In subproblem F2 (6 points), the constraints 1 β€ n, m β€ 22 will hold.
|
Output the minimum possible time it takes to make all scaygers look nerdy and loveable or -1 if it is impossible.
|
Consider the first sample test. The scaygers are hiding on a 4 by 4 map. Scaygerboss initially resides in the cell (2, 1) and can move between cells in 1 unit of time. There are also 2 male and 3 female scaygers on the map. One of the females initially is in the cell (1, 1), and all the other scaygers are in the cell (2, 1). All the scaygers move between cells in 2 units of time. If Scaygerboss and the female scayger from the cell (1, 1) move to the cell (1, 2), and a male and a female scayger from those residing in the cell (2, 1) move to the cell (1, 1), then all the scaygers will look nerdy and lovable in 2 units of time.
|
Input: 4 4 2 3.....###########2 1 12 1 22 1 22 1 22 1 21 1 2 | Output: 2
|
Master
| 1 | 1,003 | 1,224 | 113 | 5 |
1,688 |
A
|
1688A
|
A. Cirno's Perfect Bitmasks Classroom
| 800 |
bitmasks; brute force
|
Even if it's a really easy question, she won't be able to answer itβ Perfect Memento in Strict SenseCirno's perfect bitmasks classroom has just started!Cirno gave her students a positive integer \(x\). As an assignment, her students need to find the minimum positive integer \(y\), which satisfies the following two conditions:$$$\(x\ \texttt{and}\ y > 0\)\( \)\(x\ \texttt{xor}\ y > 0\)\(Where \)\texttt{and}\( is the bitwise AND operation, and \)\texttt{xor}$$$ is the bitwise XOR operation.Among the students was Mystia, who was truly baffled by all these new operators. Please help her!
|
The first line of input contains a single integer \(t\) (\(1 \leq t \leq 10^3\)) β the number of input test cases.For each test case, the only line of input contains one integer \(x\) (\(1 \leq x \leq 2^{30}\)).
|
For each test case, print a single integer β the minimum number of \(y\).
|
Test case 1: \(1\; \texttt{and}\; 3=1>0\), \(1\; \texttt{xor}\; 3=2>0\).Test case 2: \(2\; \texttt{and}\; 3=2>0\), \(2\; \texttt{xor}\; 3=1>0\).
|
Input: 71259161145141000000 | Output: 3 3 1 1 17 2 64
|
Beginner
| 2 | 590 | 211 | 73 | 16 |
1,034 |
D
|
1034D
|
D. Intervals of Intervals
| 3,500 |
binary search; data structures; two pointers
|
Little D is a friend of Little C who loves intervals very much instead of number ""\(3\)"".Now he has \(n\) intervals on the number axis, the \(i\)-th of which is \([a_i,b_i]\).Only the \(n\) intervals can not satisfy him. He defines the value of an interval of intervals \([l,r]\) (\(1 \leq l \leq r \leq n\), \(l\) and \(r\) are both integers) as the total length of the union of intervals from the \(l\)-th to the \(r\)-th.He wants to select exactly \(k\) different intervals of intervals such that the sum of their values is maximal. Please help him calculate the maximal sum.
|
First line contains two integers \(n\) and \(k\) (\(1 \leq n \leq 3 \cdot 10^5\), \(1 \leq k \leq \min\{\frac{n(n+1)}{2},10^9\}\)) β the number of intervals Little D has and the number of intervals of intervals he will select.Each of the next \(n\) lines contains two integers \(a_i\) and \(b_i\), the \(i\)-th line of the \(n\) lines describing the \(i\)-th interval (\(1 \leq a_i < b_i \leq 10^9\)).
|
Print one integer β the maximal sum of values Little D can get.
|
For the first example, Little D will select \([1,2]\), the union of the first interval and the second interval is \([1,4]\), whose length is \(3\).For the second example, Little D will select \([1,2]\), \([2,3]\) and \([1,3]\), the answer is \(5+6+4=15\).
|
Input: 2 11 32 4 | Output: 3
|
Master
| 3 | 580 | 401 | 63 | 10 |
1,858 |
E2
|
1858E2
|
E2. Rollbacks (Hard Version)
| 2,600 |
data structures; interactive; trees
|
This is a hard version of this problem. The only difference between the versions is that you have to solve the hard version in online mode. You can make hacks only if both versions of the problem are solved.You have an array \(a\), which is initially empty. You need to process queries of the following types: + \(x\) β add the integer \(x\) to the end of the array \(a\). - \(k\) β remove the last \(k\) numbers from the array \(a\). ! β roll back the last active change (i.e., make the array \(a\) the way it was before the change). In this problem, only queries of the first two types (+ and -) are considered as changes. ? β find the number of distinct numbers in the array \(a\).
|
The first line contains an integer \(q\) (\(1 \leq q \leq 10^6\)) β the number of queries.The next \(q\) lines contain the queries as described above.It is guaranteed that in the queries of the first type, \(1 \le x \le 10^6\); in the queries of the second type, \(k \ge 1\) and \(k\) does not exceed the current length of the array \(a\); at the moment of the queries of the third type, there is at least one query of the first or of the second type that can be rolled back. It is also guaranteed that the number of queries of the fourth type (?) does not exceed \(10^5\).Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query, so don't forget to flush output after printing answers. You can use functions like fflush(stdout) in C++ and BufferedWriter.flush in Java or similar after each writing in your program.
|
For each query of the fourth type output one integer β the number of distinct elements in array \(a\) at the moment of query.
|
In the first example array \(a\) changes as follows: After the first query, \(a=[1]\). After the second query, \(a=[1,2]\). After the third query, \(a=[1,2,2]\). At the moment of the fourth query, there are \(2\) distinct intergers in the array \(a\): \(1\) and \(2\). After the fifth query, \(a=[1,2]\) (rolled back the change + 2). After the sixth query, \(a=[1,2,3]\). After the seventh query, \(a=[1]\). At the moment of the eigth query, there is only one \(1\) in the array \(a\). After the ninth query, \(a=[1,1]\). At the moment of the tenth query, there are only two \(1\) in the array \(a\). In the second example array \(a\) changes as follows: After the first query, \(a=[1]\). After the second query, \(a=[1, 1\,000\,000]\). At the moment of the third query, there are \(2\) distinct intergers in the array \(a\): \(1\) and \(1\,000\,000\). After the fourth query, \(a=[1]\) (rolled back the change + 1000000). After the fifth query, \(a=[]\) (rolled back the change + 1). At the moment of the sixth query, there are no integers in the array \(a\), so the answer to this query is \(0\).
|
Input: 10 + 1 + 2 + 2 ? ! + 3 - 2 ? + 1 ? | Output: 2 1 1
|
Expert
| 3 | 684 | 940 | 125 | 18 |
2,055 |
A
|
2055A
|
A. Two Frogs
| 800 |
constructive algorithms; games; greedy; math
|
Roaming through the alligator-infested Everglades, Florida Man encounters a most peculiar showdown.There are \(n\) lilypads arranged in a row, numbered from \(1\) to \(n\) from left to right. Alice and Bob are frogs initially positioned on distinct lilypads, \(a\) and \(b\), respectively. They take turns jumping, starting with Alice. During a frog's turn, it can jump either one space to the left or one space to the right, as long as the destination lilypad exists. For example, on Alice's first turn, she can jump to either lilypad \(a-1\) or \(a+1\), provided these lilypads are within bounds. It is important to note that each frog must jump during its turn and cannot remain on the same lilypad.However, there are some restrictions: The two frogs cannot occupy the same lilypad. This means that Alice cannot jump to a lilypad that Bob is currently occupying, and vice versa. If a frog cannot make a valid jump on its turn, it loses the game. As a result, the other frog wins. Determine whether Alice can guarantee a win, assuming that both players play optimally. It can be proven that the game will end after a finite number of moves if both players play optimally.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 500\)). The description of the test cases follows. The first and only line of each test case contains three integers \(n\), \(a\), and \(b\) (\(2 \leq n \leq 100\), \(1 \leq a, b \leq n\), \(a\neq b\)) β the number of lilypads, and the starting positions of Alice and Bob, respectively.Note that there are no constraints on the sum of \(n\) over all test cases.
|
For each test case, print a single line containing either ""YES"" or ""NO"", representing whether or not Alice has a winning strategy. You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
|
In the first test case, Alice has no legal moves. Therefore, Alice loses on the first turn.In the second test case, Alice can only move to lilypad \(2\). Then, Bob has no legal moves. Therefore, Alice has a winning strategy in this case.In the third test case, Alice can only move to lilypad \(1\). Then, Bob can move to lilypad \(2\). Alice is no longer able to move and loses, giving Bob the win. It can be shown that Bob can always win regardless of Alice's moves; hence, Alice does not have a winning strategy.
|
Input: 52 1 23 3 14 2 35 2 47 6 2 | Output: NO YES NO YES YES
|
Beginner
| 4 | 1,173 | 471 | 296 | 20 |
1,284 |
F
|
1284F
|
F. New Year and Social Network
| 3,200 |
data structures; graph matchings; graphs; math; trees
|
Donghyun's new social network service (SNS) contains \(n\) users numbered \(1, 2, \ldots, n\). Internally, their network is a tree graph, so there are \(n-1\) direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as \(T_1\).To prevent a possible server breakdown, Donghyun created a backup network \(T_2\), which also connects the same \(n\) users via a tree graph. If a system breaks down, exactly one edge \(e \in T_1\) becomes unusable. In this case, Donghyun will protect the edge \(e\) by picking another edge \(f \in T_2\), and add it to the existing network. This new edge should make the network be connected again. Donghyun wants to assign a replacement edge \(f \in T_2\) for as many edges \(e \in T_1\) as possible. However, since the backup network \(T_2\) is fragile, \(f \in T_2\) can be assigned as the replacement edge for at most one edge in \(T_1\). With this restriction, Donghyun wants to protect as many edges in \(T_1\) as possible.Formally, let \(E(T)\) be an edge set of the tree \(T\). We consider a bipartite graph with two parts \(E(T_1)\) and \(E(T_2)\). For \(e \in E(T_1), f \in E(T_2)\), there is an edge connecting \(\{e, f\}\) if and only if graph \(T_1 - \{e\} + \{f\}\) is a tree. You should find a maximum matching in this bipartite graph.
|
The first line contains an integer \(n\) (\(2 \le n \le 250\,000\)), the number of users. In the next \(n-1\) lines, two integers \(a_i\), \(b_i\) (\(1 \le a_i, b_i \le n\)) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in \(T_1\).In the next \(n-1\) lines, two integers \(c_i\), \(d_i\) (\(1 \le c_i, d_i \le n\)) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in \(T_2\). It is guaranteed that both edge sets form a tree of size \(n\).
|
In the first line, print the number \(m\) (\(0 \leq m < n\)), the maximum number of edges that can be protected.In the next \(m\) lines, print four integers \(a_i, b_i, c_i, d_i\). Those four numbers denote that the edge \((a_i, b_i)\) in \(T_1\) is will be replaced with an edge \((c_i, d_i)\) in \(T_2\).All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge \((a_i, b_i)\) from \(T_1\) and adds edge \((c_i, d_i)\) from \(T_2\), the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.If there are several solutions, you can print any.
|
Input: 4 1 2 2 3 4 3 1 3 2 4 1 4 | Output: 3 3 2 4 2 2 1 1 3 4 3 1 4
|
Master
| 5 | 1,392 | 544 | 702 | 12 |
|
1,634 |
A
|
1634A
|
A. Reverse and Concatenate
| 800 |
greedy; strings
|
Real stupidity beats artificial intelligence every time.β Terry Pratchett, Hogfather, DiscworldYou are given a string \(s\) of length \(n\) and a number \(k\). Let's denote by \(rev(s)\) the reversed string \(s\) (i.e. \(rev(s) = s_n s_{n-1} ... s_1\)). You can apply one of the two kinds of operations to the string: replace the string \(s\) with \(s + rev(s)\) replace the string \(s\) with \(rev(s) + s\)How many different strings can you get as a result of performing exactly \(k\) operations (possibly of different kinds) on the original string \(s\)?In this statement we denoted the concatenation of strings \(s\) and \(t\) as \(s + t\). In other words, \(s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m\), where \(n\) and \(m\) are the lengths of strings \(s\) and \(t\) respectively.
|
The first line contains one integer \(t\) (\(1 \le t \le 100\)) β number of test cases. Next \(2 \cdot t\) lines contain \(t\) test cases:The first line of a test case contains two integers \(n\) and \(k\) (\(1 \le n \le 100\), \(0 \le k \le 1000\)) β the length of the string and the number of operations respectively.The second string of a test case contains one string \(s\) of length \(n\) consisting of lowercase Latin letters.
|
For each test case, print the answer (that is, the number of different strings that you can get after exactly \(k\) operations) on a separate line.It can be shown that the answer does not exceed \(10^9\) under the given constraints.
|
In the first test case of the example:After the first operation the string \(s\) can become either aabbaa or baaaab. After the second operation there are 2 possibilities for \(s\): aabbaaaabbaa and baaaabbaaaab.
|
Input: 43 2aab3 3aab7 1abacaba2 0ab | Output: 2 2 1 1
|
Beginner
| 2 | 783 | 432 | 232 | 16 |
1,874 |
E
|
1874E
|
E. Jellyfish and Hack
| 3,000 |
dp; math
|
It is well known that quick sort works by randomly selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. But Jellyfish thinks that choosing a random element is just a waste of time, so she always chooses the first element to be the pivot. The time her code needs to run can be calculated by the following pseudocode:function fun(A) if A.length > 0 let L[1 ... L.length] and R[1 ... R.length] be new arrays L.length = R.length = 0 for i = 2 to A.length if A[i] < A[1] L.length = L.length + 1 L[L.length] = A[i] else R.length = R.length + 1 R[R.length] = A[i] return A.length + fun(L) + fun(R) else return 0Now you want to show her that her code is slow. When the function \(\mathrm{fun(A)}\) is greater than or equal to \(lim\), her code will get \(\text{Time Limit Exceeded}\). You want to know how many distinct permutations \(P\) of \([1, 2, \dots, n]\) satisfies \(\mathrm{fun(P)} \geq lim\). Because the answer may be large, you will only need to find the answer modulo \(10^9+7\).
|
The only line of the input contains two integers \(n\) and \(lim\) (\(1 \leq n \leq 200\), \(1 \leq lim \leq 10^9\)).
|
Output the number of different permutations that satisfy the condition modulo \(10^9+7\).
|
In the first example, \(P = [1, 4, 2, 3]\) satisfies the condition, because: \(\mathrm{fun([1, 4, 2, 3]) = 4 + fun([4, 2, 3]) = 7 + fun([2, 3]) = 9 + fun([3]) = 10}\)Do remember to output the answer modulo \(10^9+7\).
|
Input: 4 10 | Output: 8
|
Master
| 2 | 1,098 | 117 | 89 | 18 |
314 |
B
|
314B
|
B. Sereja and Periods
| 2,000 |
binary search; dfs and similar; strings
|
Let's introduce the designation , where x is a string, n is a positive integer and operation "" + "" is the string concatenation operation. For example, [abc, 2] = abcabc.We'll say that string s can be obtained from string t, if we can remove some characters from string t and obtain string s. For example, strings ab and aΡba can be obtained from string xacbac, and strings bx and aaa cannot be obtained from it.Sereja has two strings, w = [a, b] and q = [c, d]. He wants to find such maximum integer p (p > 0), that [q, p] can be obtained from string w.
|
The first line contains two integers b, d (1 β€ b, d β€ 107). The second line contains string a. The third line contains string c. The given strings are not empty and consist of lowercase English letters. Their lengths do not exceed 100.
|
In a single line print an integer β the largest number p. If the required value of p doesn't exist, print 0.
|
Input: 10 3ababbab | Output: 3
|
Hard
| 3 | 555 | 235 | 108 | 3 |
|
1,621 |
A
|
1621A
|
A. Stable Arrangement of Rooks
| 800 |
constructive algorithms
|
You have an \(n \times n\) chessboard and \(k\) rooks. Rows of this chessboard are numbered by integers from \(1\) to \(n\) from top to bottom and columns of this chessboard are numbered by integers from \(1\) to \(n\) from left to right. The cell \((x, y)\) is the cell on the intersection of row \(x\) and collumn \(y\) for \(1 \leq x \leq n\) and \(1 \leq y \leq n\).The arrangement of rooks on this board is called good, if no rook is beaten by another rook.A rook beats all the rooks that shares the same row or collumn with it.The good arrangement of rooks on this board is called not stable, if it is possible to move one rook to the adjacent cell so arrangement becomes not good. Otherwise, the good arrangement is stable. Here, adjacent cells are the cells that share a side. Such arrangement of \(3\) rooks on the \(4 \times 4\) chessboard is good, but it is not stable: the rook from \((1, 1)\) can be moved to the adjacent cell \((2, 1)\) and rooks on cells \((2, 1)\) and \((2, 4)\) will beat each other. Please, find any stable arrangement of \(k\) rooks on the \(n \times n\) chessboard or report that there is no such arrangement.
|
The first line contains a single integer \(t\) (\(1 \leq t \leq 100\)) β the number of test cases.The first line of each test case contains two integers \(n\), \(k\) (\(1 \leq k \leq n \leq 40\)) β the size of the chessboard and the number of rooks.
|
If there is a stable arrangement of \(k\) rooks on the \(n \times n\) chessboard, output \(n\) lines of symbols . and R. The \(j\)-th symbol of the \(i\)-th line should be equals R if and only if there is a rook on the cell \((i, j)\) in your arrangement.If there are multiple solutions, you may output any of them.If there is no stable arrangement, output \(-1\).
|
In the first test case, you should find stable arrangement of \(2\) rooks on the \(3 \times 3\) chessboard. Placing them in cells \((3, 1)\) and \((1, 3)\) gives stable arrangement.In the second test case it can be shown that it is impossbile to place \(3\) rooks on the \(3 \times 3\) chessboard to get stable arrangement.
|
Input: 53 23 31 15 240 33 | Output: ..R ... R.. -1 R ..... R.... ..... ....R ..... -1
|
Beginner
| 1 | 1,146 | 249 | 364 | 16 |
165 |
B
|
165B
|
B. Burning Midnight Oil
| 1,500 |
binary search; implementation
|
One day a highly important task was commissioned to Vasya β writing a program in a night. The program consists of n lines of code. Vasya is already exhausted, so he works like that: first he writes v lines of code, drinks a cup of tea, then he writes as much as lines, drinks another cup of tea, then he writes lines and so on: , , , ...The expression is regarded as the integral part from dividing number a by number b.The moment the current value equals 0, Vasya immediately falls asleep and he wakes up only in the morning, when the program should already be finished.Vasya is wondering, what minimum allowable value v can take to let him write not less than n lines of code before he falls asleep.
|
The input consists of two integers n and k, separated by spaces β the size of the program in lines and the productivity reduction coefficient, 1 β€ n β€ 109, 2 β€ k β€ 10.
|
Print the only integer β the minimum value of v that lets Vasya write the program in one night.
|
In the first sample the answer is v = 4. Vasya writes the code in the following portions: first 4 lines, then 2, then 1, and then Vasya falls asleep. Thus, he manages to write 4 + 2 + 1 = 7 lines in a night and complete the task.In the second sample the answer is v = 54. Vasya writes the code in the following portions: 54, 6. The total sum is 54 + 6 = 60, that's even more than n = 59.
|
Input: 7 2 | Output: 4
|
Medium
| 2 | 701 | 167 | 95 | 1 |
51 |
F
|
51F
|
F. Caterpillar
| 2,800 |
dfs and similar; dp; graphs; trees
|
An undirected graph is called a caterpillar if it is a connected graph without cycles and it has such a path p that any vertex is located at a distance of at most 1 from the path p. The caterpillar can contain loops (edges from a vertex to itself) but cannot contain multiple (parallel) edges.The picture contains an example of a caterpillar: You are given an undirected graph G. You are allowed to do a merging operations, each such operation merges two vertices into one vertex. For that two any vertices a and b (a β b) are chosen. These verteces are deleted together with their edges (which are incident to at least one of the vertices a or b) but a new vertex w is added together with edges (x, w) for each edge (a, w) and/or (b, w). If there was the edge (a, b) it transforms to the loop (w, w). The resulting graph (after the merging operation) may contain multiple (parallel) edges between pairs of vertices and loops. Let us note that this operation decreases the number of vertices of graph by 1 but leaves the number of edges in the graph unchanged.The merging operation can be informally described as a unity of two vertices of the graph into one with the natural transformation of the graph edges.You may apply this operation consecutively and make the given graph to be a caterpillar. Write a program that will print the minimal number of merging operations required to make the given graph a caterpillar.
|
The first line contains a pair of integers n, m (1 β€ n β€ 2000;0 β€ m β€ 105), where n represents the number of vertices in the graph and m is the number of edges in it. Then the following m lines contain edge descriptions, one edge description per line. Every line contains a pair of integers ai, bi (1 β€ ai, bi β€ n;ai β bi), ai, bi which represent the indices of the vertices connected by the edge. The vertices are numbered from 1 to n. In the given graph it will be no more than one edge between any pair of vertices. The given graph is not necessarily connected.
|
Print the minimal required number of operations.
|
Input: 4 41 22 33 44 2 | Output: 2
|
Master
| 4 | 1,419 | 564 | 48 | 0 |
|
1,830 |
F
|
1830F
|
F. The Third Grace
| 3,200 |
data structures; dp
|
You are given \(n\) intervals and \(m\) points on the number line. The \(i\)-th intervals covers coordinates \([l_i,r_i]\) and the \(i\)-th point is on coordinate \(i\) and has coefficient \(p_i\).Initially, all points are not activated. You should choose a subset of the \(m\) points to activate. For each of \(n\) interval, we define its cost as: \(0\), if there are no activated points in the interval; the coefficient of the activated point with the largest coordinate within it, otherwise. Your task is to maximize the sum of the costs of all intervals by choosing which points to activate.
|
Each test contains multiple test cases. The first line of input contains a single integer \(t\) (\(1 \le t \le 10^5\)) β the number of test cases. The description of test cases follows.The first line of each test case contains two integers \(n\) and \(m\) (\(1 \le n \le 10^6, 1 \le m \le 10^6\)) β the number of intervals and the number of points.The following \(n\) lines of each test case contains two integers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le m\)) β the endpoints of the \(i\)-th interval.The following line of each test case contains \(m\) integers \(p_1,p_2,\ldots,p_m\) (\(0 \le p_i \le 10^9\)) β the coefficients of the points.It is guaranteed that the sum of \(n\) does not exceed \(10^6\) and the sum of \(m\) does not exceed \(10^6\).
|
Output the maximum possible sum of costs of all intervals.
|
In the first sample, we can activate points \(1\) and \(8\). The sum of costs of all intervals will be \(78+30=108\).In the second sample, we will activate no points. The sum of costs of all intervals will be \(0\).
|
Input: 22 81 53 878 0 50 0 0 0 0 301 61 50 0 0 0 0 100 | Output: 108 0
|
Master
| 2 | 595 | 757 | 58 | 18 |
1,553 |
E
|
1553E
|
E. Permutation Shift
| 2,100 |
brute force; combinatorics; constructive algorithms; dfs and similar; dsu; graphs; math
|
An identity permutation of length \(n\) is an array \([1, 2, 3, \dots, n]\).We performed the following operations to an identity permutation of length \(n\): firstly, we cyclically shifted it to the right by \(k\) positions, where \(k\) is unknown to you (the only thing you know is that \(0 \le k \le n - 1\)). When an array is cyclically shifted to the right by \(k\) positions, the resulting array is formed by taking \(k\) last elements of the original array (without changing their relative order), and then appending \(n - k\) first elements to the right of them (without changing relative order of the first \(n - k\) elements as well). For example, if we cyclically shift the identity permutation of length \(6\) by \(2\) positions, we get the array \([5, 6, 1, 2, 3, 4]\); secondly, we performed the following operation at most \(m\) times: pick any two elements of the array and swap them. You are given the values of \(n\) and \(m\), and the resulting array. Your task is to find all possible values of \(k\) in the cyclic shift operation.
|
The first line contains one integer \(t\) (\(1 \le t \le 10^5\)) β the number of test cases.Each test case consists of two lines. The first line contains two integers \(n\) and \(m\) (\(3 \le n \le 3 \cdot 10^5\); \(0 \le m \le \frac{n}{3}\)).The second line contains \(n\) integers \(p_1, p_2, \dots, p_n\) (\(1 \le p_i \le n\), each integer from \(1\) to \(n\) appears in this sequence exactly once) β the resulting array.The sum of \(n\) over all test cases does not exceed \(3 \cdot 10^5\).
|
For each test case, print the answer in the following way: firstly, print one integer \(r\) (\(0 \le r \le n\)) β the number of possible values of \(k\) for the cyclic shift operation; secondly, print \(r\) integers \(k_1, k_2, \dots, k_r\) (\(0 \le k_i \le n - 1\)) β all possible values of \(k\) in increasing order.
|
Consider the example: in the first test case, the only possible value for the cyclic shift is \(3\). If we shift \([1, 2, 3, 4]\) by \(3\) positions, we get \([2, 3, 4, 1]\). Then we can swap the \(3\)-rd and the \(4\)-th elements to get the array \([2, 3, 1, 4]\); in the second test case, the only possible value for the cyclic shift is \(0\). If we shift \([1, 2, 3]\) by \(0\) positions, we get \([1, 2, 3]\). Then we don't change the array at all (we stated that we made at most \(1\) swap), so the resulting array stays \([1, 2, 3]\); in the third test case, all values from \(0\) to \(2\) are possible for the cyclic shift: if we shift \([1, 2, 3]\) by \(0\) positions, we get \([1, 2, 3]\). Then we can swap the \(1\)-st and the \(3\)-rd elements to get \([3, 2, 1]\); if we shift \([1, 2, 3]\) by \(1\) position, we get \([3, 1, 2]\). Then we can swap the \(2\)-nd and the \(3\)-rd elements to get \([3, 2, 1]\); if we shift \([1, 2, 3]\) by \(2\) positions, we get \([2, 3, 1]\). Then we can swap the \(1\)-st and the \(2\)-nd elements to get \([3, 2, 1]\); in the fourth test case, we stated that we didn't do any swaps after the cyclic shift, but no value of cyclic shift could produce the array \([1, 2, 3, 4, 6, 5]\).
|
Input: 4 4 1 2 3 1 4 3 1 1 2 3 3 1 3 2 1 6 0 1 2 3 4 6 5 | Output: 1 3 1 0 3 0 1 2 0
|
Hard
| 7 | 1,050 | 494 | 318 | 15 |
1,889 |
D
|
1889D
|
D. Game of Stacks
| 3,000 |
brute force; dfs and similar; graphs; implementation; trees
|
You have \(n\) stacks \(r_1,r_2,\ldots,r_n\). Each stack contains some positive integers ranging from \(1\) to \(n\).Define the following functions:function init(pos): stacks := an array that contains n stacks r[1], r[2], ..., r[n] return get(stacks, pos)function get(stacks, pos): if stacks[pos] is empty: return pos else: new_pos := the top element of stacks[pos] pop the top element of stacks[pos] return get(stacks, new_pos)You want to know the values returned by \(\texttt{init(1)}, \texttt{init(2)}, \ldots, \texttt{init(n)}\).Note that, during these calls, the stacks \(r_1,r_2,\ldots,r_n\) don't change, so the calls \(\texttt{init(1)}, \texttt{init(2)}, \ldots, \texttt{init(n)}\) are independent.
|
The first line of the input contains one integer \(n\) (\(1\le n\le 10^5\)) β the length of the array \(r\).Each of the following \(n\) lines contains several integers. The first integer \(k_i\) (\(0\le k_i\le 10^5\)) represents the number of elements in the \(i\)-th stack, and the following \(k_i\) positive integers \(c_{i,1},c_{i,2},\ldots,c_{i,k_i}\) (\(1\le c_{i,j}\le n\)) represent the elements in the \(i\)-th stack. \(c_{i,1}\) is the bottom element.In each test, \(\sum k_i\le 10^6\).
|
You need to output \(n\) values, the \(i\)-th of which is the value returned by \(\texttt{init(i)}\).
|
In the first example: When you call \(\texttt{init(1)}\), set \(\texttt{stacks := [[1,2,2],[3,1,2],[1,2,1]]}\), and then call \(\texttt{get(stacks, 1)}\). \(\texttt{stacks[1]}\) is not empty, set \(\texttt{new_pos := 2}\), and pop the top element of \(\texttt{stacks[1]}\), which makes \(\texttt{stacks}\) become \([[1,2],[3,1,2],[1,2,1]]\), and then call \(\texttt{get(stacks, 2)}\). \(\texttt{stacks[2]}\) is not empty, set \(\texttt{new_pos := 2}\), and pop the top element of \(\texttt{stacks[2]}\), which makes \(\texttt{stacks}\) become \([[1,2],[3,1],[1,2,1]]\), and then call \(\texttt{get(stacks, 2)}\). \(\texttt{stacks[2]}\) is not empty, set \(\texttt{new_pos := 1}\), and pop the top element of \(\texttt{stacks[2]}\), which makes \(\texttt{stacks}\) become \([[1,2],[3],[1,2,1]]\), and then call \(\texttt{get(stacks, 1)}\). \(\texttt{stacks[1]}\) is not empty, set \(\texttt{new_pos := 2}\), and pop the top element of \(\texttt{stacks[1]}\), which makes \(\texttt{stacks}\) become \([[1],[3],[1,2,1]]\), and then call \(\texttt{get(stacks, 2)}\). \(\texttt{stacks[2]}\) is not empty, set \(\texttt{new_pos := 3}\), and pop the top element of \(\texttt{stacks[2]}\), which makes \(\texttt{stacks}\) become \([[1],[],[1,2,1]]\), and then call \(\texttt{get(stacks, 3)}\). \(\texttt{stacks[3]}\) is not empty, set \(\texttt{new_pos := 1}\), and pop the top element of \(\texttt{stacks[3]}\), which makes \(\texttt{stacks}\) become \([[1],[],[1,2]]\), and then call \(\texttt{get(stacks, 1)}\). \(\texttt{stacks[1]}\) is not empty, set \(\texttt{new_pos := 1}\), and pop the top element of \(\texttt{stacks[1]}\), which makes \(\texttt{stacks}\) become \([[],[],[1,2]]\), and then call \(\texttt{get(stacks, 1)}\). \(\texttt{stacks[1]}\) is empty, return \(1\). When you call \(\texttt{init(2)}\), set \(\texttt{stacks := [[1,2,2],[3,1,2],[1,2,1]]}\), and then call \(\texttt{get(stacks, 2)}\). \(\texttt{stacks[2]}\) is not empty, set \(\texttt{new_pos := 2}\), and pop the top element of \(\texttt{stacks[2]}\), which makes \(\texttt{stacks}\) become \([[1,2,2],[3,1],[1,2,1]]\), and then call \(\texttt{get(stacks, 2)}\). \(\texttt{stacks[2]}\) is not empty, set \(\texttt{new_pos := 1}\), and pop the top element of \(\texttt{stacks[2]}\), which makes \(\texttt{stacks}\) become \([[1,2,2],[3],[1,2,1]]\), and then call \(\texttt{get(stacks, 1)}\). \(\texttt{stacks[1]}\) is not empty, set \(\texttt{new_pos := 2}\), and pop the top element of \(\texttt{stacks[1]}\), which makes \(\texttt{stacks}\) become \([[1,2],[3],[1,2,1]]\), and then call \(\texttt{get(stacks, 2)}\). \(\texttt{stacks[2]}\) is not empty, set \(\texttt{new_pos := 3}\), and pop the top element of \(\texttt{stacks[2]}\), which makes \(\texttt{stacks}\) become \([[1,2],[],[1,2,1]]\), and then call \(\texttt{get(stacks, 3)}\). \(\texttt{stacks[3]}\) is not empty, set \(\texttt{new_pos := 1}\), and pop the top element of \(\texttt{stacks[3]}\), which makes \(\texttt{stacks}\) become \([[1,2],[],[1,2]]\), and then call \(\texttt{get(stacks, 1)}\). \(\texttt{stacks[1]}\) is not empty, set \(\texttt{new_pos := 2}\), and pop the top element of \(\texttt{stacks[1]}\), which makes \(\texttt{stacks}\) become \([[1],[],[1,2]]\), and then call \(\texttt{get(stacks, 2)}\). \(\texttt{stacks[2]}\) is empty, return \(2\). When you call \(\texttt{init(3)}\), set \(\texttt{stacks := [[1,2,2],[3,1,2],[1,2,1]]}\), and then call \(\texttt{get(stacks, 3)}\). \(\texttt{stacks[3]}\) is not empty, set \(\texttt{new_pos := 1}\), and pop the top element of \(\texttt{stacks[3]}\), which makes \(\texttt{stacks}\) become \([[1,2,2],[3,1,2],[1,2]]\), and then call \(\texttt{get(stacks, 1)}\). \(\texttt{stacks[1]}\) is not empty, set \(\texttt{new_pos := 2}\), and pop the top element of \(\texttt{stacks[1]}\), which makes \(\texttt{stacks}\) become \([[1,2],[3,1,2],[1,2]]\), and then call \(\texttt{get(stacks, 2)}\). \(\texttt{stacks[2]}\) is not empty, set \(\texttt{new_pos := 2}\), and pop the top element of \(\texttt{stacks[2]}\), which makes \(\texttt{stacks}\) become \([[1,2],[3,1],[1,2]]\), and then call \(\texttt{get(stacks, 2)}\). \(\texttt{stacks[2]}\) is not empty, set \(\texttt{new_pos := 1}\), and pop the top element of \(\texttt{stacks[2]}\), which makes \(\texttt{stacks}\) become \([[1,2],[3],[1,2]]\), and then call \(\texttt{get(stacks, 1)}\). \(\texttt{stacks[1]}\) is not empty, set \(\texttt{new_pos := 2}\), and pop the top element of \(\texttt{stacks[1]}\), which makes \(\texttt{stacks}\) become \([[1],[3],[1,2]]\), and then call \(\texttt{get(stacks, 2)}\). \(\texttt{stacks[2]}\) is not empty, set \(\texttt{new_pos := 3}\), and pop the top element of \(\texttt{stacks[2]}\), which makes \(\texttt{stacks}\) become \([[1],[],[1,2]]\), and then call \(\texttt{get(stacks, 3)}\). \(\texttt{stacks[3]}\) is not empty, set \(\texttt{new_pos := 2}\), and pop the top element of \(\texttt{stacks[3]}\), which makes \(\texttt{stacks}\) become \([[1],[],[1]]\), and then call \(\texttt{get(stacks, 2)}\). \(\texttt{stacks[2]}\) is empty, return \(2\).
|
Input: 3 3 1 2 2 3 3 1 2 3 1 2 1 | Output: 1 2 2
|
Master
| 5 | 706 | 495 | 101 | 18 |
1,110 |
C
|
1110C
|
C. Meaningless Operations
| 1,500 |
constructive algorithms; math; number theory
|
Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question.Suppose you are given a positive integer \(a\). You want to choose some integer \(b\) from \(1\) to \(a - 1\) inclusive in such a way that the greatest common divisor (GCD) of integers \(a \oplus b\) and \(a \> \& \> b\) is as large as possible. In other words, you'd like to compute the following function:$$$\(f(a) = \max_{0 < b < a}{gcd(a \oplus b, a \> \& \> b)}.\)\(Here \)\oplus\( denotes the bitwise XOR operation, and \)\&\( denotes the bitwise AND operation.The greatest common divisor of two integers \)x\( and \)y\( is the largest integer \)g\( such that both \)x\( and \)y\( are divided by \)g\( without remainder.You are given \)q\( integers \)a_1, a_2, \ldots, a_q\(. For each of these integers compute the largest possible value of the greatest common divisor (when \)b$$$ is chosen optimally).
|
The first line contains an integer \(q\) (\(1 \le q \le 10^3\)) β the number of integers you need to compute the answer for.After that \(q\) integers are given, one per line: \(a_1, a_2, \ldots, a_q\) (\(2 \le a_i \le 2^{25} - 1\)) β the integers you need to compute the answer for.
|
For each integer, print the answer in the same order as the integers are given in input.
|
For the first integer the optimal choice is \(b = 1\), then \(a \oplus b = 3\), \(a \> \& \> b = 0\), and the greatest common divisor of \(3\) and \(0\) is \(3\).For the second integer one optimal choice is \(b = 2\), then \(a \oplus b = 1\), \(a \> \& \> b = 2\), and the greatest common divisor of \(1\) and \(2\) is \(1\).For the third integer the optimal choice is \(b = 2\), then \(a \oplus b = 7\), \(a \> \& \> b = 0\), and the greatest common divisor of \(7\) and \(0\) is \(7\).
|
Input: 3 2 3 5 | Output: 3 1 7
|
Medium
| 3 | 924 | 282 | 88 | 11 |
909 |
D
|
909D
|
D. Colorful Points
| 2,100 |
data structures; greedy; implementation
|
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.How many operations will you need to perform until the next operation does not have any points to delete?
|
Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc.The number of the points is between 1 and 106.
|
Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.
|
In the first test case, the first operation will delete two middle points and leave points ""ab"", which will be deleted with the second operation. There will be no points left to apply the third operation to.In the second test case, the first operation will delete the four points in the middle, leaving points ""aa"". None of them have neighbors of other colors, so the second operation can't be applied.
|
Input: aabb | Output: 2
|
Hard
| 3 | 770 | 325 | 156 | 9 |
1,920 |
F1
|
1920F1
|
F1. Smooth Sailing (Easy Version)
| 2,500 |
binary search; brute force; data structures; dfs and similar; dsu; graphs; shortest paths
|
The only difference between the two versions of this problem is the constraint on \(q\). You can make hacks only if both versions of the problem are solved.Thomas is sailing around an island surrounded by the ocean. The ocean and island can be represented by a grid with \(n\) rows and \(m\) columns. The rows are numbered from \(1\) to \(n\) from top to bottom, and the columns are numbered from \(1\) to \(m\) from left to right. The position of a cell at row \(r\) and column \(c\) can be represented as \((r, c)\). Below is an example of a valid grid. Example of a valid grid There are three types of cells: island, ocean and underwater volcano. Cells representing the island are marked with a '#', cells representing the ocean are marked with a '.', and cells representing an underwater volcano are marked with a 'v'. It is guaranteed that there is at least one island cell and at least one underwater volcano cell. It is also guaranteed that the set of all island cells forms a single connected component\(^{\dagger}\) and the set of all ocean cells and underwater volcano cells forms a single connected component. Additionally, it is guaranteed that there are no island cells at the edge of the grid (that is, at row \(1\), at row \(n\), at column \(1\), and at column \(m\)).Define a round trip starting from cell \((x, y)\) as a path Thomas takes which satisfies the following conditions: The path starts and ends at \((x, y)\). If Thomas is at cell \((i, j)\), he can go to cells \((i+1, j)\), \((i-1, j)\), \((i, j-1)\), and \((i, j+1)\) as long as the destination cell is an ocean cell or an underwater volcano cell and is still inside the grid. Note that it is allowed for Thomas to visit the same cell multiple times in the same round trip. The path must go around the island and fully encircle it. Some path \(p\) fully encircles the island if it is impossible to go from an island cell to a cell on the grid border by only traveling to adjacent on a side or diagonal cells without visiting a cell on path \(p\). In the image below, the path starting from \((2, 2)\), going to \((1, 3)\), and going back to \((2, 2)\) the other way does not fully encircle the island and is not considered a round trip. Example of a path that does not fully encircle the island The safety of a round trip is the minimum Manhattan distance\(^{\ddagger}\) from a cell on the round trip to an underwater volcano (note that the presence of island cells does not impact this distance).You have \(q\) queries. A query can be represented as \((x, y)\) and for every query, you want to find the maximum safety of a round trip starting from \((x, y)\). It is guaranteed that \((x, y)\) is an ocean cell or an underwater volcano cell.\(^{\dagger}\)A set of cells forms a single connected component if from any cell of this set it is possible to reach any other cell of this set by moving only through the cells of this set, each time going to a cell with a common side.\(^{\ddagger}\)Manhattan distance between cells \((r_1, c_1)\) and \((r_2, c_2)\) is equal to \(|r_1 - r_2| + |c_1 - c_2|\).
|
The first line contains three integers \(n\), \(m\), and \(q\) (\(3 \leq n, m \leq 10^5\), \(9 \leq n \cdot m \leq 3 \cdot 10^5\), \(1 \leq q \leq 5\)) β the number of rows and columns of the grid and the number of queries. Each of the following \(n\) lines contains \(m\) characters describing the cells of the grid. The character '#' denotes an island cell, '.' denotes an ocean cell, and 'v' denotes an underwater volcano cell.It is guaranteed that there is at least one island cell and at least one underwater volcano cell. It is guaranteed that the set of all island cells forms a single connected component and the set of all ocean cells and underwater volcano cells forms a single connected component. Also, it is guaranteed that there are no island cells at the edge of the grid (that is, at the row \(1\), at the row \(n\), at the column \(1\), and at the column \(m\)).The following \(q\) lines describe the queries. Each of these lines contains two integers \(x\) and \(y\) (\(1 \leq x \leq n\), \(1 \leq y \leq m\)) denoting a round trip starting from \((x, y)\).It is guaranteed that \((x, y)\) is an ocean cell or an underwater volcano cell.
|
For each query, output a single integer β the maximum safety of a round trip starting from the specified position.
|
For the first example, the image below shows an optimal round trip starting from \((1, 1)\). The round trip has a safety of \(3\) as the minimum Manhattan distance from a cell on the round trip to an underwater volcano is \(3\). Example of an optimal round trip For the fourth example, remember that it is allowed for Thomas to visit the same cell multiple times in the same round trip. For example, doing so is necessary for the round trip starting from \((7, 6)\).
|
Input: 9 9 3 ......... ......... ....###.. ...v#.... ..###.... ...##...v ...##.... ......... v........ 1 1 9 1 5 7 | Output: 3 0 3
|
Expert
| 7 | 3,081 | 1,155 | 114 | 19 |
1,930 |
F
|
1930F
|
F. Maximize the Difference
| 2,700 |
bitmasks; brute force; dfs and similar
|
For an array \(b\) of \(m\) non-negative integers, define \(f(b)\) as the maximum value of \(\max\limits_{i = 1}^{m} (b_i | x) - \min\limits_{i = 1}^{m} (b_i | x)\) over all possible non-negative integers \(x\), where \(|\) is bitwise OR operation.You are given integers \(n\) and \(q\). You start with an empty array \(a\). Process the following \(q\) queries: \(v\): append \(v\) to the back of \(a\) and then output \(f(a)\). It is guaranteed that \(0 \leq v < n\). The queries are given in a modified way.
|
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 2 \cdot 10^5\)) β the number of test cases. The description of the test cases follows.The first line of each test case contains two integers \(n\) and \(q\) (\(1 \leq n \leq 2^{22}\), \(1 \leq q \leq 10^6\)) β the number of queries.The second line of each test case contains \(q\) space-separated integers \(e_1,e_2,\ldots,e_q\) (\(0 \leq e_i < n\)) β the encrypted values of \(v\).Let \(\mathrm{last}_i\) equal the output of the \((i-1)\)-th query for \(i\geq 2\) and \(\mathrm{last}_i=0\) for \(i=1\). Then the value of \(v\) for the \(i\)-th query is (\(e_i + \mathrm{last}_i\)) modulo \(n\). It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2^{22}\) and the sum of \(q\) over all test cases does not exceed \(10^6\).
|
For each test case, print \(q\) integers. The \(i\)-th integer is the output of the \(i\)-th query.
|
In the first test case, the final \(a=[1,2]\). For \(i=1\), the answer is always \(0\), irrespective of \(x\). For \(i=2\), we can select \(x=5\).In the second test case, the final \(a=[3,1,0,5]\).
|
Input: 25 21 27 43 1 5 2 | Output: 0 2 0 2 3 5
|
Master
| 3 | 509 | 852 | 99 | 19 |
2,101 |
F
|
2101F
|
F. Shoo Shatters the Sunshine
| 3,300 |
combinatorics; dp; trees
|
You are given a tree with \(n\) vertices, where each vertex can be colored red, blue, or white. The coolness of a coloring is defined as the maximum distance\(^{\text{β}}\) between a red and a blue vertex.Formally, if we denote the color of the \(i\)-th vertex as \(c_i\), the coolness of a coloring is \(\max d(u, v)\) over all pairs of vertices \(1\le u, v\le n\) where \(c_u\) is red and \(c_v\) is blue. If there are no red or no blue vertices, the coolness is zero.Your task is to calculate the sum of coolness over all \(3^n\) possible colorings of the tree, modulo \(998\,244\,353\).\(^{\text{β}}\)The distance between two vertices \(a\) and \(b\) in a tree is equal to the number of edges on the unique simple path between vertex \(a\) and vertex \(b\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 50\)). The description of the test cases follows. The first line of each test case contains a single integer \(n\) (\(2\le n\le 3000\)) β the number of vertices in the tree.Each of the next \(n - 1\) lines contains two integers \(u\) and \(v\) (\(1\le u, v\le n\)) β the endpoints of the edges of the tree.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 \(3000\).
|
For each test case, output the sum of coolness over all \(3^n\) possible colorings of the tree, modulo \(998\,244\,353\).
|
In the first test case, there are \(12\) colorings that have at least one blue and one red node. The following pictures show their coloring and their coolness: All these colorings have coolness \(2\) All these colorings have coolness \(1\) Therefore, the sum of coolness over all possible colorings is \(6\cdot 2 + 6\cdot 1 = 18\).In the second test case, the following are some examples of colorings with a coolness of \(3\):
|
Input: 331 22 361 21 31 43 55 6171 21 31 41 52 62 72 83 93 107 117 1211 1313 1414 1510 1616 17 | Output: 18 1920 78555509
|
Master
| 3 | 761 | 550 | 121 | 21 |
780 |
G
|
780G
|
G. Andryusha and Nervous Barriers
| 2,700 |
data structures; dp
|
Andryusha has found a perplexing arcade machine. The machine is a vertically adjusted board divided into square cells. The board has w columns numbered from 1 to w from left to right, and h rows numbered from 1 to h from the bottom to the top.Further, there are barriers in some of board rows. There are n barriers in total, and i-th of them occupied the cells li through ri of the row ui. Andryusha recollects well that no two barriers share the same row. Furthermore, no row is completely occupied with a barrier, that is, at least one cell in each row is free.The player can throw a marble to any column of the machine from above. A marble falls downwards until it encounters a barrier, or falls through the bottom of the board. A marble disappears once it encounters a barrier but is replaced by two more marbles immediately to the left and to the right of the same barrier. In a situation when the barrier is at an edge of the board, both marbles appear next to the barrier at the side opposite to the edge. More than one marble can occupy the same place of the board, without obstructing each other's movement. Ultimately, all marbles are bound to fall from the bottom of the machine. Examples of marble-barrier interaction. Peculiarly, sometimes marbles can go through barriers as if they were free cells. That is so because the barriers are in fact alive, and frightened when a marble was coming at them from a very high altitude. More specifically, if a marble falls towards the barrier i from relative height more than si (that is, it started its fall strictly higher than ui + si), then the barrier evades the marble. If a marble is thrown from the top of the board, it is considered to appear at height (h + 1).Andryusha remembers to have thrown a marble once in each of the columns. Help him find the total number of marbles that came down at the bottom of the machine. Since the answer may be large, print it modulo 109 + 7.
|
The first line contains three integers h, w, and n (1 β€ h β€ 109, 2 β€ w β€ 105, 0 β€ n β€ 105) β the number of rows, columns, and barriers in the machine respectively.Next n lines describe barriers. i-th of these lines containts four integers ui, li, ri, and si (1 β€ ui β€ h, 1 β€ li β€ ri β€ w, 1 β€ si β€ 109) β row index, leftmost and rightmost column index of i-th barrier, and largest relative fall height such that the barrier does not evade a falling marble. It is guaranteed that each row has at least one free cell, and that all ui are distinct.
|
Print one integer β the answer to the problem modulo 109 + 7.
|
In the first sample case, there is a single barrier: if one throws a marble in the second or the third column, two marbles come out, otherwise there is only one. The total answer is 7.In the second sample case, the numbers of resulting marbles are 2, 2, 4, 4, 4 in order of indexing columns with the initial marble.In the third sample case, the numbers of resulting marbles are 1, 1, 4, 4, 4. Note that the first barrier evades the marbles falling from the top of the board, but does not evade the marbles falling from the second barrier.In the fourth sample case, the numbers of resulting marbles are 2, 2, 6, 6, 6, 6, 6, 6, 6, 1, 2, 1, 1, 1, 1. The picture below shows the case when a marble is thrown into the seventh column. The result of throwing a marble into the seventh column.
|
Input: 10 5 13 2 3 10 | Output: 7
|
Master
| 2 | 1,938 | 544 | 61 | 7 |
176 |
B
|
176B
|
B. Word Cut
| 1,700 |
dp
|
Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word ""wordcut"" into word ""cutword"".You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
|
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
|
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
|
The sought way in the first sample is:ab β a|b β ba β b|a β abIn the second sample the two sought ways are: ababab β abab|ab β ababab ababab β ab|abab β ababab
|
Input: abab2 | Output: 1
|
Medium
| 1 | 896 | 352 | 124 | 1 |
1,288 |
E
|
1288E
|
E. Messenger Simulator
| 2,000 |
data structures
|
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has \(n\) friends, numbered from \(1\) to \(n\).Recall that a permutation of size \(n\) is an array of size \(n\) such that each integer from \(1\) to \(n\) occurs exactly once in this array.So his recent chat list can be represented with a permutation \(p\) of size \(n\). \(p_1\) is the most recent friend Polycarp talked to, \(p_2\) is the second most recent and so on.Initially, Polycarp's recent chat list \(p\) looks like \(1, 2, \dots, n\) (in other words, it is an identity permutation).After that he receives \(m\) messages, the \(j\)-th message comes from the friend \(a_j\). And that causes friend \(a_j\) to move to the first position in a permutation, shifting everyone between the first position and the current position of \(a_j\) by \(1\). Note that if the friend \(a_j\) is in the first position already then nothing happens.For example, let the recent chat list be \(p = [4, 1, 5, 3, 2]\): if he gets messaged by friend \(3\), then \(p\) becomes \([3, 4, 1, 5, 2]\); if he gets messaged by friend \(4\), then \(p\) doesn't change \([4, 1, 5, 3, 2]\); if he gets messaged by friend \(2\), then \(p\) becomes \([2, 4, 1, 5, 3]\). For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
|
The first line contains two integers \(n\) and \(m\) (\(1 \le n, m \le 3 \cdot 10^5\)) β the number of Polycarp's friends and the number of received messages, respectively.The second line contains \(m\) integers \(a_1, a_2, \dots, a_m\) (\(1 \le a_i \le n\)) β the descriptions of the received messages.
|
Print \(n\) pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
|
In the first example, Polycarp's recent chat list looks like this: \([1, 2, 3, 4, 5]\) \([3, 1, 2, 4, 5]\) \([5, 3, 1, 2, 4]\) \([1, 5, 3, 2, 4]\) \([4, 1, 5, 3, 2]\) So, for example, the positions of the friend \(2\) are \(2, 3, 4, 4, 5\), respectively. Out of these \(2\) is the minimum one and \(5\) is the maximum one. Thus, the answer for the friend \(2\) is a pair \((2, 5)\).In the second example, Polycarp's recent chat list looks like this: \([1, 2, 3, 4]\) \([1, 2, 3, 4]\) \([2, 1, 3, 4]\) \([4, 2, 1, 3]\)
|
Input: 5 4 3 5 1 4 | Output: 1 3 2 5 1 4 1 5 1 5
|
Hard
| 1 | 1,428 | 303 | 154 | 12 |
1,530 |
A
|
1530A
|
A. Binary Decimal
| 800 |
greedy; math
|
Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either \(0\) or \(1\). For example, \(1\,010\,111\) is a binary decimal, while \(10\,201\) and \(787\,788\) are not.Given a number \(n\), you are asked to represent \(n\) as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.
|
The first line contains a single integer \(t\) (\(1 \le t \le 1000\)), denoting the number of test cases.The only line of each test case contains a single integer \(n\) (\(1 \le n \le 10^9\)), denoting the number to be represented.
|
For each test case, output the smallest number of binary decimals required to represent \(n\) as a sum.
|
In the first test case, \(121\) can be represented as \(121 = 110 + 11\) or \(121 = 111 + 10\).In the second test case, \(5\) can be represented as \(5 = 1 + 1 + 1 + 1 + 1\).In the third test case, \(1\,000\,000\,000\) is a binary decimal itself, thus the answer is \(1\).
|
Input: 3 121 5 1000000000 | Output: 2 5 1
|
Beginner
| 2 | 404 | 231 | 103 | 15 |
1,510 |
C
|
1510C
|
C. Cactus Not Enough
| 2,900 |
dfs and similar; graph matchings; graphs
|
There was no problem about a cactus at the NERC 2020 online round. That's a bad mistake, so judges decided to fix it. You shall not pass to the World Finals 2021 without solving a problem about a cactus!A cactus is a connected undirected graph in which every edge lies on at most one simple cycle. Intuitively, a cactus is a generalization of a tree where some cycles are allowed. Multiedges (multiple edges between a pair of vertices) and loops (edges that connect a vertex to itself) are not allowed in a cactus. Cher has got a cactus. She calls cactus strong if it is impossible to add an edge to it in such a way that it still remains a cactus. But Cher thinks her cactus is not strong enough. She wants to add the smallest possible number of edges to it to make it strong, i. e. to create a new cactus with the same vertices, so that the original cactus is a subgraph of the new one, and it is impossible to add another edge to it so that the graph remains a cactus. Cher hired you to do this job for her. So... it's on you!
|
The input consists of one or more independent test cases.The first line of each test case contains two integers \(n\) and \(m\) (\(1 \le n \le 10^5\), \(0 \le m \le 10^5\)), where \(n\) is the number of vertices in the graph. Vertices are numbered from \(1\) to \(n\). Edges of the graph are represented by a set of edge-distinct paths, where \(m\) is the number of such paths. Each of the following \(m\) lines contains a path in the graph. A path starts with an integer number \(s_i\) (\(2 \le s_i \le 1000\)) followed by \(s_i\) integers from \(1\) to \(n\). These \(s_i\) integers represent vertices of a path. Adjacent vertices in a path are distinct. The path can go through the same vertex multiple times, but every edge is traversed exactly once in the whole test case. There are no multiedges in the graph (there is at most one edge between any two vertices).The last line of the input after all test cases always contains two zeros. It does not define a test case. It just marks the end of the input and does not require any output.All graphs in the input are cacti. The total sum of all values of \(n\) and the total sum of all values of \(m\) throughout the input both do not exceed \(10^5\).
|
For each test case, first output the line with the minimal possible number of additional edges \(A\). Then output \(A\) lines, each describing one edge as \(u_i\) \(v_i\), where \(u_i\) and \(v_i\) are the numbers of vertices to connect. After adding these edges, the resulting graph must be a strong cactus.
|
Input: 6 1 7 1 2 5 6 2 3 4 3 1 4 1 2 3 1 5 2 3 1 3 5 3 1 2 4 7 2 6 1 2 3 4 5 3 3 6 5 7 0 0 | Output: 1 1 4 0 1 5 4 2 1 3 6 7
|
Master
| 3 | 1,029 | 1,204 | 308 | 15 |
|
2,000 |
B
|
2000B
|
B. Seating in a Bus
| 800 |
two pointers
|
In Berland, a bus consists of a row of \(n\) seats numbered from \(1\) to \(n\). Passengers are advised to always board the bus following these rules: If there are no occupied seats in the bus, a passenger can sit in any free seat; Otherwise, a passenger should sit in any free seat that has at least one occupied neighboring seat. In other words, a passenger can sit in a seat with index \(i\) (\(1 \le i \le n\)) only if at least one of the seats with indices \(i-1\) or \(i+1\) is occupied. Today, \(n\) passengers boarded the bus. The array \(a\) chronologically records the seat numbers they occupied. That is, \(a_1\) contains the seat number where the first passenger sat, \(a_2\) β the seat number where the second passenger sat, and so on.You know the contents of the array \(a\). Determine whether all passengers followed the recommendations.For example, if \(n = 5\), and \(a\) = [\(5, 4, 2, 1, 3\)], then the recommendations were not followed, as the \(3\)-rd passenger sat in seat number \(2\), while the neighboring seats with numbers \(1\) and \(3\) were free.
|
The first line of input contains a single integer \(t\) (\(1 \le t \le 10^4\)) β the number of test cases.The following describes the input test cases.The first line of each test case contains exactly one integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β the number of seats in the bus and the number of passengers who boarded the bus.The second line of each test case contains \(n\) distinct integers \(a_i\) (\(1 \le a_i \le n\)) β the seats that the passengers occupied in chronological order.It is guaranteed that the sum of \(n\) values across all test cases does not exceed \(2 \cdot 10^5\), and that no passenger sits in an already occupied seat.
|
For each test case, output on a separate line: ""YES"", if all passengers followed the recommendations; ""NO"" otherwise. You may 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 problem statement.
|
Input: 455 4 2 1 332 3 142 3 1 451 2 3 5 4 | Output: NO YES YES NO
|
Beginner
| 1 | 1,075 | 650 | 266 | 20 |
1,693 |
A
|
1693A
|
A. Directional Increase
| 1,300 |
greedy
|
We have an array of length \(n\). Initially, each element is equal to \(0\) and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by \(1\). Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by \(1\). Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array \(a\). Determine whether it's possible to obtain \(a\) after some operations or not.
|
The first line contains a single integer \(t\) \((1\le t\le 1000)\) β the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer \(n\) \((1\le n\le 2 \cdot 10^5)\) β the size of array \(a\).The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(-10^9 \le a_i \le 10^9\)) β elements of the array.It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(2 \cdot 10^5\).
|
For each test case, print ""Yes"" (without quotes) if it's possible to obtain \(a\) after some operations, and ""No"" (without quotes) otherwise.You can output ""Yes"" and ""No"" in any case (for example, strings ""yEs"", ""yes"" and ""Yes"" will be recognized as a positive response).
|
In the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.\(\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle\)
|
Input: 7 2 1 0 4 2 -1 -1 0 4 1 -4 3 0 4 1 -1 1 -1 5 1 2 3 4 -10 7 2 -1 1 -2 0 0 0 1 0 | Output: No Yes No No Yes Yes Yes
|
Easy
| 1 | 705 | 486 | 285 | 16 |
2,113 |
E
|
2113E
|
E. From Kazan with Love
| 2,800 |
dfs and similar; graphs; implementation; trees
|
Marat is a native of Kazan. Kazan can be represented as an undirected tree consisting of \(n\) vertices. In his youth, Marat often got into street fights, and now he has \(m\) enemies, numbered from \(1\) to \(m\), living in Kazan along with him.Every day, all the people living in the city go to work. Marat knows that the \(i\)-th of his enemies lives at vertex \(a_i\) and works at vertex \(b_i\). He himself lives at vertex \(x\) and works at vertex \(y\). It is guaranteed that \(a_i \ne x\).All enemies go to work via the shortest path and leave their homes at time \(1\). That is, if we represent the shortest path between vertices \(a_i\) and \(b_i\) as \(c_1, c_2, c_3, \ldots, c_k\) (where \(c_1 = a_i\) and \(c_k = b_i\)), then at the moment \(p\) (\(1 \le p \le k\)), the enemy numbered \(i\) will be at vertex \(c_p\).Marat really does not want to meet any of his enemies at the same vertex at the same time, as this would create an awkward situation, but they can meet on an edge. Marat also leaves his home at time \(1\), and at each subsequent moment in time, he can either move to an adjacent vertex or stay at his current one.Note that Marat can only meet the \(i\)-th enemy at the moments \(2, 3, \ldots, k\) (where \(c_1, c_2, \ldots, c_k\) is the shortest path between vertices \(a_i\) and \(b_i\)). In other words, starting from the moment after the enemy reaches work, Marat can no longer meet him.Help Marat find the earliest moment in time when he can reach work without encountering any enemies along the way, or determine 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 four integers \(n\), \(m\), \(x\), and \(y\) (\(2 \le n \le 10^5\), \(1 \le m \le 200\), \(1 \le x, y \le n\), \(x \neq y\)) β the number of vertices in the tree, the number of enemies, and the vertex numbers from which Marat starts his journey and where he needs to arrive, respectively.The \(j\)-th of the following \(n - 1\) lines contains two integers \(v_j\) and \(u_j\) (\(1 \le v_j, u_j \le n\), \(v_j \neq u_j\)) β the endpoints of the \(j\)-th edge of the tree.The \(i\)-th of the following \(m\) lines contains two integers \(a_i\) and \(b_i\) (\(1 \le a_i, b_i \le n\), \(a_i \neq b_i\), \(a_i \ne x\)) β the description of the routes of Marat's enemies.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
|
For each test case, output a single integer β the minimum moment in time when Marat can reach work, or \(-1\) if it is impossible.
|
In the first test case, it is possible to reach vertex number \(4\) from vertex number \(1\) via the shortest path. Note that Marat will meet a single enemy on an edge, not at a vertex.In the second test case, the optimal strategy is to wait for one moment in time at the starting vertex and then go along the shortest path from vertex \(1\) to vertex \(5\). If he does not stop at the beginning, Marat will meet his enemy at a vertex, not on an edge.In the third test case, it is beneficial to go from vertex \(1\) to vertex \(4\). After that, he should not move anywhere for one moment in time, and then go along the shortest path from vertex \(4\) to vertex \(9\).
|
Input: 54 1 1 41 22 33 44 15 1 1 51 22 33 44 55 19 2 1 91 22 33 43 55 66 76 88 99 17 19 2 7 21 42 53 64 55 64 75 86 92 83 73 2 1 31 22 32 13 1 | Output: 4 6 10 5 -1
|
Master
| 4 | 1,571 | 953 | 130 | 21 |
65 |
D
|
65D
|
D. Harry Potter and the Sorting Hat
| 2,200 |
brute force; dfs and similar; hashing
|
As you know, Hogwarts has four houses: Gryffindor, Hufflepuff, Ravenclaw and Slytherin. The sorting of the first-years into houses is done by the Sorting Hat. The pupils are called one by one in the alphabetical order, each of them should put a hat on his head and, after some thought, the hat solemnly announces the name of the house the student should enter.At that the Hat is believed to base its considerations on the student's personal qualities: it sends the brave and noble ones to Gryffindor, the smart and shrewd ones β to Ravenclaw, the persistent and honest ones β to Hufflepuff and the clever and cunning ones β to Slytherin. However, a first year student Hermione Granger got very concerned about the forthcoming sorting. She studied all the literature on the Sorting Hat and came to the conclusion that it is much simpler than that. If the relatives of the student have already studied at Hogwarts, the hat puts the student to the same house, where his family used to study. In controversial situations, when the relatives studied in different houses or when they were all Muggles like Hermione's parents, then the Hat sorts the student to the house, to which the least number of first years has been sent at that moment. If there are several such houses, the choice is given to the student himself. Then the student can choose any of the houses, to which the least number of first years has been sent so far. Hermione has already asked the students that are on the list before her about their relatives. Now she and her new friends Harry Potter and Ron Weasley want to find out into what house the Hat will put Hermione.
|
The first input line contains an integer n (1 β€ n β€ 10000). It is the number of students who are in the list before Hermione. The next line contains n symbols. If all the relatives of a student used to study in the same house, then the i-th character in the string coincides with the first letter of the name of this house. Otherwise, the i-th symbol is equal to ""?"".
|
Print all the possible houses where Hermione can be sent. The names of the houses should be printed in the alphabetical order, one per line.
|
Consider the second example. There are only two students before Hermione. The first student is sent to Hufflepuff. The second disciple is given the choice between the houses where the least number of students has been sent, i.e. Gryffindor, Slytherin and Ravenclaw. If he chooses Gryffindor, Hermione is forced to choose between Ravenclaw and Slytherin, if he chooses Ravenclaw, Hermione will choose between Gryffindor and Slytherin, if he chooses Slytherin, Hermione will choose between Gryffindor and Ravenclaw. In the end, the following situation is possible (it depends on the choice of the second student and Hermione). Hermione will end up 1) in Gryffindor, 2) in Ravenclaw, 3) in Slytherin. Note that, despite the fact that in neither case Hermione will be given a choice between all the three options, they are all possible and they should all be printed in the answer. Hermione will not, under any circumstances, end up in Hufflepuff.
|
Input: 11G????SS???H | Output: GryffindorRavenclaw
|
Hard
| 3 | 1,635 | 369 | 140 | 0 |
830 |
C
|
830C
|
C. Bamboo Partition
| 2,300 |
brute force; data structures; implementation; math; number theory; sortings; two pointers
|
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high. Vladimir has just planted n bamboos in a row, each of which has height 0 meters right now, but they grow 1 meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing.Vladimir wants to check the bamboos each d days (i.e. d days after he planted, then after 2d days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than k meters.What is the maximum value d he can choose so that he can achieve what he wants without cutting off more than k meters of bamboo?
|
The first line contains two integers n and k (1 β€ n β€ 100, 1 β€ k β€ 1011) β the number of bamboos and the maximum total length of cut parts, in meters.The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the required heights of bamboos, in meters.
|
Print a single integer β the maximum value of d such that Vladimir can reach his goal.
|
In the first example Vladimir can check bamboos each 3 days. Then he will cut the first and the second bamboos after 3 days, and the third bamboo after 6 days. The total length of cut parts is 2 + 0 + 1 = 3 meters.
|
Input: 3 41 3 5 | Output: 3
|
Expert
| 7 | 941 | 262 | 86 | 8 |
316 |
E3
|
316E3
|
E3. Summer Homework
| 2,300 |
data structures; math
|
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: For given numbers xi and vi assign value vi to element axi. For given numbers li and ri you've got to calculate sum , where f0 = f1 = 1 and at i β₯ 2: fi = fi - 1 + fi - 2. For a group of three numbers li ri di you should increase value ax by di for all x (li β€ x β€ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.
|
The first line contains two integers n and m (1 β€ n, m β€ 2Β·105) β the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 β€ ti β€ 3) β the operation type: if ti = 1, then next follow two integers xi vi (1 β€ xi β€ n, 0 β€ vi β€ 105); if ti = 2, then next follow two integers li ri (1 β€ li β€ ri β€ n); if ti = 3, then next follow three integers li ri di (1 β€ li β€ ri β€ n, 0 β€ di β€ 105). The input limits for scoring 30 points are (subproblem E1): It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): No extra limitations.
|
For each query print the calculated sum modulo 1000000000 (109).
|
Input: 5 51 3 1 2 42 1 42 1 52 2 41 3 102 1 5 | Output: 1232850
|
Expert
| 2 | 632 | 972 | 64 | 3 |
|
506 |
E
|
506E
|
E. Mr. Kitayuta's Gift
| 3,000 |
combinatorics; dp; matrices; strings
|
Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly n lowercase English letters into s to make it a palindrome. (A palindrome is a string that reads the same forward and backward. For example, ""noon"", ""testset"" and ""a"" are all palindromes, while ""test"" and ""kitayuta"" are not.) You can choose any n lowercase English letters, and insert each of them to any position of s, possibly to the beginning or the end of s. You have to insert exactly n letters even if it is possible to turn s into a palindrome by inserting less than n letters.Find the number of the palindromes that can be obtained in this way, modulo 10007.
|
The first line contains a string s (1 β€ |s| β€ 200). Each character in s is a lowercase English letter.The second line contains an integer n (1 β€ n β€ 109).
|
Print the number of the palindromes that can be obtained, modulo 10007.
|
For the first sample, you can obtain the palindrome ""reviver"" by inserting 'r' to the end of ""revive"".For the second sample, the following 28 palindromes can be obtained: ""adada"", ""adbda"", ..., ""adzda"", ""dadad"" and ""ddadd"".
|
Input: revive1 | Output: 1
|
Master
| 4 | 694 | 154 | 71 | 5 |
2,115 |
A
|
2115A
|
A. Gellyfish and Flaming Peony
| 1,500 |
constructive algorithms; dp; math; number theory
|
Gellyfish hates math problems, but she has to finish her math homework:Gellyfish is given an array of \(n\) positive integers \(a_1, a_2, \ldots, a_n\).She needs to do the following two-step operation until all elements of \(a\) are equal: Select two indexes \(i\), \(j\) satisfying \(1 \leq i, j \leq n\) and \(i \neq j\). Replace \(a_i\) with \(\gcd(a_i, a_j)\). Now, Gellyfish asks you for the minimum number of operations to achieve her goal.It can be proven that Gellyfish can always achieve her goal.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 5000\)). The description of the test cases follows. The first line of each test case contains a single integer \(n\) (\(1 \leq n \leq 5000\)) β the length of the array.The second line of each test case contains \(n\) integers \(a_1,a_2,\ldots,a_n\) (\(1 \leq a_i \leq 5000\)) β the elements of the array.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5000\).
|
For each test case, output a single integer β the minimum number of operations to achieve her goal.
|
In the first test case, the following is a way that minimizes the number of operations: Choose \(i = 3\) and \(j=2\) and replace \(a_3\) with \(\gcd(a_3,a_2) = \gcd(30, 20) = 10\), then \(a\) becomes \([12, 20, 10]\). Choose \(i=1\) and \(j=3\) and replace \(a_1\) with \(\gcd(a_1,a_3) = \gcd(12, 10) = 2\), then \(a\) becomes \([2, 20, 10]\). Choose \(i=2\) and \(j=1\) and replace \(a_2\) with \(\gcd(a_2,a_1) = \gcd(20, 2) = 2\), then \(a\) becomes \([2, 2, 10]\). Choose \(i=3\) and \(j=1\) and replace \(a_3\) with \(\gcd(a_3,a_1) = \gcd(10, 2) = 2\), then \(a\) becomes \([2, 2, 2]\).
|
Input: 3312 20 3061 9 1 9 8 136 14 15 | Output: 4 3 3
|
Medium
| 4 | 506 | 498 | 99 | 21 |
1,344 |
F
|
1344F
|
F. Piet's Palette
| 3,200 |
matrices
|
Piet Mondrian is an artist most famous for his minimalist works, consisting only of the four colors red, yellow, blue, and white. Most people attribute this to his style, but the truth is that his paint behaves in a very strange way where mixing two primary colors only produces another primary color! A lesser known piece, entitled ""Pretentious rectangles"" A sequence of primary colors (red, yellow, blue) is mixed as follows. While there are at least two colors, look at the first two. If they are distinct, replace them with the missing color. If they are the same, remove them from the sequence. In the end, if there is one color, that is the resulting color. Otherwise, if the sequence is empty, we say the resulting color is white. Here are two example mixings: Piet has a color palette with cells numbered from \(1\) to \(n\). Each cell contains a primary color or is empty. Piet is very secretive, and will not share his palette with you, so you do not know what colors belong to each cell.However, he did perform \(k\) operations. There are four kinds of operations: In a mix operation, Piet chooses a subset of cells and mixes their colors together in some order. The order is not necessarily by increasing indexes. He records the resulting color. Empty cells are skipped over, having no effect on the mixing process. The mixing does not change the color values stored in the cells. In a RY operation, Piet chooses a subset of cells. Any red cells in this subset become yellow, and any yellow cells in this subset become red. Blue and empty cells remain unchanged. In a RB operation, Piet chooses a subset of cells. Any red cells in this subset become blue, and any blue cells in this subset become red. Yellow and empty cells remain unchanged. In a YB operation, Piet chooses a subset of cells. Any yellow cells in this subset become blue, and any blue cells in this subset become yellow. Red and empty cells remain unchanged. Piet only tells you the list of operations he performs in chronological order, the indexes involved, and the resulting color of each mix operation. For each mix operation, you also know the order in which the cells are mixed. Given this information, determine the color of each cell in the initial palette. That is, you should find one possible state of the palette (before any operations were performed), or say that the described situation is impossible.
|
The first line contains two integers \(n\) and \(k\) (\(1\le n,k\le 1000\)) β the number of cells in the palette and the number of operations, respectively.The next \(k\) lines describe the operations. The \(i\)-th line begins with the name of the \(i\)-th operation and an integer \(m\) (\(1\le m\le n\)) β the number of indexes involved. Then follow \(m\) integers \(j_1,\ldots,j_m\) (\(1\le j_i\le n\)) β the indexes of the operation. It is guaranteed that all \(j_i\) are distinct within an operation. If it is a mix operation, the indexes are listed in the order the colors are mixed, and the line also ends with a character representing the resulting color: ""R"" for red, ""Y"" for yellow, ""B"" for blue, and ""W"" for white.
|
Output ""YES"" if a solution exists, or ""NO"" otherwise. You can print each character in any case (upper or lower).If the answer is ""YES"", on the next line output a string of length \(n\), consisting of characters ""R"", ""Y"", ""B"", and ""."", representing the paint colors in the \(n\) cells of the initial palette (red, yellow, blue, and empty, respectively). If there are multiple solutions, print any. You can print each character in any case (upper or lower).
|
For the first test case, the answer ""YB."" is consistent with both mixings. The first mixing ""BY"" results in red, while the second mixing ""Y"" results in yellow (the empty cell is ignored). Other valid solutions include ""BYR"" and "".RY"".For the second test case, we can show that no solution exists.For the third test case, the answer ""R"" is consistent with all operations. In the first two operations it changes to ""Y"", then ""B"". In the final operation, the mixing ""B"" results in blue.For the fourth test case, the answer "".RY"" is consistent with all operations. The first two mixings are ""R"" and ""Y"", resulting in red and yellow, respectively. During the next three operations, the palette changes to "".YR"", then "".YB"", then "".BY"". The final three mixings agree with this palette.
|
Input: 3 2 mix 2 2 1 R mix 2 1 3 Y | Output: YES YB.
|
Master
| 1 | 2,396 | 733 | 469 | 13 |
1,578 |
G
|
1578G
|
G. Game of Chance
| 3,500 |
math; probabilities
|
The King wants to marry off his daughter, and he wants her husband to have the greatest innate luckiness possible. To find such a person he decided to hold a heads-or-tails tournament. If person \(A\) with luckiness \(x\) and person \(B\) with luckiness \(y\) play heads-or-tails against each other, person \(A\) wins with probability \(x/(x+y)\). The tournament has several rounds. Each round some participants are split into pairs. Each pair plays against each other, and the loser leaves the tournament. The participants are numbered from \(1\) to \(n\). During the first round, a number \(k\) (\(1 \le k \le n\)) is selected such that \(n-k/2\) is a power of \(2\) (such \(k\) always exists and is unique). Only participants numbered from \(1\) to \(k\) take part in the first round. It ensures that in all other rounds the number of participants is the power of \(2\). During other rounds, all the participants who still have not left the tournament take part. If during some round, participants numbered \(p_1 < \ldots < p_{2m}\) take part, then they are split into pairs in the following manner: participant \(p_{2i-1}\) plays against participant \(p_{2i}\) for each \(i\) from \(1\) to \(m\). The rounds are held until only one participant is left. He is declared the winner of the tournament and he will marry the King's daughter. The princess can't wait to find out who is her future husband. She asked every participant to tell her his luckiness. Assuming they did not lie, she wants to know the probability of each participant winning the tournament. As you are the best friend of the princess, she asks you to help her.
|
The first line of the input contains the number of participants, \(n\) (\(2 \le n \le 3 \cdot 10^5\)). The second line of the input contains \(n\) integer numbers, \(a_1, \ldots, a_{n}\) (\(1 \le a_i \le 10^9\)). The luckiness of the \(i\)-th participant equals to \(a_i\).
|
Print \(n\) numbers \(p_i\). The \(i\)-th number should be the probability of the \(i\)-th participant winning the tournament. The absolute error of your answer must not exceed \(10^{-9}\).
|
Here is an example of a tournament bracket, showing the winning probability in each pair.
|
Input: 5 1 4 1 1 4 | Output: 0.026 0.3584 0.0676 0.0616 0.4864
|
Master
| 2 | 1,632 | 273 | 189 | 15 |
409 |
B
|
409B
|
B. Mysterious Language
| 1,700 |
*special
|
You are given a mysterious language (codenamed ""Secret"") available in ""Custom Invocation"" tab. Figure out what this language is and write a program which prints its name. Note that the program must be written in this language.
|
This program has only one test (your program doesn't have to read anything).
|
Output the name of the mysterious language. Note that the name is case-sensitive and might contain digits and special characters.
|
Some scientists disagree on what should be considered as a language and what should be considered as a dialect.
|
Medium
| 1 | 230 | 76 | 129 | 4 |
|
1,833 |
E
|
1833E
|
E. Round Dance
| 1,600 |
dfs and similar; dsu; graphs; shortest paths
|
\(n\) people came to the festival and decided to dance a few round dances. There are at least \(2\) people in the round dance and each person has exactly two neighbors. If there are \(2\) people in the round dance then they have the same neighbor on each side.You decided to find out exactly how many dances there were. But each participant of the holiday remembered exactly one neighbor. Your task is to determine what the minimum and maximum number of round dances could be.For example, if there were \(6\) people at the holiday, and the numbers of the neighbors they remembered are equal \([2, 1, 4, 3, 6, 5]\), then the minimum number of round dances is\(1\): \(1 - 2 - 3 - 4 - 5 - 6 - 1\) and the maximum is \(3\): \(1 - 2 - 1\) \(3 - 4 - 3\) \(5 - 6 - 5\)
|
The first line contains a positive number \(t\) (\(1 \le t \le 10^4\)) β the number of test cases. The following is a description of the test cases.The first line of the description of each test case contains a positive number \(n\) (\(2 \le n \le 2 \cdot 10^5\)) β the number of people at the holiday.The second line of the description of each test case contains \(n\) integers \(a_i\) (\(1 \le a_i \le n, a_i \neq i\)) β the number of the neighbor that the \(i\)th person remembered.It is guaranteed that the test cases are correct and corresponds to at least one division of people into round dances.It is guaranteed that the sum of \(n\) for all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, output two integers β the minimum and maximum number of round dances that could be.
|
Input: 1062 1 4 3 6 562 3 1 5 6 492 3 2 5 6 5 8 9 822 144 3 2 152 3 4 5 165 3 4 1 1 253 5 4 1 266 3 2 5 4 365 1 4 3 4 2 | Output: 1 3 2 2 1 3 1 1 1 2 1 1 1 1 2 2 1 2 1 1
|
Medium
| 4 | 761 | 694 | 103 | 18 |
|
1,832 |
B
|
1832B
|
B. Maximum Sum
| 1,100 |
brute force; sortings; two pointers
|
You are given an array \(a_1, a_2, \dots, a_n\), where all elements are different.You have to perform exactly \(k\) operations with it. During each operation, you do exactly one of the following two actions (you choose which to do yourself): find two minimum elements in the array, and delete them; find the maximum element in the array, and delete it. You have to calculate the maximum possible sum of elements in the resulting array.
|
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 two integers \(n\) and \(k\) (\(3 \le n \le 2 \cdot 10^5\); \(1 \le k \le 99999\); \(2k < n\)) β the number of elements and operations, respectively. the second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\); all \(a_i\) are different) β the elements of the array. Additional constraint on the input: the sum of \(n\) does not exceed \(2 \cdot 10^5\).
|
For each test case, print one integer β the maximum possible sum of elements in the resulting array.
|
In the first testcase, applying the first operation produces the following outcome: two minimums are \(1\) and \(2\); removing them leaves the array as \([5, 10, 6]\), with sum \(21\); a maximum is \(10\); removing it leaves the array as \([2, 5, 1, 6]\), with sum \(14\). \(21\) is the best answer.In the second testcase, it's optimal to first erase two minimums, then a maximum.
|
Input: 65 12 5 1 10 65 22 5 1 10 63 11 2 36 115 22 12 10 13 116 215 22 12 10 13 115 1999999996 999999999 999999997 999999998 999999995 | Output: 21 11 3 62 46 3999999986
|
Easy
| 3 | 435 | 536 | 100 | 18 |
1,729 |
A
|
1729A
|
A. Two Elevators
| 800 |
math
|
Vlad went into his appartment house entrance, now he is on the \(1\)-th floor. He was going to call the elevator to go up to his apartment.There are only two elevators in his house. Vlad knows for sure that: the first elevator is currently on the floor \(a\) (it is currently motionless), the second elevator is located on floor \(b\) and goes to floor \(c\) (\(b \ne c\)). Please note, if \(b=1\), then the elevator is already leaving the floor \(1\) and Vlad does not have time to enter it. If you call the first elevator, it will immediately start to go to the floor \(1\). If you call the second one, then first it will reach the floor \(c\) and only then it will go to the floor \(1\). It takes \(|x - y|\) seconds for each elevator to move from floor \(x\) to floor \(y\).Vlad wants to call an elevator that will come to him faster. Help him choose such an elevator.
|
The first line of the input contains the only \(t\) (\(1 \le t \le 10^4\)) β the number of test cases.This is followed by \(t\) lines, three integers each \(a\), \(b\) and \(c\) (\(1 \le a, b, c \le 10^8\), \(b \ne c\)) β floor numbers described in the statement.
|
Output \(t\) numbers, each of which is the answer to the corresponding test case. As an answer, output: \(1\), if it is better to call the first elevator; \(2\), if it is better to call the second one; \(3\), if it doesn't matter which elevator to call (both elevators will arrive in the same time).
|
In the first test case of the example, the first elevator is already on the floor of \(1\).In the second test case of the example, when called, the elevators would move as follows: At the time of the call, the first elevator is on the floor of \(3\), and the second one is on the floor of \(1\), but is already going to another floor; in \(1\) second after the call, the first elevator would be on the floor \(2\), the second one would also reach the floor \(2\) and now can go to the floor \(1\); in \(2\) seconds, any elevator would reach the floor \(1\). In the third test case of the example, the first elevator will arrive in \(2\) seconds, and the second in \(1\).
|
Input: 31 2 33 1 23 2 1 | Output: 1 3 2
|
Beginner
| 1 | 872 | 263 | 299 | 17 |
1,430 |
A
|
1430A
|
A. Number of Apartments
| 900 |
brute force; constructive algorithms; math
|
Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room β five windows, and a seven-room β seven windows.Monocarp went around the building and counted \(n\) windows. Now he is wondering, how many apartments of each type the building may have.Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has \(n\) windows. If there are multiple answers, you can print any of them.Here are some examples: if Monocarp has counted \(30\) windows, there could have been \(2\) three-room apartments, \(2\) five-room apartments and \(2\) seven-room apartments, since \(2 \cdot 3 + 2 \cdot 5 + 2 \cdot 7 = 30\); if Monocarp has counted \(67\) windows, there could have been \(7\) three-room apartments, \(5\) five-room apartments and \(3\) seven-room apartments, since \(7 \cdot 3 + 5 \cdot 5 + 3 \cdot 7 = 67\); if Monocarp has counted \(4\) windows, he should have mistaken since no building with the aforementioned layout can have \(4\) windows.
|
Th first line contains one integer \(t\) (\(1 \le t \le 1000\)) β the number of test cases.The only line of each test case contains one integer \(n\) (\(1 \le n \le 1000\)) β the number of windows in the building.
|
For each test case, if a building with the new layout and the given number of windows just can't exist, print \(-1\).Otherwise, print three non-negative integers β the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.
|
Input: 4 30 67 4 14 | Output: 2 2 2 7 5 3 -1 0 0 2
|
Beginner
| 3 | 1,382 | 213 | 286 | 14 |
|
575 |
I
|
575I
|
I. Robots protection
| 2,800 |
data structures
|
Company ""Robots industries"" produces robots for territory protection. Robots protect triangle territories β right isosceles triangles with catheti parallel to North-South and East-West directions.Owner of some land buys and sets robots on his territory to protect it. From time to time, businessmen want to build offices on that land and want to know how many robots will guard it. You are to handle these queries.
|
The first line contains integer N β width and height of the land, and integer Q β number of queries to handle.Next Q lines contain queries you need to process.Two types of queries: 1 dir x y len β add a robot to protect a triangle. Depending on the value of dir, the values of x, y and len represent a different triangle: dir = 1: Triangle is defined by the points (x, y), (x + len, y), (x, y + len) dir = 2: Triangle is defined by the points (x, y), (x + len, y), (x, y - len) dir = 3: Triangle is defined by the points (x, y), (x - len, y), (x, y + len) dir = 4: Triangle is defined by the points (x, y), (x - len, y), (x, y - len) 2 x y β output how many robots guard this point (robot guards a point if the point is inside or on the border of its triangle) 1 β€ N β€ 5000 1 β€ Q β€ 105 1 β€ dir β€ 4 All points of triangles are within range [1, N] All numbers are positive integers
|
For each second type query output how many robots guard this point. Each answer should be in a separate line.
|
Input: 17 101 1 3 2 41 3 10 3 71 2 6 8 21 3 9 4 22 4 41 4 15 10 62 7 72 9 42 12 22 13 8 | Output: 22201
|
Master
| 1 | 416 | 879 | 109 | 5 |
|
241 |
C
|
241C
|
C. Mirror Box
| 2,000 |
geometry; implementation
|
Mirror Box is a name of a popular game in the Iranian National Amusement Park (INAP). There is a wooden box, 105 cm long and 100 cm high in this game. Some parts of the box's ceiling and floor are covered by mirrors. There are two negligibly small holes in the opposite sides of the box at heights hl and hr centimeters above the floor. The picture below shows what the box looks like. In the game, you will be given a laser gun to shoot once. The laser beam must enter from one hole and exit from the other one. Each mirror has a preset number vi, which shows the number of points players gain if their laser beam hits that mirror. Also β to make things even funnier β the beam must not hit any mirror more than once.Given the information about the box, your task is to find the maximum score a player may gain. Please note that the reflection obeys the law ""the angle of incidence equals the angle of reflection"".
|
The first line of the input contains three space-separated integers hl, hr, n (0 < hl, hr < 100, 0 β€ n β€ 100) β the heights of the holes and the number of the mirrors.Next n lines contain the descriptions of the mirrors. The i-th line contains space-separated vi, ci, ai, bi; the integer vi (1 β€ vi β€ 1000) is the score for the i-th mirror; the character ci denotes i-th mirror's position β the mirror is on the ceiling if ci equals ""T"" and on the floor if ci equals ""F""; integers ai and bi (0 β€ ai < bi β€ 105) represent the x-coordinates of the beginning and the end of the mirror.No two mirrors will share a common point. Consider that the x coordinate increases in the direction from left to right, so the border with the hole at height hl has the x coordinate equal to 0 and the border with the hole at height hr has the x coordinate equal to 105.
|
The only line of output should contain a single integer β the maximum possible score a player could gain.
|
The second sample is depicted above. The red beam gets 10 + 50 + 5 + 35 + 8 + 2 = 110 points and the blue one gets 120.The red beam on the picture given in the statement shows how the laser beam can go approximately, this is just illustration how the laser beam can gain score. So for the second sample there is no such beam that gain score 110.
|
Input: 50 50 710 F 1 8000020 T 1 8000030 T 81000 8200040 T 83000 8400050 T 85000 8600060 T 87000 8800070 F 81000 89000 | Output: 100
|
Hard
| 2 | 917 | 855 | 105 | 2 |
2,068 |
J
|
2068J
|
J. The Ultimate Wine Tasting Event
| 2,000 |
combinatorics; greedy
|
Rumors of the excellence of Gabriella's wine tasting events have toured the world and made it to the headlines of prestigious wine magazines. Now, she has been asked to organize an event at the EUC 2025!This time she selected \(2n\) bottles of wine, of which exactly \(n\) are of white wine, and exactly \(n\) of red wine. She arranged them in a line as usual, in a predetermined order described by a string \(s\) of length \(2n\): for \(1 \le i \le 2n\), the \(i\)-th bottle from the left is white wine if \(s_i = \texttt{W}\) and red wine if \(s_i = \texttt{R}\).To spice things up for the attendees (which include EUC contestants), Gabriella came up with the following wine-themed problem:Consider a way of dividing the \(2n\) bottles into two disjoint subsets, each containing \(n\) bottles. Then, for every \(1 \le i \le n\), swap the \(i\)-th bottle in the first subset (from the left) and the \(i\)-th bottle of the second subset (also from the left). Is it possible to choose the subsets so that, after this operation is done exactly once, the white wines occupy the first \(n\) positions?
|
The first line contains an integer \(t\) (\(1 \le t \le 500\)) β the number of test cases. The descriptions of the \(t\) test cases follow.The first line of each test case contains an integer \(n\) (\(1 \le n \le 100\)) β where \(2n\) is the total number of bottles.The second line of each test case contains a string \(s\) of length \(2n\), describing the bottle arrangement β the \(i\)-th character of \(s\) (\(1 \le i \le 2n\)) is \(\texttt{W}\) for a white wine and \(\texttt{R}\) for a red wine.It is guaranteed that \(s\) contains exactly \(n\) \(\texttt{W}\)'s and \(n\) \(\texttt{R}\)'s.
|
For each test case, print \(\texttt{YES}\) if it is possible to divide the bottles as explained in the statement. Otherwise, print \(\texttt{NO}\).
|
In the first test case, we can make one subset out of the bottles at positions \(1\), \(2\), \(3\) and \(7\) (which are, respectively: white, red, red, red) and the other subset out of the bottles at positions \(4\), \(5\), \(6\), \(8\) (which are, respectively: white, white, white, red). We will then swap pairs \((1, 4)\), \((2, 5)\), \((3, 6)\) and \((7, 8)\), after which the white wines will occupy the first \(4\) positions, and the red wines the last \(4\) positions.In the second test case, there is only one possible way to form the subsets: one with the first bottle, and one with the second bottle. After swapping, the resulting arrangement is \(\texttt{RW}\), therefore there is no solution.
|
Input: 34WRRWWWRR1WR20WWWWRRWRRRRRWRRWRWRRWRRWWWWWWWRWWRWWRRRR | Output: YES NO YES
|
Hard
| 2 | 1,097 | 595 | 147 | 20 |
81 |
A
|
81A
|
A. Plug-in
| 1,400 |
implementation
|
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase ""how are you"" he can type ""hhoow aaaare yyoouu"". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.
|
The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters.
|
Print the given string after it is processed. It is guaranteed that the result will contain at least one character.
|
Input: hhoowaaaareyyoouu | Output: wre
|
Easy
| 1 | 1,132 | 171 | 115 | 0 |
|
113 |
A
|
113A
|
A. Grammar Lessons
| 1,600 |
implementation; strings
|
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words ""lios"", ""liala"", ""etr"" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
|
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
|
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print ""NO"" (without the quotes). Otherwise, print ""YES"" (without the quotes).
|
Input: petr | Output: YES
|
Medium
| 2 | 1,942 | 370 | 200 | 1 |
|
60 |
B
|
60B
|
B. Serial Time!
| 1,400 |
dfs and similar; dsu
|
The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped k Γ n Γ m, that is, it has k layers (the first layer is the upper one), each of which is a rectangle n Γ m with empty squares ('.') and obstacles ('#'). The water can only be present in the empty squares. The tap is positioned above the square (x, y) of the first layer, it is guaranteed that this square is empty. Every minute a cubical unit of water falls into the plate. Find out in how many minutes the Serial Guy should unglue himself from the soap opera and turn the water off for it not to overfill the plate. That is, you should find the moment of time when the plate is absolutely full and is going to be overfilled in the next moment.Note: the water fills all the area within reach (see sample 4). Water flows in each of the 6 directions, through faces of 1 Γ 1 Γ 1 cubes.
|
The first line contains three numbers k, n, m (1 β€ k, n, m β€ 10) which are the sizes of the plate. Then follow k rectangles consisting of n lines each containing m characters '.' or '#', which represents the ""layers"" of the plate in the order from the top to the bottom. The rectangles are separated by empty lines (see the samples). The last line contains x and y (1 β€ x β€ n, 1 β€ y β€ m) which are the tap's coordinates. x is the number of the line and y is the number of the column. Lines of each layer are numbered from left to right by the integers from 1 to n, columns of each layer are numbered from top to bottom by the integers from 1 to m.
|
The answer should contain a single number, showing in how many minutes the plate will be filled.
|
Input: 1 1 1.1 1 | Output: 1
|
Easy
| 2 | 1,033 | 649 | 96 | 0 |
|
1,996 |
C
|
1996C
|
C. Sort
| 1,200 |
dp; greedy; sortings; strings
|
You are given two strings \(a\) and \(b\) of length \(n\). Then, you are (forced against your will) to answer \(q\) queries.For each query, you are given a range bounded by \(l\) and \(r\). In one operation, you can choose an integer \(i\) (\(l \leq i \leq r\)) and set \(a_i = x\) where \(x\) is any character you desire. Output the minimum number of operations you must perform such that \(\texttt{sorted(a[l..r])} = \texttt{sorted(b[l..r])}\). The operations you perform on one query does not affect other queries.For an arbitrary string \(c\), \(\texttt{sorted(c[l..r])}\) denotes the substring consisting of characters \(c_l, c_{l+1}, ... , c_r\) sorted in lexicographical order.
|
The first line contains \(t\) (\(1 \leq t \leq 1000\)) β the number of test cases.The first line of each test case contains two integers \(n\) and \(q\) (\(1 \leq n, q \leq 2 \cdot 10^5\)) β the length of both strings and the number of queries.The following line contains \(a\) of length \(n\). It is guaranteed \(a\) only contains lowercase latin letters.The following line contains \(b\) of length \(n\). It is guaranteed \(b\) only contains lowercase latin letters.The following \(q\) lines contain two integers \(l\) and \(r\) (\(1 \leq l \leq r \leq n\)) β the range of the query.It is guaranteed the sum of \(n\) and \(q\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each query, output an integer, the minimum number of operations you need to perform in a new line.
|
For the first query, \(\texttt{sorted(a[1..5])} =\) abcde and \(\texttt{sorted(b[1..5])} =\) abcde, so no operations are necessary.For the second query, you need to set \(a_1 = \) e. Then, \(\texttt{sorted(a[1..4])} = \texttt{sorted(b[1..4])} = \) bcde.
|
Input: 35 3abcdeedcba1 51 43 34 2zzdeazbe1 31 46 3uwuwuwwuwuwu2 41 31 6 | Output: 0 1 0 2 2 1 1 0
|
Easy
| 4 | 684 | 682 | 102 | 19 |
1,413 |
E
|
1413E
|
E. Solo mid Oracle
| 2,100 |
greedy; math; ternary search
|
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal \(a\) instant damage to him, and then heal that enemy \(b\) health points at the end of every second, for exactly \(c\) seconds, starting one second after the ability is used. That means that if the ability is used at time \(t\), the enemy's health decreases by \(a\) at time \(t\), and then increases by \(b\) at time points \(t + 1\), \(t + 2\), ..., \(t + c\) due to this ability.The ability has a cooldown of \(d\) seconds, i. e. if Meka-Naruto uses it at time moment \(t\), next time he can use it is the time \(t + d\). Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under \(k\) spells gets \(k\cdot b\) amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every \(d\) seconds). The enemy is killed if their health points become \(0\) or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
|
The first line contains an integer \(t\) (\(1\leq t\leq 10^5\)) standing for the number of testcases.Each test case is described with one line containing four numbers \(a\), \(b\), \(c\) and \(d\) (\(1\leq a, b, c, d\leq 10^6\)) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
|
For each testcase in a separate line print \(-1\) if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
|
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.In the fourth test case of the example the enemy gets: \(4\) damage (\(1\)-st spell cast) at time \(0\); \(4\) damage (\(2\)-nd spell cast) and \(3\) heal (\(1\)-st spell cast) at time \(1\) (the total of \(5\) damage to the initial health); \(4\) damage (\(3\)-nd spell cast) and \(6\) heal (\(1\)-st and \(2\)-nd spell casts) at time \(2\) (the total of \(3\) damage to the initial health); and so on. One can prove that there is no time where the enemy gets the total of \(6\) damage or more, so the answer is \(5\). Please note how the health is recalculated: for example, \(8\)-health enemy would not die at time \(1\), as if we first subtracted \(4\) damage from his health and then considered him dead, before adding \(3\) heal.In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.In the seventh test case the answer does not fit into a 32-bit integer type.
|
Input: 7 1 1 1 1 2 2 2 2 1 2 3 4 4 3 2 1 228 21 11 3 239 21 11 3 1000000 1 1000000 1 | Output: 1 2 1 5 534 -1 500000500000
|
Hard
| 3 | 1,430 | 358 | 213 | 14 |
1,621 |
H
|
1621H
|
H. Trains and Airplanes
| 3,500 |
dfs and similar; graphs; shortest paths; trees
|
Railway network of one city consists of \(n\) stations connected by \(n-1\) roads. These stations and roads forms a tree. Station \(1\) is a city center. For each road you know the time trains spend to pass this road. You can assume that trains don't spend time on stops. Let's define \(dist(v)\) as the time that trains spend to get from the station \(v\) to the station \(1\).This railway network is splitted into zones named by first \(k\) capital latin letters. The zone of the \(i\)-th station is \(z_i\). City center is in the zone A. For all other stations it is guaranteed that the first station on the road from this station to the city center is either in the same zone or in the zone with lexicographically smaller name. Any road is completely owned by the zone of the most distant end from the city center.Tourist will arrive at the airport soon and then he will go to the city center. Here's how the trip from station \(v\) to station \(1\) happends: At the moment \(0\), tourist enters the train that follows directly from the station \(v\) to the station \(1\). The trip will last for \(dist(v)\) minutes. Tourist can buy tickets for any subset of zones at any moment. Ticket for zone \(i\) costs \(pass_i\) euro. Every \(T\) minutes since the start of the trip (that is, at the moments \(T, 2T, \ldots\)) the control system will scan tourist. If at the moment of scan tourist is in the zone \(i\) without zone \(i\) ticket, he should pay \(fine_i\) euro. Formally, the zone of tourist is determined in the following way: If tourist is at the station \(1\), then he already at the city center so he shouldn't pay fine. If tourist is at the station \(u \neq 1\), then he is in the zone \(z_u\). If tourist is moving from the station \(x\) to the station \(y\) that are directly connected by road, then he is in the zone \(z_x\). Note, that tourist can pay fine multiple times in the same zone. Tourist always selects such way to buy tickets and pay fines that minimizes the total cost of trip. Let \(f(v)\) be such cost for station \(v\).Unfortunately, tourist doesn't know the current values of \(pass_i\) and \(fine_i\) for different zones and he has forgot the location of the airport. He will ask you queries of \(3\) types: \(1\) \(i\) \(c\) β the cost of ticket in zone \(i\) has changed. Now \(pass_i\) is \(c\). \(2\) \(i\) \(c\) β the cost of fine in zone \(i\) has changed. Now \(fine_i\) is \(c\). \(3\) \(u\) β solve the following problem for current values of \(pass\) and \(fine\): You are given the station \(u\). Consider all the stations \(v\) that satisfy the following conditions: \(z_v = z_u\) The station \(u\) is on the path from the station \(v\) to the station \(1\). Find the value of \(\min(f(v))\) over all such stations \(v\) with the following assumption: tourist has the ticket for the zone of station \(z_u\).
|
The first line contains the single integer \(n\) (\(2 \leq n \leq 2 \cdot 10^5\)) β the number of stations.Each of the next \(n - 1\) lines contains three integers \(v_i\), \(u_i\), \(t_i\) (\(1 \leq v_i, u_i \leq n, 1 \leq t_i \leq 10^9\)) β the ends of the \(i\)-th road and the time it takes a train to pass this road. It is guaranteed that this roads forms a tree.The next line contains the single integer \(k\) (\(1 \leq k \leq 26\)) β the number of zones.The next line contains \(n\) symbols \(z_1z_2 \ldots z_n\) β \(z_i\) is the name of the zone of the \(i\)-th station. It is guaranteed that the conditions from the second paragraph are satisfied.The next line contains \(k\) integers \(pass_1\), \(pass_2\), \(\ldots\), \(pass_k\) (\(1 \leq pass_i \leq 10^9\)) β initial costs of tickets.The next line contains \(k\) integers \(fine_1\), \(fine_2\), \(\ldots\), \(fine_k\) (\(1 \leq fine_i \leq 10^9\)) β initial fines.The next line contains the single integer \(T\) (\(1 \leq T \leq 10^9\)) β the time gap between scans of control system.The next line contains the single integer \(q\) (\(1 \leq q \leq 2 \cdot 10^5\)) β the number of queries.Next \(q\) lines contains queries as described in the statement. It is guaranteed that in the queries of the first and the second type \(i\) is a correct name of the zone (one of the first \(k\) capital latin letters) and \(1 \leq c \leq 10^9\), and in the queries of the third type \(1 \leq u \leq n\).
|
For each query of the third type print the answer to it.
|
Note, that the fine can be cheaper than the pass. The railway network from the example. Green color is used for stations and roads of zone A, blue color is used for zone B and red color is used for zone D. The integer near each road is time that trains spend to pass it. In the first query, the airport can be located near the station \(2\) or near the station \(4\). During the trip, tourist will always stay in the zone A. He already has the pass for this zone so the answer is \(0\).After the second query, the cost of the pass in the zone A has become \(10\).In the third query, the airport can be located only near the station \(3\). Optimal solution will be to buy the pass for zone A. During the first \(3\) seconds of trip tourist will be in the zone B. Then he will move to the zone A and will be scanned there on the \(4\)-th and the \(8\)-th second of his ride. Since he have a pass for this zone, he won't pay fines.After the forth query, the fine in the zone A has become \(3\).In the fifth query, the airport can be located only near the station \(7\) and \(f(7) = 6\).In the sixth query, the airport can be located near the station \(6\) or near the station \(8\). Since \(f(6)=9\) and \(f(8)=6\) the answer is \(6\).
|
Input: 8 1 2 7 2 3 4 2 4 3 4 5 1 5 6 6 4 7 10 6 8 6 4 AABABBDB 11 12 10 42 16 15 15 30 4 6 3 2 1 A 10 3 3 2 A 3 3 7 3 6 | Output: 0 10 6 6
|
Master
| 4 | 2,854 | 1,457 | 56 | 16 |
475 |
B
|
475B
|
B. Strongly Connected City
| 1,400 |
brute force; dfs and similar; graphs; implementation
|
Imagine a city with n horizontal streets crossing m vertical streets, forming an (n - 1) Γ (m - 1) grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also, traffic moves only from north to south or only from south to north in each vertical street. It is possible to enter a horizontal street from a vertical street, or vice versa, at their intersection. The mayor has received some street direction patterns. Your task is to check whether it is possible to reach any junction from any other junction in the proposed street direction pattern.
|
The first line of input contains two integers n and m, (2 β€ n, m β€ 20), denoting the number of horizontal streets and the number of vertical streets.The second line contains a string of length n, made of characters '<' and '>', denoting direction of each horizontal street. If the i-th character is equal to '<', the street is directed from east to west otherwise, the street is directed from west to east. Streets are listed in order from north to south.The third line contains a string of length m, made of characters '^' and 'v', denoting direction of each vertical street. If the i-th character is equal to '^', the street is directed from south to north, otherwise the street is directed from north to south. Streets are listed in order from west to east.
|
If the given pattern meets the mayor's criteria, print a single line containing ""YES"", otherwise print a single line containing ""NO"".
|
The figure above shows street directions in the second sample test case.
|
Input: 3 3><>v^v | Output: NO
|
Easy
| 4 | 700 | 760 | 137 | 4 |
600 |
B
|
600B
|
B. Queries about less or equal elements
| 1,300 |
binary search; data structures; sortings; two pointers
|
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
|
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the sizes of arrays a and b.The second line contains n integers β the elements of array a ( - 109 β€ ai β€ 109).The third line contains m integers β the elements of array b ( - 109 β€ bj β€ 109).
|
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
|
Input: 5 41 3 5 7 96 4 2 8 | Output: 3 2 1 4
|
Easy
| 4 | 180 | 254 | 152 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.