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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
571 |
C
|
571C
|
C. CNF 2
| 2,500 |
constructive algorithms; dfs and similar; graphs; greedy
|
'In Boolean logic, a formula is in conjunctive normal form (CNF) or clausal normal form if it is a conjunction of clauses, where a clause is a disjunction of literals' (cited from https://en.wikipedia.org/wiki/Conjunctive_normal_form)In the other words, CNF is a formula of type , where & represents a logical ""AND"" (conjunction), represents a logical ""OR"" (disjunction), and vij are some boolean variables or their negations. Each statement in brackets is called a clause, and vij are called literals.You are given a CNF containing variables x1, ..., xm and their negations. We know that each variable occurs in at most two clauses (with negation and without negation in total). Your task is to determine whether this CNF is satisfiable, that is, whether there are such values of variables where the CNF value is true. If CNF is satisfiable, then you also need to determine the values of the variables at which the CNF is true. It is guaranteed that each variable occurs at most once in each clause.
|
The first line contains integers n and m (1 ≤ n, m ≤ 2·105) — the number of clauses and the number variables, correspondingly.Next n lines contain the descriptions of each clause. The i-th line first contains first number ki (ki ≥ 1) — the number of literals in the i-th clauses. Then follow space-separated literals vij (1 ≤ |vij| ≤ m). A literal that corresponds to vij is x|vij| either with negation, if vij is negative, or without negation otherwise.
|
If CNF is not satisfiable, print a single line ""NO"" (without the quotes), otherwise print two strings: string ""YES"" (without the quotes), and then a string of m numbers zero or one — the values of variables in satisfying assignment in the order from x1 to xm.
|
In the first sample test formula is . One of possible answer is x1 = TRUE, x2 = TRUE.
|
Input: 2 22 1 -22 2 -1 | Output: YES11
|
Expert
| 4 | 1,004 | 454 | 263 | 5 |
420 |
D
|
420D
|
D. Cup Trick
| 2,200 |
data structures
|
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts: each cup contains a mark — a number from 1 to n; all marks on the cups are distinct; the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position). When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.
|
The first line contains integers n and m (1 ≤ n, m ≤ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 ≤ xi, yi ≤ n) — the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order.
|
If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i.If there are multiple correct answers, you should print the lexicographically minimum one.
|
Input: 2 12 1 | Output: 2 1
|
Hard
| 1 | 1,352 | 359 | 341 | 4 |
|
811 |
A
|
811A
|
A. Vladik and Courtesy
| 800 |
brute force; implementation
|
At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn.More formally, the guys take turns giving each other one candy more than they received in the previous turn.This continued until the moment when one of them couldn’t give the right amount of candy. Candies, which guys got from each other, they don’t consider as their own. You need to know, who is the first who can’t give the right amount of candy.
|
Single line of input data contains two space-separated integers a, b (1 ≤ a, b ≤ 109) — number of Vladik and Valera candies respectively.
|
Pring a single line ""Vladik’’ in case, if Vladik first who can’t give right amount of candy, or ""Valera’’ otherwise.
|
Illustration for first test case:Illustration for second test case:
|
Input: 1 1 | Output: Valera
|
Beginner
| 2 | 618 | 137 | 118 | 8 |
725 |
C
|
725C
|
C. Hidden Word
| 1,600 |
brute force; constructive algorithms; implementation; strings
|
Let’s define a grid to be a set of tiles with 2 rows and 13 columns. Each tile has an English letter written in it. The letters don't have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid: ABCDEFGHIJKLMNOPQRSTUVWXYZ We say that two tiles are adjacent if they share a side or a corner. In the example grid above, the tile with the letter 'A' is adjacent only to the tiles with letters 'B', 'N', and 'O'. A tile is not adjacent to itself.A sequence of tiles is called a path if each tile in the sequence is adjacent to the tile which follows it (except for the last tile in the sequence, which of course has no successor). In this example, ""ABC"" is a path, and so is ""KXWIHIJK"". ""MAB"" is not a path because 'M' is not adjacent to 'A'. A single tile can be used more than once by a path (though the tile cannot occupy two consecutive places in the path because no tile is adjacent to itself).You’re given a string s which consists of 27 upper-case English letters. Each English letter occurs at least once in s. Find a grid that contains a path whose tiles, viewed in the order that the path visits them, form the string s. If there’s no solution, print ""Impossible"" (without the quotes).
|
The only line of the input contains the string s, consisting of 27 upper-case English letters. Each English letter occurs at least once in s.
|
Output two lines, each consisting of 13 upper-case English characters, representing the rows of the grid. If there are multiple solutions, print any of them. If there is no solution print ""Impossible"".
|
Input: ABCDEFGHIJKLMNOPQRSGTUVWXYZ | Output: YXWVUTGHIJKLMZABCDEFSRQPON
|
Medium
| 4 | 1,258 | 141 | 203 | 7 |
|
1,985 |
E
|
1985E
|
E. Secret Box
| 1,200 |
brute force; combinatorics; math
|
Ntarsis has a box \(B\) with side lengths \(x\), \(y\), and \(z\). It lies in the 3D coordinate plane, extending from \((0,0,0)\) to \((x,y,z)\). Ntarsis has a secret box \(S\). He wants to choose its dimensions such that all side lengths are positive integers, and the volume of \(S\) is \(k\). He can place \(S\) somewhere within \(B\) such that: \(S\) is parallel to all axes. every corner of \(S\) lies on an integer coordinate. \(S\) is magical, so when placed at an integer location inside \(B\), it will not fall to the ground. Among all possible ways to choose the dimensions of \(S\), determine the maximum number of distinct locations he can choose to place his secret box \(S\) inside \(B\). Ntarsis does not rotate \(S\) once its side lengths are selected.
|
The first line consists of an integer \(t\), the number of test cases (\(1 \leq t \leq 2000\)). The description of the test cases follows.The first and only line of each test case contains four integers \(x, y, z\) and \(k\) (\(1 \leq x, y, z \leq 2000\), \(1 \leq k \leq x \cdot y \cdot z\)).It is guaranteed the sum of all \(x\), sum of all \(y\), and sum of all \(z\) do not exceed \(2000\) over all test cases.Note that \(k\) may not fit in a standard 32-bit integer data type.
|
For each test case, output the answer as an integer on a new line. If there is no way to select the dimensions of \(S\) so it fits in \(B\), output \(0\).
|
For the first test case, it is optimal to choose \(S\) with side lengths \(2\), \(2\), and \(2\), which has a volume of \(2 \cdot 2 \cdot 2 = 8\). It can be shown there are \(8\) ways to put \(S\) inside \(B\).The coordinate with the least \(x\), \(y\), and \(z\) values for each possible arrangement of \(S\) are: \((0, 0, 0)\) \((1, 0, 0)\) \((0, 1, 0)\) \((0, 0, 1)\) \((1, 0, 1)\) \((1, 1, 0)\) \((0, 1, 1)\) \((1, 1, 1)\) The arrangement of \(S\) with a coordinate of \((0, 0, 0)\) is depicted below: For the second test case, \(S\) with side lengths \(2\), \(3\), and \(3\) are optimal.
|
Input: 73 3 3 83 3 3 185 1 1 12 2 2 73 4 2 124 3 1 61800 1800 1800 4913000000 | Output: 8 2 5 0 4 4 1030301
|
Easy
| 3 | 768 | 481 | 154 | 19 |
1,188 |
A2
|
1188A2
|
A2. Add on a Tree: Revolution
| 2,500 |
constructive algorithms; dfs and similar; implementation; trees
|
Note that this is the second problem of the two similar problems. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.You are given a tree with \(n\) nodes. In the beginning, \(0\) is written on all edges. In one operation, you can choose any \(2\) distinct leaves \(u\), \(v\) and any integer number \(x\) and add \(x\) to values written on all edges on the simple path between \(u\) and \(v\). Note that in previous subtask \(x\) was allowed to be any real, here it has to be integer.For example, on the picture below you can see the result of applying two operations to the graph: adding \(2\) on the path from \(7\) to \(6\), and then adding \(-1\) on the path from \(4\) to \(5\). You are given some configuration of nonnegative integer pairwise different even numbers, written on the edges. For a given configuration determine if it is possible to achieve it with these operations, and, if it is possible, output the sequence of operations that leads to the given configuration. Constraints on the operations are listed in the output format section.Leave is a node of a tree of degree \(1\). Simple path is a path that doesn't contain any node twice.
|
The first line contains a single integer \(n\) (\(2 \le n \le 1000\)) — the number of nodes in a tree.Each of the next \(n-1\) lines contains three integers \(u\), \(v\), \(val\) (\(1 \le u, v \le n\), \(u \neq v\), \(0 \le val \le 10\,000\)), meaning that there is an edge between nodes \(u\) and \(v\) with \(val\) written on it. It is guaranteed that these edges form a tree. It is guaranteed that all \(val\) numbers are pairwise different and even.
|
If there aren't any sequences of operations which lead to the given configuration, output ""NO"".If it exists, output ""YES"" in the first line. In the second line output \(m\) — number of operations you are going to apply (\(0 \le m \le 10^5\)). Note that you don't have to minimize the number of the operations!In the next \(m\) lines output the operations in the following format:\(u, v, x\) (\(1 \le u, v \le n\), \(u \not = v\), \(x\) — integer, \(-10^9 \le x \le 10^9\)), where \(u, v\) — leaves, \(x\) — number we are adding. It is guaranteed that if there exists a sequence of operations producing given configuration, then there exists a sequence of operations producing given configuration, satisfying all the conditions above.
|
The configuration from the first sample is drawn below, and it is impossible to achieve. The sequence of operations from the second sample is illustrated below.
|
Input: 5 1 2 2 2 3 4 3 4 10 3 5 18 | Output: NO
|
Expert
| 4 | 1,217 | 453 | 737 | 11 |
609 |
E
|
609E
|
E. Minimum spanning tree for each edge
| 2,100 |
data structures; dfs and similar; dsu; graphs; trees
|
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).The weight of the spanning tree is the sum of weights of all edges included in spanning tree.
|
First line contains two integers n and m (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105) — the number of vertices and edges in graph.Each of the next m lines contains three integers ui, vi, wi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ wi ≤ 109) — the endpoints of the i-th edge and its weight.
|
Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge.The edges are numbered from 1 to m in order of their appearing in input.
|
Input: 5 71 2 31 3 11 4 52 3 22 5 33 4 24 5 4 | Output: 98118889
|
Hard
| 5 | 320 | 268 | 185 | 6 |
|
1,741 |
E
|
1741E
|
E. Sending a Sequence Over the Network
| 1,600 |
dp
|
The sequence \(a\) is sent over the network as follows: sequence \(a\) is split into segments (each element of the sequence belongs to exactly one segment, each segment is a group of consecutive elements of sequence); for each segment, its length is written next to it, either to the left of it or to the right of it; the resulting sequence \(b\) is sent over the network. For example, we needed to send the sequence \(a = [1, 2, 3, 1, 2, 3]\). Suppose it was split into segments as follows: \([\color{red}{1}] + [\color{blue}{2, 3, 1}] + [\color{green}{2, 3}]\). Then we could have the following sequences: \(b = [1, \color{red}{1}, 3, \color{blue}{2, 3, 1}, \color{green}{2, 3}, 2]\), \(b = [\color{red}{1}, 1, 3, \color{blue}{2, 3, 1}, 2, \color{green}{2, 3}]\), \(b = [\color{red}{1}, 1, \color{blue}{2, 3, 1}, 3, 2, \color{green}{2, 3}]\), \(b = [\color{red}{1}, 1,\color{blue}{2, 3, 1}, 3, \color{green}{2, 3}, 2]\). If a different segmentation had been used, the sent sequence might have been different.The sequence \(b\) is given. Could the sequence \(b\) be sent over the network? In other words, is there such a sequence \(a\) that converting \(a\) to send it over the network could result in a sequence \(b\)?
|
The first line of input data contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.Each test case consists of two lines.The first line of the test case contains an integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) — the size of the sequence \(b\).The second line of test case contains \(n\) integers \(b_1, b_2, \dots, b_n\) (\(1 \le b_i \le 10^9\)) — the sequence \(b\) itself.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case print on a separate line: YES if sequence \(b\) could be sent over the network, that is, if sequence \(b\) could be obtained from some sequence \(a\) to send \(a\) over the network. NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as positive response).
|
In the first case, the sequence \(b\) could be obtained from the sequence \(a = [1, 2, 3, 1, 2, 3]\) with the following partition: \([\color{red}{1}] + [\color{blue}{2, 3, 1}] + [\color{green}{2, 3}]\). The sequence \(b\): \([\color{red}{1}, 1, \color{blue}{2, 3, 1}, 3, 2, \color{green}{2, 3}]\).In the second case, the sequence \(b\) could be obtained from the sequence \(a = [12, 7, 5]\) with the following partition: \([\color{red}{12}] + [\color{green}{7, 5}]\). The sequence \(b\): \([\color{red}{12}, 1, 2, \color{green}{7, 5}]\).In the third case, the sequence \(b\) could be obtained from the sequence \(a = [7, 8, 9, 10, 3]\) with the following partition: \([\color{red}{7, 8, 9, 10, 3}]\). The sequence \(b\): \([5, \color{red}{7, 8, 9, 10, 3}]\).In the fourth case, there is no sequence \(a\) such that changing \(a\) for transmission over the network could produce a sequence \(b\).
|
Input: 791 1 2 3 1 3 2 2 3512 1 2 7 565 7 8 9 10 344 8 6 223 1104 6 2 1 9 4 9 3 4 211 | Output: YES YES YES NO YES YES NO
|
Medium
| 1 | 1,220 | 493 | 338 | 17 |
2,018 |
E1
|
2018E1
|
E1. Complex Segments (Easy Version)
| 3,300 |
binary search; data structures; divide and conquer; dsu; greedy; math; sortings
|
Ken Arai - COMPLEX⠀This is the easy version of the problem. In this version, the constraints on \(n\) and the time limit are lower. You can make hacks only if both versions of the problem are solved.A set of (closed) segments is complex if it can be partitioned into some subsets such that all the subsets have the same size; and a pair of segments intersects if and only if the two segments are in the same subset. You are given \(n\) segments \([l_1, r_1], [l_2, r_2], \ldots, [l_n, r_n]\). Find the maximum size of a complex subset of these segments.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^3\)). The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^4\)) — the number of segments.The second line of each test case contains \(n\) integers \(l_1, l_2, \ldots, l_n\) (\(1 \le l_i \le 2n\)) — the left endpoints of the segments.The third line of each test case contains \(n\) integers \(r_1, r_2, \ldots, r_n\) (\(l_i \leq r_i \le 2n\)) — the right endpoints of the segments.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^4\).
|
For each test case, output a single integer: the maximum size of a complex subset of the given segments.
|
In the first test case, all pairs of segments intersect, therefore it is optimal to form a single group containing all of the three segments.In the second test case, there is no valid partition for all of the five segments. A valid partition with four segments is the following: \(\{\{ [1, 5], [2, 4] \}, \{ [6, 9], [8, 10] \}\}\).In the third test case, it is optimal to make a single group containing all the segments except the second.
|
Input: 331 2 35 4 651 2 3 6 85 4 7 9 1053 1 4 1 57 2 6 5 10 | Output: 3 4 4
|
Master
| 7 | 553 | 665 | 104 | 20 |
342 |
E
|
342E
|
E. Xenia and Tree
| 2,400 |
data structures; divide and conquer; trees
|
Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue.The distance between two tree nodes v and u is the number of edges in the shortest path between v and u.Xenia needs to learn how to quickly execute queries of two types: paint a specified blue node in red; calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries.
|
The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree.Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi.It is guaranteed that the given graph is a tree and that all queries are correct.
|
For each second type query print the reply in a single line.
|
Input: 5 41 22 32 44 52 12 51 22 5 | Output: 032
|
Expert
| 3 | 608 | 650 | 60 | 3 |
|
2,107 |
E
|
2107E
|
E. Ain and Apple Tree
| 2,600 |
binary search; constructive algorithms; greedy; math; trees
|
If I was also hit by an apple falling from an apple tree, could I become as good at physics as Newton?To be better at physics, Ain wants to build an apple tree so that she can get hit by apples on it. Her apple tree has \(n\) nodes and is rooted at \(1\). She defines the weight of an apple tree as \(\sum \limits_{i=1}^n \sum \limits_{j=i+1}^n \text{dep}(\operatorname{lca}(i,j))\). Here, \(\text{dep}(x)\) is defined as the number of edges on the unique shortest path from node \(1\) to node \(x\). \(\operatorname{lca}(i, j)\) is defined as the unique node \(x\) with the largest value of \(\text{dep}(x)\) and which is present on both the paths \((1, i)\) and \((1, j)\).From some old books Ain reads, she knows that Newton's apple tree's weight is around \(k\), but the exact value of it is lost.As Ain's friend, you want to build an apple tree with \(n\) nodes for her, and the absolute difference between your tree's weight and \(k\) should be at most \(1\), i.e. \(|\text{weight} - k| \le 1\). Unfortunately, this is not always possible, in this case please report it.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The first line of each test case contains two numbers \(n,k\) (\(2 \le n \le 10^5,0 \le k \le 10^{15}\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, first output \(\texttt{Yes}\) if a solution exists or \(\texttt{No}\) if no solution exists. You may print each character in either case, for example \(\texttt{YES}\) and \(\texttt{yEs}\) will also be accepted.If there's at least one solution, print \(n-1\) lines and each line contains two numbers \(u,v\) \((1 \le u,v \le n)\) represents the apple tree.
|
In the first test case, we can check that the weight is \(0\). This satisfies the condition because \(k = 1\) and so the absolute difference is only \(1\).In the second test case, there exists no solution because there are no trees of \(2\) nodes with weights of either \(1, 2\) or \(3\).
|
Input: 52 12 24 05 75 5 | Output: Yes 1 2 No Yes 1 2 1 3 1 4 Yes 1 3 3 5 4 5 3 2 Yes 1 2 2 3 2 4 2 5
|
Expert
| 5 | 1,076 | 359 | 375 | 21 |
1,935 |
E
|
1935E
|
E. Distance Learning Courses in MAC
| 2,400 |
bitmasks; brute force; data structures; greedy; math
|
The New Year has arrived in the Master's Assistance Center, which means it's time to introduce a new feature!Now students are given distance learning courses, with a total of \(n\) courses available. For the \(i\)-th distance learning course, a student can receive a grade ranging from \(x_i\) to \(y_i\).However, not all courses may be available to each student. Specifically, the \(j\)-th student is only given courses with numbers from \(l_j\) to \(r_j\), meaning the distance learning courses with numbers \(l_j, l_j + 1, \ldots, r_j\).The creators of the distance learning courses have decided to determine the final grade in a special way. Let the \(j\)-th student receive grades \(c_{l_j}, c_{l_j + 1}, \ldots, c_{r_j}\) for their distance learning courses. Then their final grade will be equal to \(c_{l_j}\) \(|\) \(c_{l_j + 1}\) \(|\) \(\ldots\) \(|\) \(c_{r_j}\), where \(|\) denotes the bitwise OR operation.Since the chatbot for solving distance learning courses is broken, the students have asked for your help. For each of the \(q\) students, tell them the maximum final grade they can achieve.
|
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 2 \cdot 10^4\)) — 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 number of distance learning courses.Each of the following \(n\) lines contains two integers \(x_i\) and \(y_i\) (\(0 \le x_i \le y_i < 2^{30}\)) — the minimum and maximum grade that can be received for the \(i\)-th course.The next line contains a single integer \(q\) (\(1 \le q \le 2\cdot10^5\)) — the number of students.Each of the following \(q\) lines contains two integers \(l_j\) and \(r_j\) (\(1 \le l_j \le r_j \le n\)) — the minimum and maximum course numbers accessible to the \(j\)-th student.It is guaranteed that the sum of \(n\) over all test cases and the sum of \(q\) over all test cases do not exceed \(2\cdot10^5\).
|
For each test case, output \(q\) integers, where the \(j\)-th integer is the maximum final grade that the \(j\)-th student can achieve.
|
In the first test case: The maximum grade for the first student is \(1\): On the first distance learning course, he will receive a grade of \(1\). Therefore, the final grade is \(1\). The maximum grade for the second student is \(5\): On the first distance learning course, he will receive a grade of \(1\). On the second distance learning course, he will receive a grade of \(4\). Therefore, the final grade is \(1\) \(|\) \(4\) \(=\) \(5\). The maximum grade for the third student is \(4\): On the second distance learning course, he will receive a grade of \(4\). Therefore, the final grade is \(4\). In the second test case: The maximum grade for the first student is \(15\): On the first distance learning course, he will receive a grade of \(7\). On the second distance learning course, he will receive a grade of \(4\). On the third distance learning course, he will receive a grade of \(8\). Therefore, the final grade is \(7\) \(|\) \(4\) \(|\) \(8\) \(=\) \(15\). The maximum grade for the second student is \(11\): On the third distance learning course, he will receive a grade of \(9\). On the fourth distance learning course, he will receive a grade of \(2\). Therefore, the final grade is \(9\) \(|\) \(2\) \(=\) \(11\).
|
Input: 320 13 431 11 22 241 71 73 102 251 33 42 31 41 261 22 20 11 13 30 043 45 52 51 2 | Output: 1 5 4 15 11 15 15 7 1 3 3 3
|
Expert
| 5 | 1,109 | 928 | 135 | 19 |
727 |
F
|
727F
|
F. Polycarp's problems
| 2,300 |
binary search; dp; greedy
|
Polycarp is an experienced participant in Codehorses programming contests. Now he wants to become a problemsetter.He sent to the coordinator a set of n problems. Each problem has it's quality, the quality of the i-th problem is ai (ai can be positive, negative or equal to zero). The problems are ordered by expected difficulty, but the difficulty is not related to the quality in any way. The easiest problem has index 1, the hardest problem has index n.The coordinator's mood is equal to q now. After reading a problem, the mood changes by it's quality. It means that after the coordinator reads a problem with quality b, the value b is added to his mood. The coordinator always reads problems one by one from the easiest to the hardest, it's impossible to change the order of the problems.If after reading some problem the coordinator's mood becomes negative, he immediately stops reading and rejects the problemset.Polycarp wants to remove the minimum number of problems from his problemset to make the coordinator's mood non-negative at any moment of time. Polycarp is not sure about the current coordinator's mood, but he has m guesses ""the current coordinator's mood q = bi"".For each of m guesses, find the minimum number of problems Polycarp needs to remove so that the coordinator's mood will always be greater or equal to 0 while he reads problems from the easiest of the remaining problems to the hardest.
|
The first line of input contains two integers n and m (1 ≤ n ≤ 750, 1 ≤ m ≤ 200 000) — the number of problems in the problemset and the number of guesses about the current coordinator's mood.The second line of input contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the qualities of the problems in order of increasing difficulty.The third line of input contains m integers b1, b2, ..., bm (0 ≤ bi ≤ 1015) — the guesses of the current coordinator's mood q.
|
Print m lines, in i-th line print single integer — the answer to the problem with q = bi.
|
Input: 6 38 -5 -4 1 -7 40 7 3 | Output: 201
|
Expert
| 3 | 1,418 | 464 | 89 | 7 |
|
733 |
D
|
733D
|
D. Kostya the Sculptor
| 1,600 |
data structures; hashing
|
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
|
The first line contains the integer n (1 ≤ n ≤ 105).n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≤ ai, bi, ci ≤ 109) — the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
|
In the first line print k (1 ≤ k ≤ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to n — the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data.You can print the stones in arbitrary order. If there are several answers print any of them.
|
In the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
|
Input: 65 5 53 2 41 4 12 1 33 2 43 3 4 | Output: 11
|
Medium
| 2 | 929 | 303 | 380 | 7 |
1,627 |
E
|
1627E
|
E. Not Escaping
| 2,200 |
data structures; dp; implementation; shortest paths; two pointers
|
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of \(n\) floors, each with \(m\) rooms each. Let \((i, j)\) represent the \(j\)-th room on the \(i\)-th floor. Additionally, there are \(k\) ladders installed. The \(i\)-th ladder allows Ram to travel from \((a_i, b_i)\) to \((c_i, d_i)\), but not in the other direction. Ram also gains \(h_i\) health points if he uses the ladder \(i\). It is guaranteed \(a_i < c_i\) for all ladders.If Ram is on the \(i\)-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from \((i, j)\) to \((i, k)\), he loses \(|j-k| \cdot x_i\) health points.Ram enters the building at \((1, 1)\) while his helicopter is waiting at \((n, m)\). What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output ""NO ESCAPE"" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
|
The first line of input contains \(t\) (\(1 \leq t \leq 5 \cdot 10^4\)) — the number of test cases.The first line of each test case consists of \(3\) integers \(n, m, k\) (\(2 \leq n, m \leq 10^5\); \(1 \leq k \leq 10^5\)) — the number of floors, the number of rooms on each floor and the number of ladders respectively.The second line of a test case consists of \(n\) integers \(x_1, x_2, \dots, x_n\) (\(1 \leq x_i \leq 10^6\)).The next \(k\) lines describe the ladders. Ladder \(i\) is denoted by \(a_i, b_i, c_i, d_i, h_i\) (\(1 \leq a_i < c_i \leq n\); \(1 \leq b_i, d_i \leq m\); \(1 \leq h_i \leq 10^6\)) — the rooms it connects and the health points gained from using it.It is guaranteed \(a_i < c_i\) for all ladders and there is at most one ladder between any 2 rooms in the building.The sum of \(n\), the sum of \(m\), and the sum of \(k\) over all test cases do not exceed \(10^5\).
|
Output the minimum health Ram loses on the optimal path from \((1, 1)\) to \((n, m)\). If Ram cannot escape the clutches of Raghav regardless of the path he takes, output ""NO ESCAPE"" (all uppercase, without quotes).
|
The figure for the first test case is in the statement. There are only \(2\) possible paths to \((n, m)\): Ram travels to \((1, 3)\), takes the ladder to \((3, 3)\), travels to \((3, 2)\), takes the ladder to \((5, 1)\), travels to \((5, 3)\) where he finally escapes via helicopter. The health lost would be $$$\( \begin{align*} &\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &= 16. \end{align*} \)\( Ram travels to \)(1, 3)\(, takes the ladder to \)(3, 3)\(, travels to \)(3, 1)\(, takes the ladder to \)(5, 2)\(, travels to \)(5, 3)\( where he finally escapes via helicopter. The health lost would be \)\( \begin{align*} &\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &= 21. \end{align*} \)\( Therefore, the minimum health lost would be \)16\(.In the second test case, there is no path to \)(n, m)\(.In the third case case, Ram travels to \)(1, 3)\( and takes the only ladder to \)(5, 3)\(. He loses \)5 \cdot 2\( health points and gains \)h_1 = 100\( health points. Therefore the total loss is \)10-100=-90$$$ (negative implies he gains health after the path).
|
Input: 45 3 35 17 8 1 41 3 3 3 43 1 5 2 53 2 5 1 66 3 35 17 8 1 4 21 3 3 3 43 1 5 2 53 2 5 1 65 3 15 17 8 1 41 3 5 3 1005 5 53 2 3 7 53 5 4 2 12 2 5 4 54 4 5 2 31 2 4 2 23 3 5 2 4 | Output: 16 NO ESCAPE -90 27
|
Hard
| 5 | 1,197 | 894 | 217 | 16 |
2,026 |
F
|
2026F
|
F. Bermart Ice Cream
| 2,700 |
data structures; dfs and similar; divide and conquer; dp; implementation; trees
|
In the Bermart chain of stores, a variety of ice cream is sold. Each type of ice cream has two parameters: price and tastiness.Initially, there is one store numbered \(1\), which sells nothing. You have to process \(q\) queries of the following types: \(1~x\) — a new store opens, that sells the same types of ice cream as store \(x\). It receives the minimum available positive index. The order of the types of ice cream in the new store is the same as in store \(x\). \(2~x~p~t\) — a type of ice cream with price \(p\) and tastiness \(t\) becomes available in store \(x\). \(3~x\) — a type of ice cream that was available the longest (appeared the earliest) in store \(x\) is removed. \(4~x~p\) — for store \(x\), find the maximum total tastiness of a subset of types of ice cream that are sold there, such that the total price does not exceed \(p\) (each type can be used in the subset no more than once).
|
The first line contains a single integer \(q\) (\(1 \le q \le 3 \cdot 10^4\)) — the number of queries.Each of the following \(q\) lines contains a query in the format described in the statement: \(1~x\); \(2~x~p~t\) (\(1 \le p, t \le 2000\)); \(3~x\); \(4~x~p\) (\(1 \le p \le 2000\)). Additional constraints on the input data: \(x\) in each query does not exceed the current number of stores (that is, \(1\) plus the number of type \(1\) queries); query type \(3\) is not applied to a store that has no types of ice cream; there is at least one query of type \(4\).
|
For each query of type \(4\), output a single integer — for store \(x\), find the maximum total tastiness of a subset of types of ice cream that are sold there, such that the total price does not exceed \(p\) (each type can be used in the subset no more than once).
|
Input: 122 1 5 72 1 3 44 1 44 1 84 1 21 12 2 4 104 1 94 2 93 14 1 94 2 9 | Output: 4 11 0 11 17 4 17
|
Master
| 6 | 908 | 566 | 265 | 20 |
|
1,598 |
E
|
1598E
|
E. Staircases
| 2,100 |
brute force; combinatorics; data structures; dfs and similar; dp; implementation; math
|
You are given a matrix, consisting of \(n\) rows and \(m\) columns. The rows are numbered top to bottom, the columns are numbered left to right.Each cell of the matrix can be either free or locked.Let's call a path in the matrix a staircase if it: starts and ends in the free cell; visits only free cells; has one of the two following structures: the second cell is \(1\) to the right from the first one, the third cell is \(1\) to the bottom from the second one, the fourth cell is \(1\) to the right from the third one, and so on; the second cell is \(1\) to the bottom from the first one, the third cell is \(1\) to the right from the second one, the fourth cell is \(1\) to the bottom from the third one, and so on. In particular, a path, consisting of a single cell, is considered to be a staircase.Here are some examples of staircases: Initially all the cells of the matrix are free.You have to process \(q\) queries, each of them flips the state of a single cell. So, if a cell is currently free, it makes it locked, and if a cell is currently locked, it makes it free.Print the number of different staircases after each query. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.
|
The first line contains three integers \(n\), \(m\) and \(q\) (\(1 \le n, m \le 1000\); \(1 \le q \le 10^4\)) — the sizes of the matrix and the number of queries.Each of the next \(q\) lines contains two integers \(x\) and \(y\) (\(1 \le x \le n\); \(1 \le y \le m\)) — the description of each query.
|
Print \(q\) integers — the \(i\)-th value should be equal to the number of different staircases after \(i\) queries. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.
|
Input: 2 2 8 1 1 1 1 1 1 2 2 1 1 1 2 2 1 1 1 | Output: 5 10 5 2 5 3 1 0
|
Hard
| 7 | 1,265 | 300 | 247 | 15 |
|
1,801 |
G
|
1801G
|
G. A task for substrings
| 3,400 |
data structures; string suffix structures; strings
|
Philip is very fond of tasks on the lines. He had already solved all the problems known to him, but this was not enough for him. Therefore, Philip decided to come up with his own task.To do this, he took the string \(t\) and a set of \(n\) strings \(s_1\), \(s_2\), \(s_3\), ..., \(s_n\). Philip has \(m\) queries, in the \(i\)th of them, Philip wants to take a substring of the string \(t\) from \(l_i\)th to \(r_i\)th character, and count the number of its substrings that match some string from the set. More formally, Philip wants to count the number of pairs of positions \(a\), \(b\), such that \(l_i \le a \le b \le r_i\), and the substring of the string \(t\) from \(a\)th to \(b\)th character coincides with some string \(s_j\) from the set.A substring of the string \(t\) from \(a\)th to \(b\)th character is a string obtained from \(t\) by removing the \(a - 1\) character from the beginning and \(|t| - b\) characters from the end, where \(|t|\) denotes the length of the string \(t\).Philip has already solved this problem, but can you?
|
The first line contains two positive integers \(n\) and \(m\) (\(1 \le n, m \le 500\,000\)) — the number of rows in the set and the number of queries.The second line contains a single string \(t\) consisting of lowercase letters of the English alphabet (\(1 \le |t| \le 5 \cdot 10^6\)).The following \(n\) lines describe the strings from the set. In the \(i\)th of them, a single string \(s_i\) is given, consisting of lowercase letters of the English alphabet. Denote by \(S\) the total length of all strings from the set. It is guaranteed that \(S \le 10^6\), as well as that all strings of \(s_i\) are different.In the following lines, queries are entered. The \(i\)th of them contains two positive integers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le |t|\)) — the left and right border of the substring \(t\) from the \(i\)-th query.
|
In a single line, print \(m\) integers, \(i\)th of them should be equal to the answers to the \(i\)th query.
|
In the first example, the first query requires the entire string to count the number of substrings that are included in the set. The substrings \([1, 3]\) and \([4, 6]\) coincide with the string ""aba"". The substrings match with the string ""a"" \([1, 1]\), \([3, 3]\), \([5, 5]\), \([7, 7]\). The substring \([3, 4]\) matches the string ""ac"". In total, it turns out that 7 substrings of the string ""abacaba"" match the strings from the set.In the second query, a substring from position 1 to position 3 is taken from the source string, this is the string ""aba"". The string ""aba"" enters it 1 time, the string ""a"" enters it 2 times and the string ""ac"" does not enter it once as a substring. In the third query, a substring from the 2nd to the 7th position is taken from the source string, this is the string ""bacaba"". The string ""aba"" is included in it 1 time, the string ""a"" is included 3 times and the string ""ac"" is included 1 time as a substring.
|
Input: 3 5 abacaba aba a ac 1 7 1 3 2 7 2 5 4 5 | Output: 7 3 5 3 1
|
Master
| 3 | 1,049 | 838 | 108 | 18 |
1,548 |
D2
|
1548D2
|
D2. Gregor and the Odd Cows (Hard)
| 3,300 |
brute force; geometry; math; number theory
|
This is the hard version of the problem. The only difference from the easy version is that in this version the coordinates can be both odd and even.There are \(n\) fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line.There are an infinite number of cows on the plane, one at every point with integer coordinates.Gregor is a member of the Illuminati, and wants to build a triangular fence, connecting \(3\) distinct existing fence posts. A cow strictly inside the fence is said to be enclosed. If there are an odd number of enclosed cows and the area of the fence is an integer, the fence is said to be interesting.Find the number of interesting fences.
|
The first line contains the integer \(n\) (\(3 \le n \le 6000\)), the number of fence posts which Gregor can choose to form the vertices of a fence.Each of the next \(n\) line contains two integers \(x\) and \(y\) (\(0 \le x,y \le 10^7\), where \((x,y)\) is the coordinate of a fence post. All fence posts lie at distinct coordinates. No three fence posts are on the same line.
|
Print a single integer, the number of interesting fences. Two fences are considered different if they are constructed with a different set of three fence posts.
|
In the first example, there is only \(1\) fence. That fence is interesting since its area is \(4\) and there is \(1\) enclosed cow, marked in red. In the second example, there are \(4\) possible fences. Only one of them is interesting however. That fence has an area of \(8\) and \(5\) enclosed cows.
|
Input: 3 0 0 2 0 0 4 | Output: 1
|
Master
| 4 | 711 | 377 | 160 | 15 |
1,032 |
E
|
1032E
|
E. The Unbearable Lightness of Weights
| 2,100 |
dp; math
|
You have a set of \(n\) weights. You know that their masses are \(a_1\), \(a_2\), ..., \(a_n\) grams, but you don't know which of them has which mass. You can't distinguish the weights.However, your friend does know the mass of each weight. You can ask your friend to give you exactly \(k\) weights with the total mass \(m\) (both parameters \(k\) and \(m\) are chosen by you), and your friend will point to any valid subset of weights, if it is possible.You are allowed to make this query only once. Find the maximum possible number of weights you can reveal after this query.
|
The first line contains a single integer \(n\) (\(1 \le n \le 100\)) — the number of weights.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 100\)) — the masses of the weights.
|
Print the maximum number of weights you can learn the masses for after making a single query.
|
In the first example we can ask for a subset of two weights with total mass being equal to \(4\), and the only option is to get \(\{2, 2\}\).Another way to obtain the same result is to ask for a subset of two weights with the total mass of \(5\) and get \(\{1, 4\}\). It is easy to see that the two remaining weights have mass of \(2\) grams each.In the second example we can ask for a subset of two weights with total mass being \(8\), and the only answer is \(\{4, 4\}\). We can prove it is not possible to learn masses for three weights in one query, but we won't put the proof here.
|
Input: 4 1 4 2 2 | Output: 2
|
Hard
| 2 | 577 | 211 | 93 | 10 |
1,611 |
B
|
1611B
|
B. Team Composition: Programmers and Mathematicians
| 800 |
binary search; constructive algorithms; math
|
The All-Berland Team Programming Contest will take place very soon. This year, teams of four are allowed to participate.There are \(a\) programmers and \(b\) mathematicians at Berland State University. How many maximum teams can be made if: each team must consist of exactly \(4\) students, teams of \(4\) mathematicians or \(4\) programmers are unlikely to perform well, so the decision was made not to compose such teams. Thus, each team must have at least one programmer and at least one mathematician.Print the required maximum number of teams. Each person can be a member of no more than one team.
|
The first line contains an integer \(t\) (\(1 \le t \le 10^4\)) —the number of test cases.This is followed by descriptions of \(t\) sets, one per line. Each set is given by two integers \(a\) and \(b\) (\(0 \le a,b \le 10^9\)).
|
Print \(t\) lines. Each line must contain the answer to the corresponding set of input data — the required maximum number of teams.
|
In the first test case of the example, two teams can be composed. One way to compose two teams is to compose two teams of \(2\) programmers and \(2\) mathematicians.In the second test case of the example, only one team can be composed: \(3\) programmers and \(1\) mathematician in the team.
|
Input: 6 5 5 10 1 2 3 0 0 17 2 1000000000 1000000000 | Output: 2 1 1 0 2 500000000
|
Beginner
| 3 | 602 | 227 | 131 | 16 |
548 |
B
|
548B
|
B. Mike and Fun
| 1,400 |
brute force; dp; greedy; implementation
|
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
|
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000).The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes).The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
|
After each round, print the current score of the bears.
|
Input: 5 4 50 1 1 01 0 0 10 1 1 01 0 0 10 0 0 01 11 41 14 24 3 | Output: 34334
|
Easy
| 4 | 914 | 454 | 55 | 5 |
|
543 |
B
|
543B
|
B. Destroying Roads
| 2,100 |
constructive algorithms; graphs; shortest paths
|
In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads.You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours.Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1.
|
The first line contains two integers n, m (1 ≤ n ≤ 3000, ) — the number of cities and roads in the country, respectively. Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them.The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1 ≤ si, ti ≤ n, 0 ≤ li ≤ n).
|
Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1.
|
Input: 5 41 22 33 44 51 3 23 5 2 | Output: 0
|
Hard
| 3 | 761 | 538 | 108 | 5 |
|
2,023 |
A
|
2023A
|
A. Concatenation of Arrays
| 1,300 |
constructive algorithms; greedy; math; sortings
|
You are given \(n\) arrays \(a_1\), \(\ldots\), \(a_n\). The length of each array is two. Thus, \(a_i = [a_{i, 1}, a_{i, 2}]\). You need to concatenate the arrays into a single array of length \(2n\) such that the number of inversions\(^{\dagger}\) in the resulting array is minimized. Note that you do not need to count the actual number of inversions.More formally, you need to choose a permutation\(^{\ddagger}\) \(p\) of length \(n\), so that the array \(b = [a_{p_1,1}, a_{p_1,2}, a_{p_2, 1}, a_{p_2, 2}, \ldots, a_{p_n,1}, a_{p_n,2}]\) contains as few inversions as possible.\(^{\dagger}\)The number of inversions in an array \(c\) is the number of pairs of indices \(i\) and \(j\) such that \(i < j\) and \(c_i > c_j\).\(^{\ddagger}\)A permutation of length \(n\) 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 consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^5\)) — the number of arrays.Each of the following \(n\) lines contains two integers \(a_{i,1}\) and \(a_{i,2}\) (\(1 \le a_{i,j} \le 10^9\)) — the elements of the \(i\)-th array.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
|
For each test case, output \(2n\) integers — the elements of the array you obtained. If there are multiple solutions, output any of them.
|
In the first test case, we concatenated the arrays in the order \(2, 1\). Let's consider the inversions in the resulting array \(b = [2, 3, 1, 4]\): \(i = 1\), \(j = 3\), since \(b_1 = 2 > 1 = b_3\); \(i = 2\), \(j = 3\), since \(b_2 = 3 > 1 = b_3\). Thus, the number of inversions is \(2\). It can be proven that this is the minimum possible number of inversions.In the second test case, we concatenated the arrays in the order \(3, 1, 2\). Let's consider the inversions in the resulting array \(b = [2, 1, 3, 2, 4, 3]\): \(i = 1\), \(j = 2\), since \(b_1 = 2 > 1 = b_2\); \(i = 3\), \(j = 4\), since \(b_3 = 3 > 2 = b_4\); \(i = 5\), \(j = 6\), since \(b_5 = 4 > 3 = b_6\). Thus, the number of inversions is \(3\). It can be proven that this is the minimum possible number of inversions.In the third test case, we concatenated the arrays in the order \(4, 2, 1, 5, 3\).
|
Input: 421 42 333 24 32 155 102 39 64 18 7110 20 | Output: 2 3 1 4 2 1 3 2 4 3 4 1 2 3 5 10 8 7 9 6 10 20
|
Easy
| 4 | 1,065 | 528 | 137 | 20 |
1,356 |
A5
|
1356A5
|
A5. Distinguish Z from -Z
| 0 |
*special
|
You are given an operation that implements a single-qubit unitary transformation: either the Z gate or the -Z gate (i.e., the \(-|0\rangle\langle0| + |1\rangle\langle1|\) gate: \((-Z)(\alpha|0\rangle + \beta|1\rangle) = -\alpha|0\rangle + \beta|1\rangle\)). The operation will have Adjoint and Controlled variants defined.Your task is to perform necessary operations and measurements to figure out which unitary it was and to return 0 if it was the Z gate or 1 if it was the -Z gate. You are allowed to apply the given operation and its adjoint/controlled variants exactly once.You have to implement an operation which takes a single-qubit operation as an input and returns an integer. Your code should have the following signature:namespace Solution { open Microsoft.Quantum.Intrinsic; operation Solve (unitary : (Qubit => Unit is Adj+Ctl)) : Int { // your code here }}
|
Beginner
| 1 | 870 | 0 | 0 | 13 |
||||
1,637 |
B
|
1637B
|
B. MEX and Array
| 1,100 |
brute force; dp; greedy; math
|
Let there be an array \(b_1, b_2, \ldots, b_k\). Let there be a partition of this array into segments \([l_1; r_1], [l_2; r_2], \ldots, [l_c; r_c]\), where \(l_1 = 1\), \(r_c = k\), and for any \(2 \leq i \leq c\) holds that \(r_{i-1} + 1 = l_i\). In other words, each element of the array belongs to exactly one segment.Let's define the cost of a partition as $$$\(c + \sum_{i = 1}^{c} \operatorname{mex}(\{b_{l_i}, b_{l_i + 1}, \ldots, b_{r_i}\}),\)\( where \)\operatorname{mex}\( of a set of numbers \)S\( is the smallest non-negative integer that does not occur in the set \)S\(. In other words, the cost of a partition is the number of segments plus the sum of MEX over all segments. Let's define the value of an array \)b_1, b_2, \ldots, b_k\( as the maximum possible cost over all partitions of this array.You are given an array \)a\( of size \)n\(. Find the sum of values of all its subsegments.An array \)x\( is a subsegment of an array \)y\( if \)x\( can be obtained from \)y$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
|
The input contains several test cases. The first line contains one integer \(t\) (\(1 \leq t \leq 30\)) — the number of test cases.The first line for each test case contains one integer \(n\) (\(1 \leq n \leq 100\)) — the length of the array.The second line contains a sequence of integers \(a_1, a_2, \ldots, a_n\) (\(0 \leq a_i \leq 10^9\)) — the array elements.It is guaranteed that the sum of the values \(n\) over all test cases does not exceed \(100\).
|
For each test case print a single integer — the answer to the problem.
|
In the second test case: The best partition for the subsegment \([2, 0, 1]\): \([2], [0, 1]\). The cost of this partition equals to \(2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0, 1\}) = 2 + 0 + 2 = 4\). The best partition for the subsegment \([2, 0]\): \([2], [0]\). The cost of this partition equals to \(2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0\}) = 2 + 0 + 1 = 3\) The best partition for the subsegment \([2]\): \([2]\). The cost of this partition equals to \(1 + \operatorname{mex}(\{2\}) = 1 + 0 = 1\). The best partition for the subsegment \([0, 1]\): \([0, 1]\). The cost of this partition equals to \(1 + \operatorname{mex}(\{0, 1\}) = 1 + 2 = 3\). The best partition for the subsegment \([0]\): \([0]\). The cost of this partition equals to \(1 + \operatorname{mex}(\{0\}) = 1 + 1 = 2\). The best partition for the subsegment \([1]\): \([1]\). The cost of this partition equals to \(1 + \operatorname{mex}(\{1\}) = 1 + 0 = 1\). The sum of values over all subsegments equals to \(4 + 3 + 1 + 3 + 2 + 1 = 14\).
|
Input: 421 232 0 142 0 5 150 1 1 0 1 | Output: 4 14 26 48
|
Easy
| 4 | 1,122 | 458 | 70 | 16 |
309 |
B
|
309B
|
B. Context Advertising
| 2,100 |
dp; two pointers
|
Advertising has become part of our routine. And now, in the era of progressive technologies, we need your ideas to make advertising better!In this problem we'll look at a simplified version of context advertising. You've got a text, consisting of exactly n words. A standard advertising banner has exactly r lines, each line can contain at most c characters. The potential customer always likes it when they can see lots of advertising, so you should determine which maximum number of consecutive words from the text can be written on the banner. Single words in one line of the banner should be separated by spaces. You are allowed to insert more than one space at once. Note that you are not allowed to break the words, that is, each word in the text must occupy exactly one line in the banner. Besides, you cannot change the word order, that is, if you read the banner text consecutively, from top to bottom and from left to right, you should get some consecutive part of the advertisement text.More formally, the statement can be written like that. Let's say that all words are indexed from 1 to n in the order in which they occur in the advertisement text. Then you have to choose all words, starting from some i-th one and ending with some j-th one (1 ≤ i ≤ j ≤ n), so that all of them could be written on the banner. There must be as many words as possible. See the samples for clarifications.
|
The first input line contains three integers n, r, c (1 ≤ n, r, c ≤ 106; r × c ≤ 106). The next line contains a text, consisting of n words. The words consist only of lowercase English letters and are not empty. The words in the lines are separated by single spaces. The total number of characters in all words doesn't exceed 5·106.
|
Print at most r lines, in each line print at most c characters — the optimal advertisement banner. If there are multiple advertisement banners, print any of them. Note that some lines of the banner can be empty. You are allowed not to print such lines.
|
Input: 9 4 12this is a sample text for croc final round | Output: this is asample textfor crocfinal round
|
Hard
| 2 | 1,400 | 332 | 252 | 3 |
|
1,017 |
C
|
1017C
|
C. The Phone Number
| 1,600 |
constructive algorithms; greedy
|
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of \(n\) can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of \(n\) integers is called a permutation if it contains all integers from \(1\) to \(n\) exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence \(a_{i_1}, a_{i_2}, \ldots, a_{i_k}\) where \(1\leq i_1 < i_2 < \ldots < i_k\leq n\) is called increasing if \(a_{i_1} < a_{i_2} < a_{i_3} < \ldots < a_{i_k}\). If \(a_{i_1} > a_{i_2} > a_{i_3} > \ldots > a_{i_k}\), a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation \([6, 4, 1, 7, 2, 3, 5]\), LIS of this permutation will be \([1, 2, 3, 5]\), so the length of LIS is equal to \(4\). LDS can be \([6, 4, 1]\), \([6, 4, 2]\), or \([6, 4, 3]\), so the length of LDS is \(3\).Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
|
The only line contains one integer \(n\) (\(1 \le n \le 10^5\)) — the length of permutation that you need to build.
|
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
|
In the first sample, you can build a permutation \([3, 4, 1, 2]\). LIS is \([3, 4]\) (or \([1, 2]\)), so the length of LIS is equal to \(2\). LDS can be ony of \([3, 1]\), \([4, 2]\), \([3, 2]\), or \([4, 1]\). The length of LDS is also equal to \(2\). The sum is equal to \(4\). Note that \([3, 4, 1, 2]\) is not the only permutation that is valid.In the second sample, you can build a permutation \([2, 1]\). LIS is \([1]\) (or \([2]\)), so the length of LIS is equal to \(1\). LDS is \([2, 1]\), so the length of LDS is equal to \(2\). The sum is equal to \(3\). Note that permutation \([1, 2]\) is also valid.
|
Input: 4 | Output: 3 4 1 2
|
Medium
| 2 | 1,354 | 115 | 113 | 10 |
1,496 |
A
|
1496A
|
A. Split it!
| 900 |
brute force; constructive algorithms; greedy; strings
|
Kawashiro Nitori is a girl who loves competitive programming.One day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem.Given a string \(s\) and a parameter \(k\), you need to check if there exist \(k+1\) non-empty strings \(a_1,a_2...,a_{k+1}\), such that $$$\(s=a_1+a_2+\ldots +a_k+a_{k+1}+R(a_k)+R(a_{k-1})+\ldots+R(a_{1}).\)\( Here \)+\( represents concatenation. We define \)R(x)\( as a reversed string \)x\(. For example \)R(abcd) = dcba\(. Note that in the formula above the part \)R(a_{k+1})$$$ is intentionally skipped.
|
The input consists of multiple test cases. The first line contains a single integer \(t\) (\(1\le t\le 100\)) — the number of test cases. The description of the test cases follows.The first line of each test case description contains two integers \(n\), \(k\) (\(1\le n\le 100\), \(0\le k\le \lfloor \frac{n}{2} \rfloor\)) — the length of the string \(s\) and the parameter \(k\).The second line of each test case description contains a single string \(s\) of length \(n\), consisting of lowercase English letters.
|
For each test case, print ""YES"" (without quotes), if it is possible to find \(a_1,a_2,\ldots,a_{k+1}\), and ""NO"" (without quotes) otherwise.You can print letters in any case (upper or lower).
|
In the first test case, one possible solution is \(a_1=qw\) and \(a_2=q\).In the third test case, one possible solution is \(a_1=i\) and \(a_2=o\).In the fifth test case, one possible solution is \(a_1=dokidokiliteratureclub\).
|
Input: 7 5 1 qwqwq 2 1 ab 3 1 ioi 4 2 icpc 22 0 dokidokiliteratureclub 19 8 imteamshanghaialice 6 3 aaaaaa | Output: YES NO YES NO YES NO NO
|
Beginner
| 4 | 576 | 514 | 195 | 14 |
1,275 |
E3
|
1275E3
|
E3. Контрольная сумма
| 0 |
*special
|
Данные пользователей ВКонтакте хранятся на десятках тысяч серверов. Для того, чтобы можно было определять ошибки при записи данных на диск, на диск регулярно записываются текущие контрольные суммы CRC32 (Wiki, IEEE 802-3). Благодаря этому, при чтении данных можно заново вычислить контрольную сумму и проверить, что данные и контрольная сумма записаны корректно. Разумеется, проверки на совпадение контрольной суммы встроены в большинство сервисов ВКонтакте. Но как-то раз оказалось, что в одном сегменте данных нужно изменить значение четырех последовательных байт на новое — нужно заменить значения последовательности \(a_i, a_{i+1}, a_{i+2}, a_{i+3}\) на \(x_0, x_1, x_2, x_3\). При этом, нужно чтобы значение контрольной суммы CRC32 осталось прежним. Конечно, при изменении последовательности ее контрольная сумма изменится, поэтому кроме изменения этих четырех байт на новое значение, были выбраны четыре байта \(a_{j}, a_{j+1}, a_{j+2}, a_{j+3}\), которым можно назначить любое значение. Ваша задача выбрать им новые значения так, чтобы CRC32 данной последовательности не изменился, или определить, что это невозможно. Поскольку изменение данных — операция серьезная, перед самим изменением нужно определить, как изменится последовательность для \(q\) независимых тестовых случаев.
|
В первой строке дано два целых числа \(n\) и \(q\) — количество байт в файле и количество запросов, для которых нужно решить задачу (\(8 \le n \le 2 \cdot 10^5\); \(1 \le q \le 10^5\)).Во второй строке дано \(n\) чисел \(a_0, a_1, \ldots, a_{n-1}\) — содержимое файла в байтах (\(0 \le a_i \le 255\)).В следующих \(q\) строках дано по шесть чисел \(i, j, x_0, x_1, x_2, x_3\) — позиция \(i\), начиная с которой нужно заменить четыре байта на \(x_0, x_1, x_2, x_3\), и позиция \(j\), начиная с которой можно менять четыре байта как угодно (\(0 \le i, j \le n-4\); \(0 \le x_0, x_1, x_2, x_3 \le 255\)). Гарантируется, что отрезки \([i; i+3]\) и \([j; j+3]\) не пересекаются.
|
Для каждого запроса выведите четыре целых числа \(z_0, z_1, z_2, z_3\), на которые нужно заменить четыре байта с номерами \(j, j+1, j+2, j+3\), чтобы crc32 не изменился. Обратите внимание, что все запросы независимы, и на самом деле последовательность не изменяется.Если существует несколько решений, выведите любое, а если для данного запроса валидного решения нет, выведите No solution.
|
CRC32 байтовой последовательности из первого примера (1 2 3 4 5 6 7 8) равен 3fca88c5, CRC32 измененной последовательности (0 0 0 0 212 34 127 159) так же равен 3fca88c5. Стандартная утилита crc32 из большинства дистрибутивов линукса должна посчитать от них данную контрольную сумму.CRC32 последовательности из второго примера равен ecbb4b55.
|
Input: 8 1 1 2 3 4 5 6 7 8 0 4 0 0 0 0 | Output: 212 34 127 159
|
Beginner
| 1 | 1,287 | 673 | 388 | 12 |
361 |
B
|
361B
|
B. Levko and Permutation
| 1,200 |
constructive algorithms; math; number theory
|
Levko loves permutations very much. A permutation of length n is a sequence of distinct positive integers, each is at most n.Let’s assume that value gcd(a, b) shows the greatest common divisor of numbers a and b. Levko assumes that element pi of permutation p1, p2, ... , pn is good if gcd(i, pi) > 1. Levko considers a permutation beautiful, if it has exactly k good elements. Unfortunately, he doesn’t know any beautiful permutation. Your task is to help him to find at least one of them.
|
The single line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ n).
|
In a single line print either any beautiful permutation or -1, if such permutation doesn’t exist.If there are multiple suitable permutations, you are allowed to print any of them.
|
In the first sample elements 4 and 3 are good because gcd(2, 4) = 2 > 1 and gcd(3, 3) = 3 > 1. Elements 2 and 1 are not good because gcd(1, 2) = 1 and gcd(4, 1) = 1. As there are exactly 2 good elements, the permutation is beautiful.The second sample has no beautiful permutations.
|
Input: 4 2 | Output: 2 4 3 1
|
Easy
| 3 | 490 | 71 | 179 | 3 |
892 |
A
|
892A
|
A. Greed
| 900 |
greedy; implementation
|
Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai ≤ bi).Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!
|
The first line of the input contains one integer n (2 ≤ n ≤ 100 000) — number of cola cans.The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — volume of remaining cola in cans.The third line contains n space-separated integers that b1, b2, ..., bn (ai ≤ bi ≤ 109) — capacities of the cans.
|
Print ""YES"" (without quotes) if it is possible to pour all remaining cola in 2 cans. Otherwise print ""NO"" (without quotes).You can print each letter in any case (upper or lower).
|
In the first sample, there are already 2 cans, so the answer is ""YES"".
|
Input: 23 53 6 | Output: YES
|
Beginner
| 2 | 223 | 322 | 182 | 8 |
1,677 |
B
|
1677B
|
B. Tokitsukaze and Meeting
| 1,700 |
data structures; implementation; math
|
Tokitsukaze is arranging a meeting. There are \(n\) rows and \(m\) columns of seats in the meeting hall.There are exactly \(n \cdot m\) students attending the meeting, including several naughty students and several serious students. The students are numerated from \(1\) to \(n\cdot m\). The students will enter the meeting hall in order. When the \(i\)-th student enters the meeting hall, he will sit in the \(1\)-st column of the \(1\)-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the \(j\)-th (\(1\leq j \leq m-1\)) column of the \(i\)-th row will move to the \((j+1)\)-th column of the \(i\)-th row, and the student sitting in \(m\)-th column of the \(i\)-th row will move to the \(1\)-st column of the \((i+1)\)-th row.For example, there is a meeting hall with \(2\) rows and \(2\) columns of seats shown as below: There will be \(4\) students entering the meeting hall in order, represented as a binary string ""1100"", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the \(i\)-th student enters the meeting hall, for all \(i\).
|
The first contains a single positive integer \(t\) (\(1 \leq t \leq 10\,000\)) — the number of test cases.For each test case, the first line contains two integers \(n\), \(m\) (\(1 \leq n,m \leq 10^6\); \(1 \leq n \cdot m \leq 10^6\)), denoting there are \(n\) rows and \(m\) columns of seats in the meeting hall.The second line contains a binary string \(s\) of length \(n \cdot m\), consisting only of zeros and ones. If \(s_i\) equal to '0' represents the \(i\)-th student is a naughty student, and \(s_i\) equal to '1' represents the \(i\)-th student is a serious student.It is guaranteed that the sum of \(n \cdot m\) over all test cases does not exceed \(10^6\).
|
For each test case, print a single line with \(n \cdot m\) integers — the number of good rows and columns just after the \(i\)-th student enters the meeting hall.
|
The first test case is shown in the statement.After the \(1\)-st student enters the meeting hall, there are \(2\) good rows and columns: the \(1\)-st row and the \(1\)-st column.After the \(2\)-nd student enters the meeting hall, there are \(3\) good rows and columns: the \(1\)-st row, the \(1\)-st column and the \(2\)-nd column.After the \(3\)-rd student enters the meeting hall, the \(4\) rows and columns are all good.After the \(4\)-th student enters the meeting hall, there are \(3\) good rows and columns: the \(2\)-nd row, the \(1\)-st column and the \(2\)-nd column.
|
Input: 32 211004 2110011012 411001101 | Output: 2 3 4 3 2 3 4 3 5 4 6 5 2 3 3 3 4 4 4 5
|
Medium
| 3 | 1,354 | 668 | 162 | 16 |
1,901 |
E
|
1901E
|
E. Compressed Tree
| 2,200 |
dfs and similar; dp; graphs; greedy; sortings; trees
|
You are given a tree consisting of \(n\) vertices. A number is written on each vertex; the number on vertex \(i\) is equal to \(a_i\).You can perform the following operation any number of times (possibly zero): choose a vertex which has at most \(1\) incident edge and remove this vertex from the tree. Note that you can delete all vertices.After all operations are done, you're compressing the tree. The compression process is done as follows. While there is a vertex having exactly \(2\) incident edges in the tree, perform the following operation: delete this vertex, connect its neighbors with an edge. It can be shown that if there are multiple ways to choose a vertex to delete during the compression process, the resulting tree is still the same.Your task is to calculate the maximum possible sum of numbers written on vertices after applying the aforementioned operation any number of times, and then compressing the tree.
|
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.The first line of each test case contains a single integer \(n\) (\(2 \le n \le 5 \cdot 10^5\)) — the number of vertices.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(-10^9 \le a_i \le 10^9\)).Each of the next \(n - 1\) lines describes an edge of the tree. Edge \(i\) is denoted by two integers \(v_i\) and \(u_i\), the labels of vertices it connects (\(1 \le v_i, u_i \le n\), \(v_i \ne u_i\)). These edges form a tree. Additional constraint on the input: the sum of \(n\) over all test cases doesn't exceed \(5 \cdot 10^5\).
|
For each test case, print a single integer — the maximum possible sum of numbers written on vertices after applying the aforementioned operation any number of times, and then compressing the tree.
|
Input: 341 -2 2 11 23 22 42-2 -52 17-2 4 -2 3 3 2 -11 22 33 43 54 64 7 | Output: 3 0 9
|
Hard
| 6 | 930 | 645 | 196 | 19 |
|
855 |
D
|
855D
|
D. Rowena Ravenclaw's Diadem
| 2,500 |
trees
|
Harry, upon inquiring Helena Ravenclaw's ghost, came to know that she told Tom Riddle or You-know-who about Rowena Ravenclaw's diadem and that he stole it from her. Harry thought that Riddle would have assumed that he was the only one to discover the Room of Requirement and thus, would have hidden it there. So Harry is trying to get inside the Room of Requirement to destroy the diadem as he knows that it is a horcrux.But he has to answer a puzzle in order to enter the room. He is given n objects, numbered from 1 to n. Some of the objects have a parent object, that has a lesser number. Formally, object i may have a parent object parenti such that parenti < i.There is also a type associated with each parent relation, it can be either of type 1 or type 2. Type 1 relation means that the child object is like a special case of the parent object. Type 2 relation means that the second object is always a part of the first object and all its special cases.Note that if an object b is a special case of object a, and c is a special case of object b, then c is considered to be a special case of object a as well. The same holds for parts: if object b is a part of a, and object c is a part of b, then we say that object c is a part of a. Also note, that if object b is a part of a, and object c is a special case of a, then b is a part of c as well.An object is considered to be neither a part of itself nor a special case of itself.Now, Harry has to answer two type of queries: 1 u v: he needs to tell if object v is a special case of object u. 2 u v: he needs to tell if object v is a part of object u.
|
First line of input contains the number n (1 ≤ n ≤ 105), the number of objects. Next n lines contain two integer parenti and typei ( - 1 ≤ parenti < i parenti ≠ 0, - 1 ≤ typei ≤ 1), implying that the i-th object has the parent parenti. (If typei = 0, this implies that the object i is a special case of object parenti. If typei = 1, this implies that the object i is a part of object parenti). In case the i-th object has no parent, both parenti and typei are -1.Next line contains an integer q (1 ≤ q ≤ 105), the number of queries. Next q lines each represent a query having three space separated integers typei, ui, vi (1 ≤ typei ≤ 2, 1 ≤ u, v ≤ n).
|
Output will contain q lines, each containing the answer for the corresponding query as ""YES"" (affirmative) or ""NO"" (without quotes).You can output each letter in any case (upper or lower).
|
In test case 1, as object 2 is a special case of object 1 and object 3 is a special case of object 2, this makes object 3 a special case of object 1.In test case 2, as object 2 is a special case of object 1 and object 1 has object 3, this will mean that object 2 will also have object 3. This is because when a general case (object 1) has object 3, its special case (object 2) will definitely have object 3.
|
Input: 3-1 -11 02 021 1 32 1 3 | Output: YESNO
|
Expert
| 1 | 1,607 | 651 | 192 | 8 |
137 |
A
|
137A
|
A. Postcards and photos
| 900 |
implementation
|
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
|
The only line of the input data contains a non-empty string consisting of letters ""С"" and ""P"" whose length does not exceed 100 characters. If the i-th character in the string is the letter ""С"", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter ""P"", than the i-th object on the wall is a photo.
|
Print the only number — the minimum number of times Polycarpus has to visit the closet.
|
In the first sample Polycarpus needs to take one item to the closet 7 times.In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
|
Input: CPCPCPC | Output: 7
|
Beginner
| 1 | 722 | 406 | 87 | 1 |
1,866 |
G
|
1866G
|
G. Grouped Carriages
| 2,100 |
binary search; data structures; dp; flows; greedy
|
Pak Chanek observes that the carriages of a train is always full on morning departure hours and afternoon departure hours. Therefore, the balance between carriages is needed so that it is not too crowded in only a few carriages.A train contains \(N\) carriages that are numbered from \(1\) to \(N\) from left to right. Carriage \(i\) initially contains \(A_i\) passengers. All carriages are connected by carriage doors, namely for each \(i\) (\(1\leq i\leq N-1\)), carriage \(i\) and carriage \(i+1\) are connected by a two-way door.Each passenger can move between carriages, but train regulation regulates that for each \(i\), a passenger that starts from carriage \(i\) cannot go through more than \(D_i\) doors.Define \(Z\) as the most number of passengers in one same carriage after moving. Pak Chanek asks, what is the minimum possible value of \(Z\)?
|
The first line contains a single integer \(N\) (\(1 \leq N \leq 2\cdot10^5\)) — the number of carriages.The second line contains \(N\) integers \(A_1, A_2, A_3, \ldots, A_N\) (\(0 \leq A_i \leq 10^9\)) — the initial number of passengers in each carriage.The third line contains \(N\) integers \(D_1, D_2, D_3, \ldots, D_N\) (\(0 \leq D_i \leq N-1\)) — the maximum limit of the number of doors for each starting carriage.
|
An integer representing the minimum possible value of \(Z\).
|
One strategy that is optimal is as follows: \(5\) people in carriage \(1\) move to carriage \(4\) (going through \(3\) doors). \(3\) people in carriage \(5\) move to carriage \(3\) (going through \(2\) doors). \(2\) people in carriage \(6\) move to carriage \(5\) (going through \(1\) door). \(1\) person in carriage \(6\) moves to carriage \(7\) (going through \(1\) door). The number of passengers in each carriage becomes \([2,4,5,5,4,5,4]\).
|
Input: 7 7 4 2 0 5 8 3 4 0 0 1 3 1 3 | Output: 5
|
Hard
| 5 | 856 | 420 | 60 | 18 |
1,909 |
H
|
1909H
|
H. Parallel Swaps Sort
| 3,500 |
constructive algorithms; data structures
|
Dubmood - Keygen 8⠀You are given a permutation \(p_1, p_2, \dots, p_n\) of \([1, 2, \dots, n]\). You can perform the following operation some (possibly \(0\)) times: choose a subarray \([l, r]\) of even length; swap \(a_l\), \(a_{l+1}\); swap \(a_{l+2}\), \(a_{l+3}\) (if \(l+3 \leq r\)); \(\dots\) swap \(a_{r-1}\), \(a_r\). Sort the permutation in at most \(10^6\) operations. You do not need to minimize the number of operations.
|
The first line contains a single integer \(n\) (\(2 \le n \le 3 \cdot 10^5\)) — the length of the permutation.The second line contains \(n\) integers \(p_1, p_2, \ldots, p_n\) (\(1 \le p_i \le n\), the \(p_i\) are distinct) — the permutation before performing the operations.
|
Output your operations in the following format.The first line should contain an integer \(k\) (\(0 \le k \le 10^6\)) — the number of operations.The next \(k\) lines represent the \(k\) operations in order. Each of these \(k\) lines should contain two integers \(l\) and \(r\) (\(1 \leq l < r \leq n\), \(r-l+1\) must be even) — the corresponding operation consists in choosing the subarray \([l, r]\) and swapping its elements according to the problem statement.After all the operations, \(a_i = i\) must be true for each \(i\) (\(1 \leq i \leq n\)).
|
In the first test: At the beginning, \(p = [2, 5, 4, 1, 3]\). In the first operation, you can choose \([l, r] = [1, 4]\). Then, \((a_1, a_2)\) are swapped and \((a_3, a_4)\) are swapped. The new permutation is \(p = [5, 2, 1, 4, 3]\). In the second operation, you can choose \([l, r] = [1, 2]\). Then, \((a_1, a_2)\) are swapped. The new permutation is \(p = [2, 5, 1, 4, 3]\). In the third operation, you can choose \([l, r] = [2, 5]\). Then, \((a_2, a_3)\) are swapped and \((a_4, a_5)\) are swapped. The new permutation is \(p = [2, 1, 5, 3, 4]\). In the fourth operation, you can choose \([l, r] = [1, 4]\). Then, \((a_1, a_2)\) are swapped and \((a_3, a_4)\) are swapped. The new permutation is \(p = [1, 2, 3, 5, 4]\). In the fifth operation, you can choose \([l, r] = [4, 5]\). Then, \((a_4, a_5)\) are swapped. The new permutation is \(p = [1, 2, 3, 4, 5]\), which is sorted. In the second test, the permutation is already sorted, so you do not need to perform any operation.
|
Input: 52 5 4 1 3 | Output: 5 1 4 1 2 2 5 1 4 4 5
|
Master
| 2 | 432 | 275 | 550 | 19 |
804 |
C
|
804C
|
C. Ice cream coloring
| 2,200 |
constructive algorithms; dfs and similar; greedy
|
Isart and Modsart were trying to solve an interesting problem when suddenly Kasra arrived. Breathless, he asked: ""Can you solve a problem I'm stuck at all day?""We have a tree T with n vertices and m types of ice cream numerated from 1 to m. Each vertex i has a set of si types of ice cream. Vertices which have the i-th (1 ≤ i ≤ m) type of ice cream form a connected subgraph. We build a new graph G with m vertices. We put an edge between the v-th and the u-th (1 ≤ u, v ≤ m, u ≠ v) vertices in G if and only if there exists a vertex in T that has both the v-th and the u-th types of ice cream in its set. The problem is to paint the vertices of G with minimum possible number of colors in a way that no adjacent vertices have the same color.Please note that we consider that empty set of vertices form a connected subgraph in this problem.As usual, Modsart don't like to abandon the previous problem, so Isart wants you to solve the new problem.
|
The first line contains two integer n and m (1 ≤ n, m ≤ 3·105) — the number of vertices in T and the number of ice cream types.n lines follow, the i-th of these lines contain single integer si (0 ≤ si ≤ 3·105) and then si distinct integers, each between 1 and m — the types of ice cream in the i-th vertex. The sum of si doesn't exceed 5·105.n - 1 lines follow. Each of these lines describes an edge of the tree with two integers u and v (1 ≤ u, v ≤ n) — the indexes of connected by this edge vertices.
|
Print single integer c in the first line — the minimum number of colors to paint the vertices in graph G.In the second line print m integers, the i-th of which should be the color of the i-th vertex. The colors should be between 1 and c. If there are some answers, print any of them.
|
In the first example the first type of ice cream is present in the first vertex only, so we can color it in any color. The second and the third ice cream are both presented in the second vertex, so we should paint them in different colors.In the second example the colors of the second, the fourth and the fifth ice cream should obviously be distinct.
|
Input: 3 31 12 2 31 21 22 3 | Output: 21 1 2
|
Hard
| 3 | 949 | 502 | 283 | 8 |
1,983 |
C
|
1983C
|
C. Have Your Cake and Eat It Too
| 1,400 |
binary search; brute force; greedy; implementation
|
Alice, Bob and Charlie want to share a rectangular cake cut into \(n\) pieces. Each person considers every piece to be worth a different value. The \(i\)-th piece is considered to be of value \(a_i\) by Alice, \(b_i\) by Bob and \(c_i\) by Charlie.The sum over all \(a_i\), all \(b_i\) and all \(c_i\) individually is the same, equal to \(tot\).Given the values of each piece of the cake for each person, you need to give each person a contiguous slice of cake. In other words, the indices at the left and right ends of these subarrays (the slices given to each person) can be represented as \((l_a, r_a)\), \((l_b, r_b)\) and \((l_c, r_c)\) respectively for Alice, Bob and Charlie. The division needs to satisfy the following constraints: No piece is assigned to more than one person, i.e., no two subarrays among \([l_a,\ldots,r_a]\), \([l_b, \ldots, r_b]\) and \([l_c, \ldots, r_c]\) intersect. \( \sum_{i = l_a}^{r_a} a_i, \sum_{i = l_b}^{r_b} b_i, \sum_{i = l_c}^{r_c} c_i \geq \lceil \frac{tot}{3} \rceil\). Here, the notation \(\lceil \frac{a}{b} \rceil\) represents ceiling division. It is defined as the smallest integer greater than or equal to the exact division of \(a\) by \(b\). In other words, it rounds up the division result to the nearest integer. For instance \(\lceil \frac{10}{3} \rceil = 4\) and \(\lceil \frac{15}{3} \rceil = 5\).
|
The first line contains an integer \(t\), the number of testcases, (\(1 \le t \le 10^4\))For each testcase:The first line contains the integer \(n\) (\(3 \le n \le 2 \cdot 10^5\)).The following three lines contain \(n\) integers each:One line with \(n\) integers \(a_1, a_2, \ldots, a_n\) represents the values for Alice (\(1 \le a_i \le 10^6\)).The next line with \(n\) integers \(b_1, b_2, \ldots, b_n\) represents the values for Bob (\(1 \le b_i \le 10^6\)).The next line with \(n\) integers \(c_1, c_2, \ldots, c_n\) represents the values for Charlie (\(1 \le c_i \le 10^6\)).It is guaranteed that \( \sum_{i = 1}^{n} a_i = \sum_{i = 1}^{n} b_i = \sum_{i = 1}^{n} c_i\).The sum of \(n\) over all testcases does not exceed \(2 \cdot 10^5\).
|
For each testcase, output \(-1\) if the required condition is impossible. Otherwise, output six numbers – \(l_a, r_a, l_b, r_b, l_c, r_c\), the respective starting and ending indices (\(1\)-indexed) of the subarrays for Alice, Bob and Charlie, respectively.
|
In the first testcase, the sum of either of the three arrays is \(9\). Each person needs a cake slice corresponding to a subarray with a total value of at least \(\lceil \frac{9}{3} \rceil = 3\). If we assign the subarray (\(1\),\(1\)) to Alice, its total value to her is \(5\), which is \(\ge 3\); the subarray (\(2\),\(3\)) to Bob, its total value to him is \(1 + 5 = 6\), which is \(\ge 3\); and the subarray (\(4\),\(5\)) to Charlie, its total value to him \(1 + 5 = 6\), which is also \(\ge 3\). Each person gets their own separate pieces of the cake, and no piece is common to two or more people.It can be shown that for the third test case, it is not possible to give slices of the cake in a way that satisfies the given constraints.
|
Input: 1055 1 1 1 11 1 5 1 11 1 1 1 561 2 3 4 5 65 6 1 2 3 43 4 5 6 1 244 4 4 44 4 4 44 4 4 455 10 5 2 109 6 9 7 110 7 10 2 334 5 26 1 41 8 2310 4 108 7 910 4 10757113 65383 19795 53580 74452 3879 2325512917 16782 89147 93107 27365 15044 4309533518 63581 33565 34112 46774 44151 4175666 3 1 8 7 110 2 6 2 2 410 9 2 1 2 255 5 4 5 51 6 3 8 62 4 1 9 8101 1 1 1 1001 1 1 1001 1 11 1 1 1 1 1 2001 1 1 11 1 1 1 1 1001 1 1 1 1001 | Output: 1 1 2 3 4 5 5 6 1 2 3 4 -1 -1 1 1 3 3 2 2 -1 1 2 3 4 5 7 3 6 1 1 2 2 1 2 3 4 5 5 1 5 6 7 8 10
|
Easy
| 4 | 1,353 | 743 | 257 | 19 |
1,994 |
D
|
1994D
|
D. Funny Game
| 1,900 |
constructive algorithms; dsu; graphs; greedy; math; number theory; trees
|
Vanya has a graph with \(n\) vertices (numbered from \(1\) to \(n\)) and an array \(a\) of \(n\) integers; initially, there are no edges in the graph. Vanya got bored, and to have fun, he decided to perform \(n - 1\) operations.Operation number \(x\) (operations are numbered in order starting from \(1\)) is as follows: Choose \(2\) different numbers \(1 \leq u,v \leq n\), such that \(|a_u - a_v|\) is divisible by \(x\). Add an undirected edge between vertices \(u\) and \(v\) to the graph. Help Vanya get a connected\(^{\text{∗}}\) graph using the \(n - 1\) operations, or determine that it is impossible.\(^{\text{∗}}\)A graph is called connected if it is possible to reach any vertex from any other by moving along the edges.
|
Each test consists of multiple test cases. The first line contains an integer \(t\) (\(1 \le t \le 10^{3}\)) — the number of test cases. Then follows the description of the test cases.The first line of each test case contains the number \(n\) (\(1 \leq n \leq 2000\)) — the number of vertices in the graph.The second line of each test case contains \(n\) numbers \(a_1, a_2, \cdots a_n\) (\(1 \leq a_i \leq 10^9\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2000\).
|
For each test case, if there is no solution, then output ""No"" (without quotes). Otherwise, output ""Yes"" (without quotes), and then output \(n - 1\) lines, where in the \(i\)-th line, output the numbers \(u\) and \(v\) that need to be chosen for operation \(i\).You can output each letter in any case (for example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as a positive answer).
|
Let's consider the second test case. First operation \((x = 1)\): we can connect vertices \(4\) and \(1\), since \(|a_4 - a_1| = |13 - 99| = |-86| = 86\), and \(86\) is divisible by \(1\). Second operation \((x = 2)\): we can connect vertices \(2\) and \(1\), since \(|a_2 - a_1| = |7 - 99| = |-92| = 92\), and \(92\) is divisible by \(2\). Third operation \((x = 3)\): we can connect vertices \(3\) and \(2\), since \(|a_3 - a_2| = |1 - 7| = |-6| = 6\), and \(6\) is divisible by \(3\). From the picture, it can be seen that a connected graph is obtained.
|
Input: 821 4499 7 1 13510 2 31 44 73587 6 81 44 32562 35 33 79 1656 51 31 69 42552 63 25 21 51233 40 3 11 31 43 37 8 50 5 12 22 | Output: YES 2 1 YES 4 1 2 1 3 2 YES 5 1 4 1 3 1 2 1 YES 4 1 3 1 2 1 5 4 YES 3 1 5 1 2 1 4 2 YES 4 1 5 1 2 1 3 2 YES 2 1 5 2 3 1 4 3 YES 9 1 12 9 11 1 10 1 6 1 7 6 2 1 8 2 5 2 3 1 4 1
|
Hard
| 7 | 731 | 499 | 410 | 19 |
121 |
E
|
121E
|
E. Lucky Array
| 2,400 |
data structures
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has an array consisting of n numbers. He wants to perform m operations of two types: add l r d — add an integer d to all elements whose indexes belong to the interval from l to r, inclusive (1 ≤ l ≤ r ≤ n, 1 ≤ d ≤ 104); count l r — find and print on the screen how many lucky numbers there are among elements with indexes that belong to the interval from l to r inclusive (1 ≤ l ≤ r ≤ n). Each lucky number should be counted as many times as it appears in the interval. Petya has a list of all operations. The operations are such that after all additions the array won't have numbers that would exceed 104. Help Petya write a program that would perform these operations.
|
The first line contains two integers n and m (1 ≤ n, m ≤ 105) — the number of numbers in the array and the number of operations correspondingly. The second line contains n positive integers, none of which exceeds 104 — those are the array numbers. Next m lines contain operations, one per line. They correspond to the description given in the statement.It is guaranteed that after all operations are fulfilled each number in the array will not exceed 104.
|
For each operation of the second type print the single number on the single line — the number of lucky numbers in the corresponding interval.
|
In the first sample after the first addition the array will look in the following manner:4 5 6After the second addition:4 8 9The second sample after the first addition:7 7 7 7After the second addition:7 47 47 7
|
Input: 3 62 3 4count 1 3count 1 2add 1 3 2count 1 3add 2 3 3count 1 3 | Output: 1011
|
Expert
| 1 | 894 | 455 | 141 | 1 |
1,170 |
I
|
1170I
|
I. Good Subsets
| 0 |
*special; dp
|
You are given \(n\) segments on the \(Ox\) axis. The \(i\)-th segment is given as a pair \(l_i, r_i\), where \(l_i\) is the position of the left end of the \(i\)-th segment and \(r_i\) is the position of the right end of the \(i\)-th segment. Segments may intersect, overlap, or even coincide. A segment is a set of numbers (including floating-point numbers) lying between the segment ends or coinciding with them. Formally, the segment \([l, r]=\{x~|~x \in \Bbb{R},~l \le x \le r\}\).Let the union of segments be the set of all axis points covered by the set of segments. Let's call a subset of the given segments good if its union equals the union of all \(n\) segments.Your task is to calculate the number of good subsets of the given \(n\) segments. Since the answer may be very large, print it modulo \(998244353\).
|
The first line of the input contains one integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) — the number of segments.The next \(n\) lines contain segments. The \(i\)-th segment is given as a pair \(l_i, r_i\) (\(1 \le l_i \le r_i \le 10^9\)), where \(l_i\) is the left border of the segment and \(r_i\) is the right border of the segment. Segments may intersect, overlap, or even coincide.
|
Print the number of good subsets of the given set of segments. Since the answer may be very large, print it modulo \(998244353\).
|
Input: 3 1 1 2 6 1 6 | Output: 4
|
Beginner
| 2 | 820 | 383 | 129 | 11 |
|
1,672 |
F1
|
1672F1
|
F1. Array Shuffling
| 2,000 |
constructive algorithms; graphs; greedy
|
oolimry has an array \(a\) of length \(n\) which he really likes. Today, you have changed his array to \(b\), a permutation of \(a\), to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers \(i,j\) such that \(1 \leq i,j \leq n\). Swap \(b_i\) and \(b_j\). The sadness of the array \(b\) is the minimum number of operations needed to transform \(b\) into \(a\).Given the array \(a\), find any array \(b\) which is a permutation of \(a\) that has the maximum sadness over all permutations of the array \(a\).
|
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 a single integer \(n\) (\(1 \leq n \leq 2 \cdot 10^5\)) — 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 n\)) — elements of the array \(a\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, print \(n\) integers \(b_1, b_2, \ldots, b_n\) — describing the array \(b\). If there are multiple answers, you may print any.
|
In the first test case, the array \([1,2]\) has sadness \(1\). We can transform \([1,2]\) into \([2,1]\) using one operation with \((i,j)=(1,2)\).In the second test case, the array \([3,3,2,1]\) has sadness \(2\). We can transform \([3,3,2,1]\) into \([1,2,3,3]\) with two operations with \((i,j)=(1,4)\) and \((i,j)=(2,3)\) respectively.
|
Input: 222 141 2 3 3 | Output: 1 2 3 3 2 1
|
Hard
| 3 | 585 | 536 | 146 | 16 |
1,392 |
B
|
1392B
|
B. Omkar and Infinity Clock
| 800 |
implementation; math
|
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:You are given an array \(a\) of \(n\) integers. You are also given an integer \(k\). Lord Omkar wants you to do \(k\) operations with this array.Define one operation as the following: Set \(d\) to be the maximum value of your array. For every \(i\) from \(1\) to \(n\), replace \(a_{i}\) with \(d-a_{i}\). The goal is to predict the contents in the array after \(k\) operations. Please help Ray determine what the final sequence will look like!
|
Each test contains multiple test cases. The first line contains the number of 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 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 10^{18}\)) – the length of your array and the number of operations to perform.The second line of each test case contains \(n\) integers \(a_{1},a_{2},...,a_{n}\) \((-10^9 \leq a_{i} \leq 10^9)\) – the initial contents of your array.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each case, print the final version of array \(a\) after \(k\) operations described above.
|
In the first test case the array changes as follows:Initially, the array is \([-199, 192]\). \(d = 192\).After the operation, the array becomes \([d-(-199), d-192] = [391, 0]\).
|
Input: 3 2 1 -199 192 5 19 5 -1 4 2 0 1 2 69 | Output: 391 0 0 6 1 3 5 0
|
Beginner
| 2 | 657 | 591 | 93 | 13 |
22 |
A
|
22A
|
A. Second Order Statistics
| 800 |
brute force
|
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.
|
The first input line contains integer n (1 ≤ n ≤ 100) — amount of numbers in the sequence. The second line contains n space-separated integer numbers — elements of the sequence. These numbers don't exceed 100 in absolute value.
|
If the given sequence has the second order statistics, output this order statistics, otherwise output NO.
|
Input: 41 2 2 -4 | Output: 1
|
Beginner
| 1 | 348 | 227 | 105 | 0 |
|
1,211 |
G
|
1211G
|
G. King's Path
| 2,500 |
*special; math; trees
|
There are \(n\) cities and \(n-1\) two-way roads in Treeland. Each road connects a pair of different cities. From any city you can drive to any other, moving only along the roads. Cities are numbered from \(1\) to \(n\). Yes, of course, you recognized an undirected tree in this description.There is exactly one flag in each city, in the \(i\)-th city the flag color is \(c_i\). The colors of the flags in different cities may be the same.If the King travels along the route \([u_1, u_2, u_3, \dots, u_k]\), then this means that he starts in the city \(u_1\), then moves to the city \(u_2\) (\(u_2\) is connected by road with \(u_1\)), then from \(u_2\) to \(u_3\) (\(u_3\) is connected by road to \(u_2\)), and so on until he arrives in the city of \(u_k\). It is possible that during this route the King will visit the same city more than once. In other words, the route \([u_1, u_2, u_3, \dots, u_k]\) does not necessarily consist of different cities. In terms of graph theory — the King moves from \(u_1\) to \(u_k\) along some path \([u_1, u_2, u_3, \dots, u_k]\), which is not necessarily simple (for all \(j\) from \(1\) to \(k-1\) of the city \(u_j\) and \(u_{j+1}\) are connected by road).When the King moves from one city to another, city heads exchange flags as a sign of their friendship. Example of moving the King along the route \([1, 4, 2, 6]\). The color of the vertex matches the color of the flag at that vertex. For aesthetic reasons, the King wants the flag color in the city \(i\) to be equal to \(d_i\) for all \(i\) from \(1\) to \(n\). Determine whether the King can choose some route and drive along it so that for each city the flag color in it turns out to be equal to the desired color \(d_i\). Note that the King can choose (and drive) exactly one route. If yes, find the shortest possible route for the King.If the initial colors of the flags already match the King's requirements (i.e. \(c_i=d_i\) for all \(i\)), then consider that the King makes a route of length \(k=0\).
|
The first line contains an integer \(t\) (\(1 \le t \le 10^5\)) — the number of test cases to solve. The following are the cases.Each case begins with a line containing an integer \(n\) (\(2 \le n \le 2\cdot10^5\)) — the number of cities in Treeland.The following is a line of \(n\) integers \(c_1, c_2, \dots, c_n\) (\(1 \le c_i \le 10^6\)), where \(c_i\) denotes the color of the flag at the \(i\)-th vertex before the King's journey.The following is a line of \(n\) integers \(d_1, d_2, \dots, d_n\) (\(1 \le d_i \le 10^6\)), where \(d_i\) denotes the required flag color at the \(i\)-th vertex after the completion of the King's journey.Further, in the \(n-1\) line, the Treeland's roads are listed. Each road is given by a line containing two integers \(x_j, y_j\) (\(1 \le x_j, y_j \le n\)) — numbers of cities that are connected by the \(j\) th road.It is guaranteed that from every city you can get to any other by road (in other words, the system of cities and roads forms an undirected tree).The sum of all \(n\) values for all cases in one test does not exceed \(2\cdot10^5\).
|
Print the answers to all cases in the order of their appearance in the input data.Each answer must begin with a line containing ""Yes"" (in the case of a positive answer) or ""No"" (in the case that the required route does not exist). In the case of a positive answer, the following line must contain an integer \(k\) — the number of cities in the shortest possible route of the King. The next line should contain the required route \(u_1, u_2, \dots, u_k\) (\(1 \le u_i \le n\)). You can skip the line if \(k=0\).
|
Input: 1 7 2 3 2 7 1 1 3 7 1 2 3 1 2 3 1 7 4 1 2 6 2 3 2 4 5 4 | Output: Yes 4 1 4 2 6
|
Expert
| 3 | 2,006 | 1,089 | 514 | 12 |
|
2,097 |
B
|
2097B
|
B. Baggage Claim
| 2,300 |
combinatorics; dfs and similar; dp; dsu; graphs; implementation; math; trees
|
Every airport has a baggage claim area, and Balbesovo Airport is no exception. At some point, one of the administrators at Sheremetyevo came up with an unusual idea: to change the traditional shape of the baggage claim conveyor from a carousel to a more complex form.Suppose that the baggage claim area is represented as a rectangular grid of size \(n \times m\). The administration proposed that the path of the conveyor should pass through the cells \(p_1, p_2, \ldots, p_{2k+1}\), where \(p_i = (x_i, y_i)\).For each cell \(p_i\) and the next cell \(p_{i+1}\) (where \(1 \leq i \leq 2k\)), these cells must share a common side. Additionally, the path must be simple, meaning that for no pair of indices \(i \neq j\) should the cells \(p_i\) and \(p_j\) coincide.Unfortunately, the route plan was accidentally spoiled by spilled coffee, and only the cells with odd indices of the path were preserved: \(p_1, p_3, p_5, \ldots, p_{2k+1}\). Your task is to determine the number of ways to restore the original complete path \(p_1, p_2, \ldots, p_{2k+1}\) given these \(k+1\) cells.Since the answer can be very large, output it modulo \(10^9+7\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 3 \cdot 10^4\)). The description of the test cases follows. The first line of each test case contains three integers \(n\), \(m\), and \(k\) (\(1 \le n, m \le 1000\), \(n \cdot m \ge 3\), \(1 \le k \le \left\lfloor \frac12 (n m - 1) \right\rfloor\)) — the dimensions of the grid and a parameter defining the length of the path.Next, there are \(k+1\) lines, the \(i\)-th of which contains two integers \(x_{2i-1}\) and \(y_{2i-1}\) (\(1 \le x_{2i-1} \le n\), \(1 \le y_{2i-1} \le m\)) — the coordinates of the cell \(p_{2i-1}\) that lies on the path.It is guaranteed that all pairs \((x_{2i-1}, y_{2i-1})\) are distinct.It is guaranteed that the sum \(n \cdot m\) over all test cases does not exceed \(10^6\).
|
For each test case, output a single integer — the number of ways to restore the original complete path modulo \(10^9+7\).
|
In the first test case, there are two possible paths: \((1,1) \to (2,1) \to (2, 2) \to (2, 3) \to (2, 4)\) \((1,1) \to (1,2) \to (2, 2) \to (2, 3) \to (2, 4)\) In the second test case, there is no suitable path, as the cells \((1,1)\) and \((1,4)\) do not have a common neighboring cell.
|
Input: 52 4 21 12 22 41 4 11 11 45 5 112 53 44 55 44 35 24 13 22 11 22 31 43 4 41 22 13 22 33 43 3 22 21 11 3 | Output: 2 0 2 5 1
|
Expert
| 8 | 1,144 | 819 | 121 | 20 |
1,613 |
F
|
1613F
|
F. Tree Coloring
| 2,600 |
combinatorics; divide and conquer; fft
|
You are given a rooted tree consisting of \(n\) vertices numbered from \(1\) to \(n\). The root of the tree is the vertex \(1\).You have to color all vertices of the tree into \(n\) colors (also numbered from \(1\) to \(n\)) so that there is exactly one vertex for each color. Let \(c_i\) be the color of vertex \(i\), and \(p_i\) be the parent of vertex \(i\) in the rooted tree. The coloring is considered beautiful if there is no vertex \(k\) (\(k > 1\)) such that \(c_k = c_{p_k} - 1\), i. e. no vertex such that its color is less than the color of its parent by exactly \(1\).Calculate the number of beautiful colorings, and print it modulo \(998244353\).
|
The first line contains one integer \(n\) (\(2 \le n \le 250000\)) — the number of vertices in the tree.Then \(n-1\) lines follow, the \(i\)-th line contains two integers \(x_i\) and \(y_i\) (\(1 \le x_i, y_i \le n\); \(x_i \ne y_i\)) denoting an edge between the vertex \(x_i\) and the vertex \(y_i\). These edges form a tree.
|
Print one integer — the number of beautiful colorings, taken modulo \(998244353\).
|
Input: 5 1 2 3 2 4 2 2 5 | Output: 42
|
Expert
| 3 | 660 | 327 | 82 | 16 |
|
1,077 |
F1
|
1077F1
|
F1. Pictures with Kittens (easy version)
| 1,900 |
dp
|
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of \(n\) consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the \(i\)-th picture has beauty \(a_i\).Vova wants to repost exactly \(x\) pictures in such a way that: each segment of the news feed of at least \(k\) consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if \(k=1\) then Vova has to repost all the pictures in the news feed. If \(k=2\) then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
|
The first line of the input contains three integers \(n, k\) and \(x\) (\(1 \le k, x \le n \le 200\)) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost.The second line of the input contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\)), where \(a_i\) is the beauty of the \(i\)-th picture.
|
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement.Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
|
Input: 5 2 3 5 1 3 10 1 | Output: 18
|
Hard
| 1 | 990 | 413 | 246 | 10 |
|
156 |
C
|
156C
|
C. Cipher
| 2,000 |
combinatorics; dp
|
Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything. At last, after some thought, he thought of something. Let's say there is a word s, consisting of |s| lowercase Latin letters. Then for one operation you can choose a certain position p (1 ≤ p < |s|) and perform one of the following actions: either replace letter sp with the one that alphabetically follows it and replace letter sp + 1 with the one that alphabetically precedes it; or replace letter sp with the one that alphabetically precedes it and replace letter sp + 1 with the one that alphabetically follows it. Let us note that letter ""z"" doesn't have a defined following letter and letter ""a"" doesn't have a defined preceding letter. That's why the corresponding changes are not acceptable. If the operation requires performing at least one unacceptable change, then such operation cannot be performed.Two words coincide in their meaning iff one of them can be transformed into the other one as a result of zero or more operations.Sherlock Holmes needs to learn to quickly determine the following for each word: how many words can exist that coincide in their meaning with the given word, but differs from the given word in at least one character? Count this number for him modulo 1000000007 (109 + 7).
|
The input data contains several tests. The first line contains the only integer t (1 ≤ t ≤ 104) — the number of tests.Next t lines contain the words, one per line. Each word consists of lowercase Latin letters and has length from 1 to 100, inclusive. Lengths of words can differ.
|
For each word you should print the number of different other words that coincide with it in their meaning — not from the words listed in the input data, but from all possible words. As the sought number can be very large, print its value modulo 1000000007 (109 + 7).
|
Some explanations about the operation: Note that for each letter, we can clearly define the letter that follows it. Letter ""b"" alphabetically follows letter ""a"", letter ""c"" follows letter ""b"", ..., ""z"" follows letter ""y"". Preceding letters are defined in the similar manner: letter ""y"" precedes letter ""z"", ..., ""a"" precedes letter ""b"". Note that the operation never changes a word's length. In the first sample you can obtain the only other word ""ba"". In the second sample you cannot obtain any other word, so the correct answer is 0.Consider the third sample. One operation can transform word ""klmbfxzb"" into word ""klmcexzb"": we should choose p = 4, and replace the fourth letter with the following one (""b"" → ""c""), and the fifth one — with the preceding one (""f"" → ""e""). Also, we can obtain many other words from this one. An operation can transform word ""ya"" only into one other word ""xb"". Word ""ya"" coincides in its meaning with words ""xb"", ""wc"", ""vd"", ..., ""ay"" (overall there are 24 other words). The word ""klmbfxzb has many more variants — there are 3320092814 other words that coincide with in the meaning. So the answer for the first word equals 24 and for the second one equals 320092793 — the number 3320092814 modulo 109 + 7
|
Input: 1ab | Output: 1
|
Hard
| 2 | 1,482 | 279 | 266 | 1 |
1,903 |
C
|
1903C
|
C. Theofanis' Nightmare
| 1,400 |
constructive algorithms; greedy
|
Theofanis easily gets obsessed with problems before going to sleep and often has nightmares about them. To deal with his obsession he visited his doctor, Dr. Emix.In his latest nightmare, he has an array \(a\) of size \(n\) and wants to divide it into non-empty subarrays\(^{\dagger}\) such that every element is in exactly one of the subarrays.For example, the array \([1,-3,7,-6,2,5]\) can be divided to \([1] [-3,7] [-6,2] [5]\). The Cypriot value of such division is equal to \(\Sigma_{i=1}^{k} i \cdot \mathrm{sum}_i\) where \(k\) is the number of subarrays that we divided the array into and \(\mathrm{sum}_i\) is the sum of the \(i\)-th subarray.The Cypriot value of this division of the array \([1] [-3,7] [-6,2] [5] = 1 \cdot 1 + 2 \cdot (-3 + 7) + 3 \cdot (-6 + 2) + 4 \cdot 5 = 17\). Theofanis is wondering what is the maximum Cypriot value of any division of the array.\(^{\dagger}\) An array \(b\) is a subarray of an array \(a\) if \(b\) can be obtained from \(a\) by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.
|
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.Each test case consists of two lines. The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^{5}\)) — the size of the array. The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(-10^8 \le a_i \le 10^{8}\)) — the elements of the array.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^{5}\).
|
For each test case, print one integer — the maximum Cypriot value of the array \(a\).
|
In the first test case, to get the maximum Cypriot value we divide the array into \([1][-3][7][-6][2][5]\) which gives us: \(\Sigma_{i=1}^{k} i \cdot \mathrm{sum}_i = 1 \cdot 1 + 2 \cdot (-3) + 3 \cdot 7 + 4 \cdot (-6) + 5 \cdot 2 + 6 \cdot 5 = 32\)Similarly, in the second test case we divide the array into \([2][9,-5,-3]\) which gives us \(\Sigma_{i=1}^{k} i \cdot \mathrm{sum}_i = 1 \cdot 2 + 2 \cdot (9 + (-5) + (-3)) = 4\).
|
Input: 461 -3 7 -6 2 542 9 -5 -38-3 -4 2 -5 1 10 17 231830 | Output: 32 4 343 830
|
Easy
| 2 | 1,161 | 469 | 85 | 19 |
610 |
A
|
610A
|
A. Pasha and Stick
| 1,000 |
combinatorics; math
|
Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n. Pasha likes rectangles but hates squares, so he wonders, how many ways are there to split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square.Your task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer x, such that the number of parts of length x in the first way differ from the number of parts of length x in the second way.
|
The first line of the input contains a positive integer n (1 ≤ n ≤ 2·109) — the length of Pasha's stick.
|
The output should contain a single integer — the number of ways to split Pasha's stick into four parts of positive integer length so that it's possible to make a rectangle by connecting the ends of these parts, but is impossible to form a square.
|
There is only one way to divide the stick in the first sample {1, 1, 2, 2}.Four ways to divide the stick in the second sample are {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7} and {4, 4, 6, 6}. Note that {5, 5, 5, 5} doesn't work.
|
Input: 6 | Output: 1
|
Beginner
| 2 | 705 | 104 | 246 | 6 |
1,285 |
B
|
1285B
|
B. Just Eat It!
| 1,300 |
dp; greedy; implementation
|
Today, Yasser and Adel are at the shop buying cupcakes. There are \(n\) cupcake types, arranged from \(1\) to \(n\) on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type \(i\) is an integer \(a_i\). There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment \([l, r]\) \((1 \le l \le r \le n)\) that does not include all of cupcakes (he can't choose \([l, r] = [1, n]\)) and buy exactly one cupcake of each of types \(l, l + 1, \dots, r\).After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be \([7, 4, -1]\). Yasser will buy all of them, the total tastiness will be \(7 + 4 - 1 = 10\). Adel can choose segments \([7], [4], [-1], [7, 4]\) or \([4, -1]\), their total tastinesses are \(7, 4, -1, 11\) and \(3\), respectively. Adel can choose segment with tastiness \(11\), and as \(10\) is not strictly greater than \(11\), Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.
|
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 \(n\) (\(2 \le n \le 10^5\)).The second line of each test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(-10^9 \le a_i \le 10^9\)), where \(a_i\) represents the tastiness of the \(i\)-th type of cupcake.It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(10^5\).
|
For each test case, print ""YES"", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print ""NO"".
|
In the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment \([1, 2]\) with total tastiness \(11\), which is not less than the total tastiness of all cupcakes, which is \(10\).In the third example, Adel can choose the segment \([3, 3]\) with total tastiness of \(5\). Note that Yasser's cupcakes' total tastiness is also \(5\), so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.
|
Input: 3 4 1 2 3 4 3 7 4 -1 3 5 -5 5 | Output: YES NO NO
|
Easy
| 3 | 1,362 | 499 | 214 | 12 |
1,431 |
A
|
1431A
|
A. Selling Hamburgers
| 800 |
*special
|
There are \(n\) customers in the cafeteria. Each of them wants to buy a hamburger. The \(i\)-th customer has \(a_i\) coins, and they will buy a hamburger if it costs at most \(a_i\) coins.Suppose the cost of the hamburger is \(m\). Then the number of coins the cafeteria earns is \(m\) multiplied by the number of people who buy a hamburger if it costs \(m\). Your task is to calculate the maximum number of coins the cafeteria can earn.
|
The first line contains one integer \(t\) (\(1 \le t \le 100\)) — the number of test cases.Each test case consists of two lines. The first line contains one integer \(n\) (\(1 \le n \le 100\)) — the number of customers.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^{12}\)), where \(a_i\) is the number of coins the \(i\)-th customer has.
|
For each test case, print one integer — the maximum number of coins the cafeteria can earn.
|
Explanations for the test cases of the example: the best price for the hamburger is \(m = 1\), so \(3\) hamburgers are bought, and the cafeteria earns \(3\) coins; the best price for the hamburger is \(m = 4\), so \(1\) hamburger is bought, and the cafeteria earns \(4\) coins; the best price for the hamburger is \(m = 2\), so \(3\) hamburgers are bought, and the cafeteria earns \(6\) coins; the best price for the hamburger is \(m = 4\), so \(5\) hamburgers are bought, and the cafeteria earns \(20\) coins; the best price for the hamburger is \(m = 10^{12}\), so \(1\) hamburger is bought, and the cafeteria earns \(10^{12}\) coins; the best price for the hamburger is \(m = 10^{12} - 1\), so \(2\) hamburgers are bought, and the cafeteria earns \(2 \cdot 10^{12} - 2\) coins.
|
Input: 6 3 1 1 1 3 4 1 1 3 2 4 2 8 1 2 3 4 5 6 7 8 1 1000000000000 3 1000000000000 999999999999 1 | Output: 3 4 6 20 1000000000000 1999999999998
|
Beginner
| 1 | 437 | 377 | 91 | 14 |
1,119 |
F
|
1119F
|
F. Niyaz and Small Degrees
| 3,400 |
data structures; dp; trees
|
Niyaz has a tree with \(n\) vertices numerated from \(1\) to \(n\). A tree is a connected graph without cycles.Each edge in this tree has strictly positive integer weight. A degree of a vertex is the number of edges adjacent to this vertex.Niyaz does not like when vertices in the tree have too large degrees. For each \(x\) from \(0\) to \((n-1)\), he wants to find the smallest total weight of a set of edges to be deleted so that degrees of all vertices become at most \(x\).
|
The first line contains a single integer \(n\) (\(2 \le n \le 250\,000\)) — the number of vertices in Niyaz's tree.Each of the next \((n - 1)\) lines contains three integers \(a\), \(b\), \(c\) (\(1 \le a, b \le n\), \(1 \leq c \leq 10^6\)) — the indices of the vertices connected by this edge and its weight, respectively. It is guaranteed that the given edges form a tree.
|
Print \(n\) integers: for each \(x = 0, 1, \ldots, (n-1)\) print the smallest total weight of such a set of edges that after one deletes the edges from the set, the degrees of all vertices become less than or equal to \(x\).
|
In the first example, the vertex \(1\) is connected with all other vertices. So for each \(x\) you should delete the \((4-x)\) lightest edges outgoing from vertex \(1\), so the answers are \(1+2+3+4\), \(1+2+3\), \(1+2\), \(1\) and \(0\).In the second example, for \(x=0\) you need to delete all the edges, for \(x=1\) you can delete two edges with weights \(1\) and \(5\), and for \(x \geq 2\) it is not necessary to delete edges, so the answers are \(1+2+5+14\), \(1+5\), \(0\), \(0\) and \(0\).
|
Input: 5 1 2 1 1 3 2 1 4 3 1 5 4 | Output: 10 6 3 1 0
|
Master
| 3 | 478 | 374 | 224 | 11 |
58 |
E
|
58E
|
E. Expression
| 2,400 |
dp
|
One day Vasya was solving arithmetical problems. He wrote down an expression a + b = c in his notebook. When the teacher checked Vasya's work it turned out that Vasya had solved the problem incorrectly. Now Vasya tries to find excuses. He says that he simply forgot to write down several digits in numbers a, b and c, but he can't remember what numbers they actually were. Help Vasya, find such numbers x, y and z, with which the following conditions are met: x + y = z, from the expression x + y = z several digits can be erased in such a way that the result will be a + b = c, the expression x + y = z should have the minimal length.
|
The first and only input line contains the expression a + b = c (1 ≤ a, b, c ≤ 106, a, b and c don't contain leading zeroes) which is the expression Vasya wrote down.
|
Print the correct expression x + y = z (x, y and z are non-negative numbers without leading zeroes). The expression a + b = c must be met in x + y = z as a subsequence. The printed solution should have the minimal possible number of characters. If there are several such solutions, you can print any of them.
|
Input: 2+4=5 | Output: 21+4=25
|
Expert
| 1 | 635 | 166 | 308 | 0 |
|
1,704 |
E
|
1704E
|
E. Count Seconds
| 2,200 |
brute force; constructive algorithms; dp; graphs; implementation; math
|
Cirno has a DAG (Directed Acyclic Graph) with \(n\) nodes and \(m\) edges. The graph has exactly one node that has no out edges. The \(i\)-th node has an integer \(a_i\) on it.Every second the following happens: Let \(S\) be the set of nodes \(x\) that have \(a_x > 0\). For all \(x \in S\), \(1\) is subtracted from \(a_x\), and then for each node \(y\), such that there is an edge from \(x\) to \(y\), \(1\) is added to \(a_y\).Find the first moment of time when all \(a_i\) become \(0\). Since the answer can be very large, output it modulo \(998\,244\,353\).
|
The first line contains a single integer \(t\) (\(1 \leq t \leq 1000\)) — the number of test cases. Description of test cases follows.The first line of each test case contains two integers \(n, m\) (\(1 \leq n, m \leq 1000\)) — the number of vertices and edges in the graph.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \leq a_i \leq 10^9\)) — the integer on vertices.Each line of the following \(m\) lines contains two integers \(x, y\) (\(1 \leq x, y \leq n\)), represent a directed edge from \(x\) to \(y\). It is guaranteed that the graph is a DAG with no multi-edges, and there is exactly one node that has no out edges.It is guaranteed that both sum of \(n\) and sum of \(m\) over all test cases are less than or equal to \(10\,000\).
|
For each test case, print an integer in a separate line — the first moment of time when all \(a_i\) become \(0\), modulo \(998\,244\,353\).
|
In the first test case: At time \(0\), the values of the nodes are \([1, 1, 1]\). At time \(1\), the values of the nodes are \([0, 1, 1]\). At time \(2\), the values of the nodes are \([0, 0, 1]\). At time \(3\), the values of the nodes are \([0, 0, 0]\).So the answer is \(3\). In the second test case: At time \(0\), the values of the nodes are \([1, 0, 0, 0, 0]\). At time \(1\), the values of the nodes are \([0, 1, 0, 0, 1]\). At time \(2\), the values of the nodes are \([0, 0, 1, 0, 0]\). At time \(3\), the values of the nodes are \([0, 0, 0, 1, 0]\). At time \(4\), the values of the nodes are \([0, 0, 0, 0, 1]\). At time \(5\), the values of the nodes are \([0, 0, 0, 0, 0]\). So the answer is \(5\).In the third test case:The first moment of time when all \(a_i\) become \(0\) is \(6\cdot 998244353 + 4\).
|
Input: 53 21 1 11 22 35 51 0 0 0 01 22 33 44 51 510 11998244353 0 0 0 998244353 0 0 0 0 01 22 33 44 55 66 77 88 99 101 37 95 61293 1145 9961 9961 19191 22 33 45 41 42 46 910 10 10 10 10 101 21 32 34 36 33 56 56 16 2 | Output: 3 5 4 28010 110
|
Hard
| 6 | 562 | 783 | 139 | 17 |
976 |
B
|
976B
|
B. Lara Croft and the New Game
| 1,300 |
implementation; math
|
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy.Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions.Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2).Lara has already moved to a neighbouring cell k times. Can you determine her current position?
|
The only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type!
|
Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times.
|
Here is her path on matrix 4 by 3:
|
Input: 4 3 0 | Output: 1 1
|
Easy
| 2 | 1,118 | 147 | 110 | 9 |
530 |
F
|
530F
|
F. Jumping frogs
| 2,100 |
*special
|
A rectangular swamp is inhabited by 10 species of frogs. Frogs of species i can jump from hillocks to hillock exactly i units along X-axis or Y-axis. Initially frogs of all types sit at the hillock at coordinates (0, 0). You are given coordinates of all other hillocks in the swamp. Find the largest Manhattan distance from (0, 0) to any hillock to which one of the frogs can travel by jumping between hillocks.Manhattan distance between (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|.
|
The first line of the input contains an integer N (1 ≤ N ≤ 100) - the number of hillocks. The following N lines contain the coordinates of the hillocks, formatted as ""X Y"" ( - 20 ≤ X, Y ≤ 20). All hillocks are distinct, and none of them is located at (0, 0).
|
Output a single integer — the largest Manhattan distance to any hillock reachable by one of the frogs by jumping between hillocks.
|
In the first example frogs of species 1, 2 and 3 can jump as far as the first, the second and the third hillocks, respectively.In the second example frog of species 2 can jump to the second hillock, then to the fourth and finally to the fifth.In the third example no frog can reach the hillock.
|
Input: 30 10 -20 3 | Output: 3
|
Hard
| 1 | 485 | 260 | 130 | 5 |
2,040 |
F
|
2040F
|
F. Number of Cubes
| 2,700 |
combinatorics; dp; math; number theory
|
Consider a rectangular parallelepiped with sides \(a\), \(b\), and \(c\), that consists of unit cubes of \(k\) different colors. We can apply cyclic shifts to the parallelepiped in any of the three directions any number of times\(^{\text{∗}}\).There are \(d_i\) cubes of the \(i\)-th color (\(1 \le i \le k\)). How many different parallelepipeds (with the given sides) can be formed from these cubes, no two of which can be made equal by some combination of cyclic shifts?\(^{\text{∗}}\)On the image: Top left shows the top view of the original parallelepiped. Lower layers will shift in the same way as the top layer. Top right shows the top view of a parallelepiped shifted to the right by \(1\). Bottom left shows the top view of a parallelepiped shifted down by \(2\). Bottom right shows the top view of a parallelepiped shifted to the right by \(1\) and down by \(2\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 100\)). The description of the test cases follows.The first line of each test case contains four integers: \(a\), \(b\), \(c\), and \(k\) (\(1 \le a, b, c \le 3 \cdot 10^6\); \(a \cdot b \cdot c \le 3 \cdot 10^6\); \(1 \le k \le 10^6\)) — three sides of the parallelepiped and the number of colors of unit cubes.The second line of each test case contains \(k\) integers \(d_1, d_2, \ldots, d_k\) (\(1 \le d_1 \le d_2 \le \ldots \le d_k \le 3 \cdot 10^6\)) — the elements of the array \(d\): the number of cubes of a given color.It is guaranteed that in each test case the sum of the elements of the array \(d\) is equal to \(a \cdot b \cdot c\).It is guaranteed that the sum of \(k\) over all test cases does not exceed \(10 ^ 6\).
|
For each test case, print one integer — the number of different parallelepipeds modulo \(998\,244\,353\).
|
In the first test case, there is only one parallelepiped, which consists of one unit cube. Possible parallelepipeds in the second test case
|
Input: 61 1 1 116 1 1 31 2 312 1 1 32 4 63 3 1 23 62 3 3 26 1272 60 96 417280 86400 120960 190080 | Output: 1 10 1160 12 1044 231490207
|
Master
| 4 | 873 | 841 | 105 | 20 |
411 |
B
|
411B
|
B. Multi-core Processor
| 1,600 |
implementation
|
The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor.At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked.The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within m cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the m cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.
|
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 100). Then follow n lines describing instructions. The i-th line contains m integers: xi1, xi2, ..., xim (0 ≤ xij ≤ k), where xij is the instruction that must be executed by the i-th core at the j-th cycle. If xij equals 0, then the corresponding instruction is «do nothing». But if xij is a number from 1 to k, then the corresponding instruction is «write information to the memory cell number xij».We assume that the cores are numbered from 1 to n, the work cycles are numbered from 1 to m and the memory cells are numbered from 1 to k.
|
Print n lines. In the i-th line print integer ti. This number should be equal to 0 if the i-th core won't be locked, or it should be equal to the number of the cycle when this core will be locked.
|
Input: 4 3 51 0 01 0 22 3 13 2 0 | Output: 1130
|
Medium
| 1 | 1,401 | 600 | 196 | 4 |
|
65 |
E
|
65E
|
E. Harry Potter and Moving Staircases
| 2,900 |
dfs and similar; implementation
|
Harry Potter lost his Invisibility Cloak, running from the school caretaker Filch. Finding an invisible object is not an easy task. Fortunately, Harry has friends who are willing to help. Hermione Granger had read ""The Invisibility Cloaks, and Everything about Them"", as well as six volumes of ""The Encyclopedia of Quick Search of Shortest Paths in Graphs, Network Flows, the Maximal Increasing Subsequences and Other Magical Objects"". She has already developed a search algorithm for the invisibility cloak in complex dynamic systems (Hogwarts is one of them).Hogwarts consists of n floors, numbered by integers from 1 to n. Some pairs of floors are connected by staircases. The staircases may change its position, moving exactly one end. Formally the situation is like this: if a staircase connects the floors a and b, then in one move it may modify its position so as to connect the floors a and c or b and c, where c is any floor different from a and b. Under no circumstances the staircase can connect a floor with itself. At the same time there can be multiple stairs between a pair of floors.Initially, Harry is on the floor with the number 1. He does not remember on what floor he has lost the cloak and wants to look for it on each of the floors. Therefore, his goal is to visit each of n floors at least once. Harry can visit the floors in any order and finish the searching at any floor.Nowadays the staircases move quite rarely. However, Ron and Hermione are willing to put a spell on any of them to help Harry find the cloak. To cause less suspicion, the three friends plan to move the staircases one by one, and no more than once for each staircase. In between shifting the staircases Harry will be able to move about the floors, reachable at the moment from the staircases, and look for his Invisibility Cloak. It is assumed that during all this time the staircases will not move spontaneously.Help the three friends to compose a searching plan. If there are several variants to solve the problem, any valid option (not necessarily the optimal one) will be accepted.
|
The first line contains integers n and m (1 ≤ n ≤ 100000, 0 ≤ m ≤ 200000), which are the number of floors and staircases in Hogwarts, respectively. The following m lines contain pairs of floors connected by staircases at the initial moment of time.
|
In the first line print ""YES"" (without the quotes) if Harry is able to search all the floors, and ""NO"" otherwise. If the answer is positive, then print on the second line the number of staircases that Ron and Hermione will have to shift. Further output should look like this:Harry's moves a staircase's move Harry's movesa staircase's move...a staircase's moveHarry's movesEach ""Harry's move"" should be represented as a list of floors in the order in which they have been visited. The total amount of elements of these lists must not exceed 106. When you print each list, first print the number of elements in it, and then in the same line print the actual space-separated elements. The first number in the first list should be the number 1 (the floor, from which Harry begins to search). Any list except the first one might contain the zero number of elements. Note that Harry can visit some floors again, but must visit all n floors at least once. Two consecutively visited floors must be directly connected by a staircase (at the time Harry goes from one of them to the other one). No two floors that are visited consequtively can be equal.In the description of a ""staircase's move"" indicate the number of staircase (the staircases are numbered from 1 to m in the order in which they are given in the input data) and its new location (two numbers of the connected floors in any order).Any staircase can be moved at most once. If there are several solutions, output any.
|
Input: 6 41 21 32 34 5 | Output: YES23 1 2 32 3 53 5 4 54 5 63 6 5 3
|
Master
| 2 | 2,085 | 248 | 1,480 | 0 |
|
1,800 |
F
|
1800F
|
F. Dasha and Nightmares
| 1,900 |
bitmasks; hashing; meet-in-the-middle; strings
|
Dasha, an excellent student, is studying at the best mathematical lyceum in the country. Recently, a mysterious stranger brought \(n\) words consisting of small latin letters \(s_1, s_2, \ldots, s_n\) to the lyceum. Since that day, Dasha has been tormented by nightmares.Consider some pair of integers \(\langle i, j \rangle\) (\(1 \le i \le j \le n\)). A nightmare is a string for which it is true: It is obtained by concatenation \(s_{i}s_{j}\); Its length is odd; The number of different letters in it is exactly \(25\); The number of occurrences of each letter that is in the word is odd. For example, if \(s_i=\) ""abcdefg"" and \(s_j=\) ""ijklmnopqrstuvwxyz"", the pair \(\langle i, j \rangle\) creates a nightmare.Dasha will stop having nightmares if she counts their number. There are too many nightmares, so Dasha needs your help. Count the number of different nightmares.Nightmares are called different if the corresponding pairs \(\langle i, j \rangle\) are different. The pairs \(\langle i_1, j_1 \rangle\) and \(\langle i_2, j_2 \rangle\) are called different if \(i_1 \neq i_2\) or \(j_1 \neq j_2\).
|
The first line contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) — the number of words.The following \(n\) lines contain the words \(s_1, s_2, \ldots, s_n\), consisting of small latin letters.It is guaranteed that the total length of words does not exceed \(5 \cdot 10^6\).
|
Print a single integer — the number of different nightmares.
|
In the first test, nightmares are created by pairs \(\langle 1, 3 \rangle\), \(\langle 2, 5 \rangle\), \(\langle 3, 4 \rangle\), \(\langle 6, 7 \rangle\), \(\langle 9, 10 \rangle\).
|
Input: 10ftlabcdefghijklmnopqrstuvwxyabcdeffghijkllmnopqrsttuvwxyffftlaabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyythedevidbcdefghhiiiijklmnopqrsuwxyzgorillasilverbackabcdefgijklmnopqrstuvwxyz | Output: 5
|
Hard
| 4 | 1,113 | 286 | 60 | 18 |
1,369 |
D
|
1369D
|
D. TediousLee
| 1,900 |
dp; graphs; greedy; math; trees
|
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...Let's define a Rooted Dead Bush (RDB) of level \(n\) as a rooted tree constructed as described below.A rooted dead bush of level \(1\) is a single vertex. To construct an RDB of level \(i\) we, at first, construct an RDB of level \(i-1\), then for each vertex \(u\): if \(u\) has no children then we will add a single child to it; if \(u\) has one child then we will add two children to it; if \(u\) has more than one child, then we will skip it. Rooted Dead Bushes of level \(1\), \(2\) and \(3\). Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw: The center of the claw is the vertex with label \(1\). Lee has a Rooted Dead Bush of level \(n\). Initially, all vertices of his RDB are green.In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo \(10^9+7\).
|
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.Next \(t\) lines contain test cases — one per line.The first line of each test case contains one integer \(n\) (\(1 \le n \le 2 \cdot 10^6\)) — the level of Lee's RDB.
|
For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo \(10^9 + 7\).
|
It's easy to see that the answer for RDB of level \(1\) or \(2\) is \(0\).The answer for RDB of level \(3\) is \(4\) since there is only one claw we can choose: \(\{1, 2, 3, 4\}\).The answer for RDB of level \(4\) is \(4\) since we can choose either single claw \(\{1, 3, 2, 4\}\) or single claw \(\{2, 7, 5, 6\}\). There are no other claws in the RDB of level \(4\) (for example, we can't choose \(\{2, 1, 7, 6\}\), since \(1\) is not a child of center vertex \(2\)). Rooted Dead Bush of level 4.
|
Input: 7 1 2 3 4 5 100 2000000 | Output: 0 0 4 4 12 990998587 804665184
|
Hard
| 5 | 1,374 | 259 | 116 | 13 |
670 |
A
|
670A
|
A. Holidays
| 900 |
brute force; constructive algorithms; greedy; math
|
On the planet Mars a year lasts exactly n days (there are no leap years on Mars). But Martians have the same weeks as earthlings — 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars.
|
The first line of the input contains a positive integer n (1 ≤ n ≤ 1 000 000) — the number of days in a year on Mars.
|
Print two integers — the minimum possible and the maximum possible number of days off per year on Mars.
|
In the first sample there are 14 days in a year on Mars, and therefore independently of the day a year starts with there will be exactly 4 days off .In the second sample there are only 2 days in a year on Mars, and they can both be either work days or days off.
|
Input: 14 | Output: 4 4
|
Beginner
| 4 | 272 | 117 | 103 | 6 |
1,985 |
G
|
1985G
|
G. D-Function
| 1,600 |
combinatorics; math; number theory
|
Let \(D(n)\) represent the sum of digits of \(n\). For how many integers \(n\) where \(10^{l} \leq n < 10^{r}\) satisfy \(D(k \cdot n) = k \cdot D(n)\)? Output the answer modulo \(10^9+7\).
|
The first line contains an integer \(t\) (\(1 \leq t \leq 10^4\)) – the number of test cases. Each test case contains three integers \(l\), \(r\), and \(k\) (\(0 \leq l < r \leq 10^9\), \(1 \leq k \leq 10^9\)).
|
For each test case, output an integer, the answer, modulo \(10^9 + 7\).
|
For the first test case, the only values of \(n\) that satisfy the condition are \(1\) and \(2\).For the second test case, the only values of \(n\) that satisfy the condition are \(1\), \(10\), and \(11\).For the third test case, all values of \(n\) between \(10\) inclusive and \(100\) exclusive satisfy the condition.
|
Input: 60 1 40 2 71 2 11 2 3582 74663 30 3 1 | Output: 2 3 90 12 974995667 999
|
Medium
| 3 | 189 | 210 | 71 | 19 |
1,144 |
F
|
1144F
|
F. Graph Without Long Directed Paths
| 1,700 |
dfs and similar; graphs
|
You are given a connected undirected graph consisting of \(n\) vertices and \(m\) edges. There are no self-loops or multiple edges in the given graph.You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges).
|
The first line contains two integer numbers \(n\) and \(m\) (\(2 \le n \le 2 \cdot 10^5\), \(n - 1 \le m \le 2 \cdot 10^5\)) — the number of vertices and edges, respectively.The following \(m\) lines contain edges: edge \(i\) is given as a pair of vertices \(u_i\), \(v_i\) (\(1 \le u_i, v_i \le n\), \(u_i \ne v_i\)). There are no multiple edges in the given graph, i. e. for each pair (\(u_i, v_i\)) there are no other pairs (\(u_i, v_i\)) and (\(v_i, u_i\)) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph).
|
If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print ""NO"" in the first line.Otherwise print ""YES"" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length \(m\). The \(i\)-th element of this string should be '0' if the \(i\)-th edge of the graph should be directed from \(u_i\) to \(v_i\), and '1' otherwise. Edges are numbered in the order they are given in the input.
|
The picture corresponding to the first example: And one of possible answers:
|
Input: 6 5 1 5 2 1 1 4 3 1 6 1 | Output: YES 10100
|
Medium
| 2 | 349 | 603 | 557 | 11 |
708 |
E
|
708E
|
E. Student's Camp
| 3,100 |
dp; math
|
Alex studied well and won the trip to student camp Alushta, located on the seashore. Unfortunately, it's the period of the strong winds now and there is a chance the camp will be destroyed! Camp building can be represented as the rectangle of n + 2 concrete blocks height and m blocks width.Every day there is a breeze blowing from the sea. Each block, except for the blocks of the upper and lower levers, such that there is no block to the left of it is destroyed with the probability . Similarly, each night the breeze blows in the direction to the sea. Thus, each block (again, except for the blocks of the upper and lower levers) such that there is no block to the right of it is destroyed with the same probability p. Note, that blocks of the upper and lower level are indestructible, so there are only n·m blocks that can be destroyed.The period of the strong winds will last for k days and k nights. If during this period the building will split in at least two connected components, it will collapse and Alex will have to find another place to spend summer.Find the probability that Alex won't have to look for other opportunities and will be able to spend the summer in this camp.
|
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 1500) that define the size of the destructible part of building.The second line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 109) that define the probability p. It's guaranteed that integers a and b are coprime. The third line contains a single integer k (0 ≤ k ≤ 100 000) — the number of days and nights strong wind will blow for.
|
Consider the answer as an irreducible fraction is equal to . Print one integer equal to . It's guaranteed that within the given constraints .
|
In the first sample, each of the four blocks is destroyed with the probability . There are 7 scenarios that result in building not collapsing, and the probability we are looking for is equal to , so you should print
|
Input: 2 21 21 | Output: 937500007
|
Master
| 2 | 1,189 | 412 | 141 | 7 |
1,633 |
F
|
1633F
|
F. Perfect Matching
| 2,800 |
data structures; divide and conquer; interactive; trees
|
You are given a tree consisting of \(n\) vertices (numbered from \(1\) to \(n\)) and \(n-1\) edges (numbered from \(1\) to \(n-1\)). Initially, all vertices except vertex \(1\) are inactive.You have to process queries of three types: \(1\) \(v\) — activate the vertex \(v\). It is guaranteed that the vertex \(v\) is inactive before this query, and one of its neighbors is active. After activating the vertex, you have to choose a subset of edges of the tree such that each active vertex is incident to exactly one chosen edge, and each inactive vertex is not incident to any of the chosen edges — in other words, this subset should represent a perfect matching on the active part of the tree. If any such subset of edges exists, print the sum of indices of edges in it; otherwise, print \(0\). \(2\) — queries of this type will be asked only right after a query of type \(1\), and there will be at most \(10\) such queries. If your answer to the previous query was \(0\), simply print \(0\); otherwise, print the subset of edges for the previous query as follows: first, print the number of edges in the subset, then print the indices of the chosen edges in ascending order. The sum of indices should be equal to your answer to the previous query. \(3\) — terminate the program. 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. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.
|
The first line contains one integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) — the number of vertices of the tree.Then \(n-1\) lines follow. The \(i\)-th line contains two integers \(u_i\) and \(v_i\) (\(1 \le u_i, v_i \le n\); \(u_i \ne v_i\)) — the endpoints of the \(i\)-th edge. These edges form a tree.Then the queries follow in the format described in the statement, one line per query. There will be at least \(2\) and at most \(n+10\) queries. The last query (and only the last one) will be of type \(3\). Note that you can read the \(i\)-th query only if you have already given the answer for the query \(i-1\) (except for \(i = 1\)).If your answer for one of the queries is incorrect and the judging program recognizes it, instead of the next query, you may receive the integer \(0\) on a separate line. After receiving it, your program should terminate gracefully, and you will receive ""Wrong Answer"" verdict. If your program doesn't terminate, your solution may receive some other verdict, like ""Time Limit Exceeded"", ""Idleness Limit Exceeded"", etc. Note that the fact that your solution doesn't receive the integer \(0\), it does not mean that all your answers are correct, some of them will be checked only after your program is terminated.
|
For each query of type \(1\) or \(2\), print the answer on a separate line as described in the statement. Don't forget to flush the output.
|
Input: 6 1 4 6 1 3 2 1 2 5 1 1 4 2 1 2 2 1 3 2 1 5 1 6 2 3 | Output: 1 1 1 0 0 4 2 1 3 0 0 0
|
Master
| 4 | 1,569 | 1,256 | 139 | 16 |
|
1,426 |
A
|
1426A
|
A. Floor Number
| 800 |
implementation; math
|
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is \(n\). There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains \(2\) apartments, every other floor contains \(x\) apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers \(1\) and \(2\), apartments on the second floor have numbers from \(3\) to \((x + 2)\), apartments on the third floor have numbers from \((x + 3)\) to \((2 \cdot x + 2)\), and so on.Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least \(n\) apartments.You have to answer \(t\) independent test cases.
|
The first line of the input contains one integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases. Then \(t\) test cases follow.The only line of the test case contains two integers \(n\) and \(x\) (\(1 \le n, x \le 1000\)) — the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
|
For each test case, print the answer: the number of floor on which Petya lives.
|
Consider the first test case of the example: the first floor contains apartments with numbers \(1\) and \(2\), the second one contains apartments with numbers \(3\), \(4\) and \(5\), the third one contains apartments with numbers \(6\), \(7\) and \(8\). Therefore, Petya lives on the third floor.In the second test case of the example, Petya lives in the apartment \(1\) which is on the first floor.
|
Input: 4 7 3 1 5 22 5 987 13 | Output: 3 1 5 77
|
Beginner
| 2 | 766 | 387 | 79 | 14 |
1,492 |
D
|
1492D
|
D. Genius's Gambit
| 1,900 |
bitmasks; constructive algorithms; greedy; math
|
You are given three integers \(a\), \(b\), \(k\).Find two binary integers \(x\) and \(y\) (\(x \ge y\)) such that both \(x\) and \(y\) consist of \(a\) zeroes and \(b\) ones; \(x - y\) (also written in binary form) has exactly \(k\) ones. You are not allowed to use leading zeros for \(x\) and \(y\).
|
The only line contains three integers \(a\), \(b\), and \(k\) (\(0 \leq a\); \(1 \leq b\); \(0 \leq k \leq a + b \leq 2 \cdot 10^5\)) — the number of zeroes, ones, and the number of ones in the result.
|
If it's possible to find two suitable integers, print ""Yes"" followed by \(x\) and \(y\) in base-2.Otherwise print ""No"".If there are multiple possible answers, print any of them.
|
In the first example, \(x = 101000_2 = 2^5 + 2^3 = 40_{10}\), \(y = 100001_2 = 2^5 + 2^0 = 33_{10}\), \(40_{10} - 33_{10} = 7_{10} = 2^2 + 2^1 + 2^0 = 111_{2}\). Hence \(x-y\) has \(3\) ones in base-2.In the second example, \(x = 10100_2 = 2^4 + 2^2 = 20_{10}\), \(y = 10010_2 = 2^4 + 2^1 = 18\), \(x - y = 20 - 18 = 2_{10} = 10_{2}\). This is precisely one 1.In the third example, one may show, that it's impossible to find an answer.
|
Input: 4 2 3 | Output: Yes 101000 100001
|
Hard
| 4 | 300 | 201 | 181 | 14 |
1,364 |
B
|
1364B
|
B. Most socially-distanced subsequence
| 1,300 |
greedy; two pointers
|
Given a permutation \(p\) of length \(n\), find its subsequence \(s_1\), \(s_2\), \(\ldots\), \(s_k\) of length at least \(2\) such that: \(|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|\) is as big as possible over all subsequences of \(p\) with length at least \(2\). Among all such subsequences, choose the one whose length, \(k\), is as small as possible. If multiple subsequences satisfy these conditions, you are allowed to find any of them.A sequence \(a\) is a subsequence of an array \(b\) if \(a\) can be obtained from \(b\) by deleting some (possibly, zero or all) elements.A permutation of length \(n\) is an array of length \(n\) in which every element from \(1\) to \(n\) occurs exactly once.
|
The first line contains an integer \(t\) (\(1 \le t \le 2 \cdot 10^4\)) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer \(n\) (\(2 \le n \le 10^5\)) — the length of the permutation \(p\).The second line of each test case contains \(n\) integers \(p_1\), \(p_2\), \(\ldots\), \(p_{n}\) (\(1 \le p_i \le n\), \(p_i\) are distinct) — the elements of the permutation \(p\).The sum of \(n\) across the test cases doesn't exceed \(10^5\).
|
For each test case, the first line should contain the length of the found subsequence, \(k\). The second line should contain \(s_1\), \(s_2\), \(\ldots\), \(s_k\) — its elements.If multiple subsequences satisfy these conditions, you are allowed to find any of them.
|
In the first test case, there are \(4\) subsequences of length at least \(2\): \([3,2]\) which gives us \(|3-2|=1\). \([3,1]\) which gives us \(|3-1|=2\). \([2,1]\) which gives us \(|2-1|=1\). \([3,2,1]\) which gives us \(|3-2|+|2-1|=2\). So the answer is either \([3,1]\) or \([3,2,1]\). Since we want the subsequence to be as short as possible, the answer is \([3,1]\).
|
Input: 2 3 3 2 1 4 1 3 4 2 | Output: 2 3 1 3 1 4 2
|
Easy
| 2 | 700 | 507 | 265 | 13 |
219 |
D
|
219D
|
D. Choosing Capital for Treeland
| 1,700 |
dfs and similar; dp; graphs; trees
|
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
|
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
|
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
|
Input: 32 12 3 | Output: 02
|
Medium
| 4 | 890 | 398 | 226 | 2 |
|
1,470 |
A
|
1470A
|
A. Strange Birthday Party
| 1,300 |
binary search; dp; greedy; sortings; two pointers
|
Petya organized a strange birthday party. He invited \(n\) friends and assigned an integer \(k_i\) to the \(i\)-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are \(m\) unique presents available, the \(j\)-th present costs \(c_j\) dollars (\(1 \le c_1 \le c_2 \le \ldots \le c_m\)). It's not allowed to buy a single present more than once.For the \(i\)-th friend Petya can either buy them a present \(j \le k_i\), which costs \(c_j\) dollars, or just give them \(c_{k_i}\) dollars directly.Help Petya determine the minimum total cost of hosting his party.
|
The first input line contains a single integer \(t\) (\(1 \leq t \leq 10^3\)) — the number of test cases.The first line of each test case contains two integers \(n\) and \(m\) (\(1 \leq n, m \leq 3 \cdot 10^5\)) — the number of friends, and the number of unique presents available.The following line contains \(n\) integers \(k_1, k_2, \ldots, k_n\) (\(1 \leq k_i \leq m\)), assigned by Petya to his friends. The next line contains \(m\) integers \(c_1, c_2, \ldots, c_m\) (\(1 \le c_1 \le c_2 \le \ldots \le c_m \le 10^9\)) — the prices of the presents.It is guaranteed that sum of values \(n\) over all test cases does not exceed \(3 \cdot 10^5\), and the sum of values \(m\) over all test cases does not exceed \(3 \cdot 10^5\).
|
For each test case output a single integer — the minimum cost of the party.
|
In the first example, there are two test cases. In the first one, Petya has \(5\) friends and \(4\) available presents. Petya can spend only \(30\) dollars if he gives \(5\) dollars to the first friend. A present that costs \(12\) dollars to the second friend. A present that costs \(5\) dollars to the third friend. A present that costs \(3\) dollars to the fourth friend. \(5\) dollars to the fifth friend. In the second one, Petya has \(5\) and \(5\) available presents. Petya can spend only \(190\) dollars if he gives A present that costs \(10\) dollars to the first friend. A present that costs \(40\) dollars to the second friend. \(90\) dollars to the third friend. \(40\) dollars to the fourth friend. \(10\) dollars to the fifth friend.
|
Input: 2 5 4 2 3 4 3 2 3 5 12 20 5 5 5 4 3 2 1 10 40 90 160 250 | Output: 30 190
|
Easy
| 5 | 601 | 731 | 75 | 14 |
625 |
C
|
625C
|
C. K-special Tables
| 1,300 |
constructive algorithms; implementation
|
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied: every integer from 1 to n2 appears in the table exactly once; in each row numbers are situated in increasing order; the sum of numbers in the k-th column is maximum possible. Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
|
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
|
First print the sum of the integers in the k-th column of the required table.Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.If there are multiple suitable table, you are allowed to print any.
|
Input: 4 1 | Output: 281 2 3 45 6 7 89 10 11 1213 14 15 16
|
Easy
| 2 | 789 | 181 | 331 | 6 |
|
1,941 |
F
|
1941F
|
F. Rudolf and Imbalance
| 1,800 |
binary search; greedy; sortings; two pointers
|
Rudolf has prepared a set of \(n\) problems with complexities \(a_1 < a_2 < a_3 < \dots < a_n\). He is not entirely satisfied with the balance, so he wants to add at most one problem to fix it.For this, Rudolf came up with \(m\) models of problems and \(k\) functions. The complexity of the \(i\)-th model is \(d_i\), and the complexity of the \(j\)-th function is \(f_j\). To create a problem, he selects values \(i\) and \(j\) (\(1 \le i \le m\), \(1 \le j \le k\)) and by combining the \(i\)-th model with the \(j\)-th function, he obtains a new problem with complexity \(d_i + f_j\) (a new element is inserted into the array \(a\)).To determine the imbalance of the set, Rudolf sorts the complexities of the problems in ascending order and finds the largest value of \(a_i - a_{i - 1}\) (\(i > 1\)).What is the minimum value of imbalance that Rudolf can achieve by adding at most one problem, created according to the described rules?
|
The first line of the input contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of testcases.The first line of each test case contains three integers \(n\), \(m\), and \(k\) (\(2 \le n \le 10^5\), \(1 \le m, k \le 2 \cdot 10^5\)) — the number of prepared problems, the number of models, and the number of functions, respectively.The second line of each test case contains \(n\) integers \(a_1, a_2, a_3, \dots a_n\) (\(1 \le a_i \le 2 \cdot 10^9\), \(a_i < a_{i+1}\)) — the complexities of the prepared problems.The third line of each test case contains \(m\) integers \(d_1, d_2, d_3, \dots d_m\) (\(1 \le d_i \le 10^9\)) — the complexities of the models.The fourth line of each test case contains \(k\) integers \(f_1, f_2, f_3, \dots f_k\) (\(1 \le f_i \le 10^9\)) — the complexities of the functions.It is guaranteed that the sum of \(n\) over all testcases does not exceed \(10^5\).It is guaranteed that the sum of \(m\) over all testcases does not exceed \(2 \cdot 10^5\).It is guaranteed that the sum of \(k\) over all testcases does not exceed \(2 \cdot 10^5\).
|
For each testcase, output a single number — the minimum imbalance that Rudolf can achieve.
|
Input: 75 5 55 10 15 20 2611 14 16 13 816 4 5 3 17 6 51 4 7 10 18 21 222 3 5 7 4 26 8 9 3 27 6 51 4 7 10 18 21 222 3 5 7 4 26 8 13 3 25 6 32 10 13 20 2511 6 10 16 14 56 17 154 2 211 12 14 1519 1410 68 4 23 10 16 18 21 22 29 309 13 16 154 22 4 74 214 15 14 520 1 15 1 12 5 11 | Output: 5 4 5 8 2 7 11
|
Medium
| 4 | 938 | 1,085 | 90 | 19 |
|
1,325 |
C
|
1325C
|
C. Ehab and Path-etic MEXs
| 1,500 |
constructive algorithms; dfs and similar; greedy; trees
|
You are given a tree consisting of \(n\) nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between \(0\) and \(n-2\) inclusive. All the written labels are distinct. The largest value among \(MEX(u,v)\) over all pairs of nodes \((u,v)\) is as small as possible. Here, \(MEX(u,v)\) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node \(u\) to node \(v\).
|
The first line contains the integer \(n\) (\(2 \le n \le 10^5\)) — the number of nodes in the tree.Each of the next \(n-1\) lines contains two space-separated integers \(u\) and \(v\) (\(1 \le u,v \le n\)) that mean there's an edge between nodes \(u\) and \(v\). It's guaranteed that the given graph is a tree.
|
Output \(n-1\) integers. The \(i^{th}\) of them will be the number written on the \(i^{th}\) edge (in the input order).
|
The tree from the second sample:
|
Input: 3 1 2 1 3 | Output: 0 1
|
Medium
| 4 | 483 | 310 | 119 | 13 |
2,013 |
D
|
2013D
|
D. Minimize the Difference
| 1,900 |
binary search; greedy
|
Zhan, tired after the contest, gave the only task that he did not solve during the contest to his friend, Sungat. However, he could not solve it either, so we ask you to try to solve this problem.You are given an array \(a_1, a_2, \ldots, a_n\) of length \(n\). We can perform any number (possibly, zero) of operations on the array.In one operation, we choose a position \(i\) (\(1 \leq i \leq n - 1\)) and perform the following action: \(a_i := a_i - 1\), and \(a_{i+1} := a_{i+1} + 1\). Find the minimum possible value of \(\max(a_1, a_2, \ldots, a_n) - \min(a_1, a_2, \ldots, a_n)\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^5\)). The description of the test cases follows.The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 2 \cdot 10^5\)).The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 10^{12}\)).The sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, output a single integer: the minimum possible value of \(\max(a_1, a_2, \ldots, a_n) - \min(a_1, a_2, \ldots, a_n)\).
|
In the third testcase, you can perform the operation twice with \(i = 1\).After that, the array is \(a = [2, 3, 2, 3]\), and \(\max(2, 3, 2, 3) - \min(2, 3, 2, 3) = 3 - 2 = 1\).
|
Input: 51131 2 344 1 2 344 2 3 155 14 4 10 2 | Output: 0 2 1 1 3
|
Hard
| 2 | 586 | 437 | 137 | 20 |
2,056 |
B
|
2056B
|
B. Find the Permutation
| 1,300 |
brute force; dfs and similar; graphs; implementation; sortings
|
You are given an undirected graph with \(n\) vertices, labeled from \(1\) to \(n\). This graph encodes a hidden permutation\(^{\text{∗}}\) \(p\) of size \(n\). The graph is constructed as follows: For every pair of integers \(1 \le i < j \le n\), an undirected edge is added between vertex \(p_i\) and vertex \(p_j\) if and only if \(p_i < p_j\). Note that the edge is not added between vertices \(i\) and \(j\), but between the vertices of their respective elements. Refer to the notes section for better understanding. Your task is to reconstruct and output the permutation \(p\). It can be proven that permutation \(p\) can be uniquely determined.\(^{\text{∗}}\)A permutation of length \(n\) 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 500\)). The description of the test cases follows. The first line of each test case contains a single integer \(n\) (\(1 \le n \le 1000\)).The \(i\)-th of the next \(n\) lines contains a string of \(n\) characters \(g_{i, 1}g_{i, 2}\ldots g_{i, n}\) (\(g_{i, j} = \mathtt{0}\) or \(g_{i, j} = \mathtt{1}\)) — the adjacency matrix. \(g_{i, j} = \mathtt{1}\) if and only if there is an edge between vertex \(i\) and vertex \(j\).It is guaranteed that there exists a permutation \(p\) which generates the given graph. It is also guaranteed that the graph is undirected and has no self-loops, meaning \(g_{i, j} = g_{j, i}\) and \(g_{i, i} = \mathtt{0}\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(1000\).
|
For each test case, output \(n\) integers \(p_1, p_2, \ldots, p_n\) representing the reconstructed permutation.
|
In the first case \(p = [1]\). Since there are no pairs \(1 \le i < j \le n\), there are no edges in the graph.The graph in the second case is shown below. For example, when we choose \(i = 3\) and \(j = 4\), we add an edge between vertices \(p_i = 1\) and \(p_j = 3\), because \(p_i < p_j\). However, when we choose \(i = 2\) and \(j = 3\), \(p_i = 2\) and \(p_j = 1\), so \(p_i < p_j\) doesn't hold. Therefore, we don't add an edge between \(2\) and \(1\).In the third case, there are no edges in the graph, so there are no pairs of integers \(1 \le i < j \le n\) such that \(p_i < p_j\). Therefore, \(p = [6, 5, 4, 3, 2, 1]\).
|
Input: 310500101001011100100001111106000000000000000000000000000000000000 | Output: 1 4 2 1 3 5 6 5 4 3 2 1
|
Easy
| 5 | 989 | 845 | 111 | 20 |
301 |
E
|
301E
|
E. Yaroslav and Arrangements
| 2,800 |
dp
|
Yaroslav calls an array of r integers a1, a2, ..., ar good, if it meets the following conditions: |a1 - a2| = 1, |a2 - a3| = 1, ..., |ar - 1 - ar| = 1, |ar - a1| = 1, at that . An array of integers b1, b2, ..., br is called great, if it meets the following conditions: The elements in it do not decrease (bi ≤ bi + 1). If the inequalities 1 ≤ r ≤ n and 1 ≤ bi ≤ m hold. If we can rearrange its elements and get at least one and at most k distinct good arrays. Yaroslav has three integers n, m, k. He needs to count the number of distinct great arrays. Help Yaroslav! As the answer may be rather large, print the remainder after dividing it by 1000000007 (109 + 7).Two arrays are considered distinct if there is a position in which they have distinct numbers.
|
The single line contains three integers n, m, k (1 ≤ n, m, k ≤ 100).
|
In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7).
|
Input: 1 1 1 | Output: 0
|
Master
| 1 | 758 | 68 | 109 | 3 |
|
1,119 |
H
|
1119H
|
H. Triple
| 3,200 |
fft; math
|
You have received your birthday gifts — \(n\) triples of integers! The \(i\)-th of them is \(\lbrace a_{i}, b_{i}, c_{i} \rbrace\). All numbers are greater than or equal to \(0\), and strictly smaller than \(2^{k}\), where \(k\) is a fixed integer.One day, you felt tired playing with triples. So you came up with three new integers \(x\), \(y\), \(z\), and then formed \(n\) arrays. The \(i\)-th array consists of \(a_i\) repeated \(x\) times, \(b_i\) repeated \(y\) times and \(c_i\) repeated \(z\) times. Thus, each array has length \((x + y + z)\).You want to choose exactly one integer from each array such that the XOR (bitwise exclusive or) of them is equal to \(t\). Output the number of ways to choose the numbers for each \(t\) between \(0\) and \(2^{k} - 1\), inclusive, modulo \(998244353\).
|
The first line contains two integers \(n\) and \(k\) (\(1 \leq n \leq 10^{5}\), \(1 \leq k \leq 17\)) — the number of arrays and the binary length of all numbers.The second line contains three integers \(x\), \(y\), \(z\) (\(0 \leq x,y,z \leq 10^{9}\)) — the integers you chose.Then \(n\) lines follow. The \(i\)-th of them contains three integers \(a_{i}\), \(b_{i}\) and \(c_{i}\) (\(0 \leq a_{i} , b_{i} , c_{i} \leq 2^{k} - 1\)) — the integers forming the \(i\)-th array.
|
Print a single line containing \(2^{k}\) integers. The \(i\)-th of them should be the number of ways to choose exactly one integer from each array so that their XOR is equal to \(t = i-1\) modulo \(998244353\).
|
In the first example, the array we formed is \((1, 0, 0, 1, 1, 1)\), we have two choices to get \(0\) as the XOR and four choices to get \(1\).In the second example, two arrays are \((0, 1, 1, 2)\) and \((1, 2, 2, 3)\). There are sixteen \((4 \cdot 4)\) choices in total, \(4\) of them (\(1 \oplus 1\) and \(2 \oplus 2\), two options for each) give \(0\), \(2\) of them (\(0 \oplus 1\) and \(2 \oplus 3\)) give \(1\), \(4\) of them (\(0 \oplus 2\) and \(1 \oplus 3\), two options for each) give \(2\), and finally \(6\) of them (\(0 \oplus 3\), \(2 \oplus 1\) and four options for \(1 \oplus 2\)) give \(3\).
|
Input: 1 1 1 2 3 1 0 1 | Output: 2 4
|
Master
| 2 | 803 | 475 | 210 | 11 |
1,394 |
C
|
1394C
|
C. Boboniu and String
| 2,600 |
binary search; geometry; ternary search
|
Boboniu defines BN-string as a string \(s\) of characters 'B' and 'N'.You can perform the following operations on the BN-string \(s\): Remove a character of \(s\). Remove a substring ""BN"" or ""NB"" of \(s\). Add a character 'B' or 'N' to the end of \(s\). Add a string ""BN"" or ""NB"" to the end of \(s\). Note that a string \(a\) is a substring of a string \(b\) if \(a\) can be obtained from \(b\) by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Boboniu thinks that BN-strings \(s\) and \(t\) are similar if and only if: \(|s|=|t|\). There exists a permutation \(p_1, p_2, \ldots, p_{|s|}\) such that for all \(i\) (\(1\le i\le |s|\)), \(s_{p_i}=t_i\). Boboniu also defines \(\text{dist}(s,t)\), the distance between \(s\) and \(t\), as the minimum number of operations that makes \(s\) similar to \(t\).Now Boboniu gives you \(n\) non-empty BN-strings \(s_1,s_2,\ldots, s_n\) and asks you to find a non-empty BN-string \(t\) such that the maximum distance to string \(s\) is minimized, i.e. you need to minimize \(\max_{i=1}^n \text{dist}(s_i,t)\).
|
The first line contains a single integer \(n\) (\(1\le n\le 3\cdot 10^5\)).Each of the next \(n\) lines contains a string \(s_i\) (\(1\le |s_i| \le 5\cdot 10^5\)). It is guaranteed that \(s_i\) only contains 'B' and 'N'. The sum of \(|s_i|\) does not exceed \(5\cdot 10^5\).
|
In the first line, print the minimum \(\max_{i=1}^n \text{dist}(s_i,t)\).In the second line, print the suitable \(t\).If there are several possible \(t\)'s, you can print any.
|
In the first example \(\text{dist(B,BN)}=\text{dist(N,BN)}=1\), \(\text{dist(BN,BN)}=0\). So the maximum distance is \(1\).
|
Input: 3 B N BN | Output: 1 BN
|
Expert
| 3 | 1,143 | 274 | 175 | 13 |
1,209 |
B
|
1209B
|
B. Koala and Lights
| 1,300 |
implementation; math; number theory
|
It is a holiday season, and Koala is decorating his house with cool lights! He owns \(n\) lights, all of which flash periodically.After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters \(a_i\) and \(b_i\). Light with parameters \(a_i\) and \(b_i\) will toggle (on to off, or off to on) every \(a_i\) seconds starting from the \(b_i\)-th second. In other words, it will toggle at the moments \(b_i\), \(b_i + a_i\), \(b_i + 2 \cdot a_i\) and so on.You know for each light whether it's initially on or off and its corresponding parameters \(a_i\) and \(b_i\). Koala is wondering what is the maximum number of lights that will ever be on at the same time. So you need to find that out. Here is a graphic for the first example.
|
The first line contains a single integer \(n\) (\(1 \le n \le 100\)), the number of lights.The next line contains a string \(s\) of \(n\) characters. The \(i\)-th character is ""1"", if the \(i\)-th lamp is initially on. Otherwise, \(i\)-th character is ""0"".The \(i\)-th of the following \(n\) lines contains two integers \(a_i\) and \(b_i\) (\(1 \le a_i, b_i \le 5\)) — the parameters of the \(i\)-th light.
|
Print a single integer — the maximum number of lights that will ever be on at the same time.
|
For first example, the lamps' states are shown in the picture above. The largest number of simultaneously on lamps is \(2\) (e.g. at the moment \(2\)).In the second example, all lights are initially on. So the answer is \(4\).
|
Input: 3 101 3 3 3 2 3 1 | Output: 2
|
Easy
| 3 | 781 | 410 | 92 | 12 |
1,248 |
A
|
1248A
|
A. Integer Points
| 1,000 |
geometry; math
|
DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew \(n\) distinct lines, given by equations \(y = x + p_i\) for some distinct \(p_1, p_2, \ldots, p_n\).Then JLS drew on the same paper sheet \(m\) distinct lines given by equations \(y = -x + q_i\) for some distinct \(q_1, q_2, \ldots, q_m\).DLS and JLS are interested in counting how many line pairs have integer intersection points, i.e. points with both coordinates that are integers. Unfortunately, the lesson will end up soon, so DLS and JLS are asking for your help.
|
The first line contains one integer \(t\) (\(1 \le t \le 1000\)), the number of test cases in the input. Then follow the test case descriptions.The first line of a test case contains an integer \(n\) (\(1 \le n \le 10^5\)), the number of lines drawn by DLS.The second line of a test case contains \(n\) distinct integers \(p_i\) (\(0 \le p_i \le 10^9\)) describing the lines drawn by DLS. The integer \(p_i\) describes a line given by the equation \(y = x + p_i\).The third line of a test case contains an integer \(m\) (\(1 \le m \le 10^5\)), the number of lines drawn by JLS.The fourth line of a test case contains \(m\) distinct integers \(q_i\) (\(0 \le q_i \le 10^9\)) describing the lines drawn by JLS. The integer \(q_i\) describes a line given by the equation \(y = -x + q_i\).The sum of the values of \(n\) over all test cases in the input does not exceed \(10^5\). Similarly, the sum of the values of \(m\) over all test cases in the input does not exceed \(10^5\).In hacks it is allowed to use only one test case in the input, so \(t=1\) should be satisfied.
|
For each test case in the input print a single integer — the number of line pairs with integer intersection points.
|
The picture shows the lines from the first test case of the example. Black circles denote intersection points with integer coordinates.
|
Input: 3 3 1 3 2 2 0 3 1 1 1 1 1 2 1 1 | Output: 3 1 0
|
Beginner
| 2 | 581 | 1,069 | 115 | 12 |
1,436 |
E
|
1436E
|
E. Complicated Computations
| 2,400 |
binary search; data structures; two pointers
|
In this problem MEX of a certain array is the smallest positive integer not contained in this array.Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today.You are given an array \(a\) of length \(n\). Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers.An array \(b\) is a subarray of an array \(a\), if \(b\) can be obtained from \(a\) by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself.Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays!
|
The first line contains a single integer \(n\) (\(1 \le n \le 10^5\)) — the length of the array. The next line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le n\)) — the elements of the array.
|
Print a single integer — the MEX of MEXes of all subarrays.
|
Input: 3 1 3 2 | Output: 3
|
Expert
| 3 | 862 | 211 | 59 | 14 |
|
2,066 |
B
|
2066B
|
B. White Magic
| 1,900 |
constructive algorithms; data structures; dp; greedy; implementation
|
We call a sequence \(a_1, a_2, \ldots, a_n\) magical if for all \(1 \leq i \leq n-1\) it holds that: \(\operatorname{min}(a_1, \ldots, a_i) \geq \operatorname{mex}(a_{i+1}, \ldots, a_n)\). In particular, any sequence of length \(1\) is considered magical.The minimum excluded (MEX) of a collection of integers \(a_1, a_2, \ldots, a_k\) is defined as the smallest non-negative integer \(t\) which does not occur in the collection \(a\). You are given a sequence \(a\) of \(n\) non-negative integers. Find the maximum possible length of a magical subsequence\(^{\text{∗}}\) of the sequence \(a\).\(^{\text{∗}}\)A sequence \(a\) is a subsequence of a sequence \(b\) if \(a\) can be obtained from \(b\) by the deletion of several (possibly, zero or all) element from arbitrary positions.
|
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 an integer \(n\) (\(1 \leq n \leq 2 \cdot 10^5\)) — the length of the sequence \(a\).The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \leq a_i \leq 10^9\)) — the elements of the sequence \(a\).It is guaranteed that the sum of \(n\) across all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, output a single number — the maximum possible length of a magical subsequence of the sequence \(a\).
|
In the first test case, the sequence \([4, 3, 2, 1, 0]\) is magical, since: \(\operatorname{min}(4) = 4, \operatorname{mex}(3, 2, 1, 0) = 4\). \(4 \geq 4\) \(\operatorname{min}(4, 3) = 3, \operatorname{mex}(2, 1, 0) = 3\). \(3 \geq 3\) \(\operatorname{min}(4, 3, 2) = 2, \operatorname{mex}(1, 0) = 2\). \(2 \geq 2\) \(\operatorname{min}(4, 3, 2, 1) = 1, \operatorname{mex}(0) = 1\). \(1 \geq 1\)In the second test case, the sequence \([4, 3, 3, 2, 1, 0]\) is not magical, since \(\operatorname{min}(4, 3) = 3, \operatorname{mex}(3, 2, 1, 0) = 4\), \(3 < 4\). However, the subsequence \([4, 3, 2, 1, 0]\) of this sequence is magical, so the answer is \(5\).
|
Input: 854 3 2 1 064 3 3 2 1 042 0 1 2177741000000000 1 7 920 121 240 1 0 1 | Output: 5 5 3 1 4 2 2 3
|
Hard
| 5 | 783 | 531 | 120 | 20 |
1,641 |
E
|
1641E
|
E. Special Positions
| 3,300 |
combinatorics; divide and conquer; fft; math
|
You are given an array \(a\) of length \(n\). Also you are given \(m\) distinct positions \(p_1, p_2, \ldots, p_m\) (\(1 \leq p_i \leq n\)).A non-empty subset of these positions \(T\) is randomly selected with equal probability and the following value is calculated: $$$\(\sum_{i=1}^{n} (a_i \cdot \min_{j \in T} \left|i - j\right|).\)\( In other word, for each index of the array, \)a_i\( and the distance to the closest chosen position are multiplied, and then these values are summed up.Find the expected value of this sum.This value must be found modulo \)998\,244\,353\(. More formally, let \)M = 998\,244\,353\(. It can be shown that the answer can be represented as an irreducible fraction \)\frac{p}{q}\(, where \)p\( and \)q\( are integers and \)q \neq 0\( (mod \)M\(). Output the integer equal to \)p \cdot q^{-1}\( (mod \)M\(). In other words, output such integer \)x\( that \)0 \leq x < M\( and \)x \cdot q = p\( (mod \)M$$$).
|
The first line contains two integers \(n\) and \(m\) (\(1 \leq m \leq n \leq 10^5\)).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \leq a_i < 998\,244\,353\)).The third line contains \(m\) distinct integers \(p_1, p_2, \ldots, p_m\) (\(1 \leq p_i \le n\)).For every \(1 \leq i < m\) it is guaranteed that \(p_i < p_{i+1}\).
|
Print a single integer — the answer to the problem.
|
In the first test: If only \(1\) is choosen, than the value equals to \(1 \cdot 0 + 2 \cdot 1 + 3 \cdot 2 + 4 \cdot 3 = 20\). If only \(4\) is choosen, than the value equals to \(1 \cdot 3 + 2 \cdot 2 + 3 \cdot 1 + 4 \cdot 0 = 10\). If both positions are chosen, than the value equals to \(1 \cdot 0 + 2 \cdot 1 + 3 \cdot 1 + 4 \cdot 0 = 5\). The answer to the problem is \(\frac{20 + 10 + 5}{3} = \frac{35}{3} = 665\,496\,247\) (modulo \(998\,244\,353\)).
|
Input: 4 2 1 2 3 4 1 4 | Output: 665496247
|
Master
| 4 | 938 | 348 | 51 | 16 |
278 |
A
|
278A
|
A. Circle Line
| 800 |
implementation
|
The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dn - 1 is the distance between the n - 1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.
|
The first line contains integer n (3 ≤ n ≤ 100) — the number of stations on the circle line. The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 100) — the distances between pairs of neighboring stations. The third line contains two integers s and t (1 ≤ s, t ≤ n) — the numbers of stations, between which you need to find the shortest distance. These numbers can be the same.The numbers in the lines are separated by single spaces.
|
Print a single number — the length of the shortest path between stations number s and t.
|
In the first sample the length of path 1 → 2 → 3 equals 5, the length of path 1 → 4 → 3 equals 13.In the second sample the length of path 4 → 1 is 100, the length of path 4 → 3 → 2 → 1 is 15.In the third sample the length of path 3 → 1 is 1, the length of path 3 → 2 → 1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0.
|
Input: 42 3 4 91 3 | Output: 5
|
Beginner
| 1 | 482 | 442 | 88 | 2 |
1,982 |
B
|
1982B
|
B. Collatz Conjecture
| 1,200 |
brute force; implementation; math; number theory
|
Recently, the first-year student Maxim learned about the Collatz conjecture, but he didn't pay much attention during the lecture, so he believes that the following process is mentioned in the conjecture:There is a variable \(x\) and a constant \(y\). The following operation is performed \(k\) times: increase \(x\) by \(1\), then while the number \(x\) is divisible by \(y\), divide it by \(y\). Note that both of these actions are performed sequentially within one operation.For example, if the number \(x = 16\), \(y = 3\), and \(k = 2\), then after one operation \(x\) becomes \(17\), and after another operation \(x\) becomes \(2\), because after adding one, \(x = 18\) is divisible by \(3\) twice.Given the initial values of \(x\), \(y\), and \(k\), Maxim wants to know what is the final value of \(x\).
|
Each test consists of multiple test cases. The first line contains an integer \(t\) (\(1 \le t \le 10^{4}\)) — the number of test cases. Then follows the description of the test cases.The only line of each test case contains three integers \(x\), \(y\), and \(k\) (\(1 \le x, k \le 10^{9}\), \(2 \le y \le 10^{9}\)) — the initial variable, constant and the number of operations.
|
For each test case, output a single integer — the number obtained after applying \(k\) operations.
|
In the first test case, there is only one operation applied to \(x = 1\), resulting in \(x\) becoming \(2\).In the second test case, for \(x = 2\), within one operation, one is added to \(x\) and it's divided by \(y = 3\), resulting in \(x\) becoming \(1\).In the third test case, \(x\) changes as follows: After the first operation, \(x = 1\), because \(24 + 1 = 25\) and \(25\) is divisible by \(y = 5\) twice within one operation. After the second operation, \(x = 2\). After the third operation, \(x = 3\). After the fourth operation, \(x = 4\). After the fifth operation, \(x = 1\).
|
Input: 131 3 12 3 124 5 516 3 22 2 11337 18 11 2 14413312345678 3 10998244353 2 998244353998244353 123456789 998244352998244354 998241111 998244352998244355 2 99824431000000000 1000000000 1000000000 | Output: 2 1 1 2 3 1338 1 16936 1 21180097 6486 1 2
|
Easy
| 4 | 809 | 378 | 98 | 19 |
1,365 |
F
|
1365F
|
F. Swaps Again
| 2,100 |
constructive algorithms; implementation; sortings
|
Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid.Each test case consists of an integer \(n\) and two arrays \(a\) and \(b\), of size \(n\). If after some (possibly zero) operations described below, array \(a\) can be transformed into array \(b\), the input is said to be valid. Otherwise, it is invalid.An operation on array \(a\) is: select an integer \(k\) \((1 \le k \le \lfloor\frac{n}{2}\rfloor)\) swap the prefix of length \(k\) with the suffix of length \(k\) For example, if array \(a\) initially is \(\{1, 2, 3, 4, 5, 6\}\), after performing an operation with \(k = 2\), it is transformed into \(\{5, 6, 3, 4, 1, 2\}\).Given the set of test cases, help them determine if each one is valid or invalid.
|
The first line contains one integer \(t\) \((1 \le t \le 500)\) — the number of test cases. The description of each test case is as follows.The first line of each test case contains a single integer \(n\) \((1 \le n \le 500)\) — the size of the arrays.The second line of each test case contains \(n\) integers \(a_1\), \(a_2\), ..., \(a_n\) \((1 \le a_i \le 10^9)\) — elements of array \(a\).The third line of each test case contains \(n\) integers \(b_1\), \(b_2\), ..., \(b_n\) \((1 \le b_i \le 10^9)\) — elements of array \(b\).
|
For each test case, print ""Yes"" if the given input is valid. Otherwise print ""No"".You may print the answer in any case.
|
For the first test case, we can swap prefix \(a[1:1]\) with suffix \(a[2:2]\) to get \(a=[2, 1]\).For the second test case, \(a\) is already equal to \(b\).For the third test case, it is impossible since we cannot obtain \(3\) in \(a\).For the fourth test case, we can first swap prefix \(a[1:1]\) with suffix \(a[4:4]\) to obtain \(a=[2, 2, 3, 1]\). Now we can swap prefix \(a[1:2]\) with suffix \(a[3:4]\) to obtain \(a=[3, 1, 2, 2]\).For the fifth test case, it is impossible to convert \(a\) to \(b\).
|
Input: 5 2 1 2 2 1 3 1 2 3 1 2 3 3 1 2 4 1 3 4 4 1 2 3 2 3 1 2 2 3 1 2 3 1 3 2 | Output: yes yes No yes No
|
Hard
| 3 | 800 | 531 | 123 | 13 |
1,066 |
F
|
1066F
|
F. Yet another 2D Walking
| 2,100 |
dp
|
Maksim walks on a Cartesian plane. Initially, he stands at the point \((0, 0)\) and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point \((0, 0)\), he can go to any of the following points in one move: \((1, 0)\); \((0, 1)\); \((-1, 0)\); \((0, -1)\). There are also \(n\) distinct key points at this plane. The \(i\)-th point is \(p_i = (x_i, y_i)\). It is guaranteed that \(0 \le x_i\) and \(0 \le y_i\) and there is no key point \((0, 0)\).Let the first level points be such points that \(max(x_i, y_i) = 1\), the second level points be such points that \(max(x_i, y_i) = 2\) and so on. Maksim wants to visit all the key points. But he shouldn't visit points of level \(i + 1\) if he does not visit all the points of level \(i\). He starts visiting the points from the minimum level of point from the given set.The distance between two points \((x_1, y_1)\) and \((x_2, y_2)\) is \(|x_1 - x_2| + |y_1 - y_2|\) where \(|v|\) is the absolute value of \(v\).Maksim wants to visit all the key points in such a way that the total distance he walks will be minimum possible. Your task is to find this distance.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
|
The first line of the input contains one integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) — the number of key points.Each of the next \(n\) lines contains two integers \(x_i\), \(y_i\) (\(0 \le x_i, y_i \le 10^9\)) — \(x\)-coordinate of the key point \(p_i\) and \(y\)-coordinate of the key point \(p_i\). It is guaranteed that all the points are distinct and the point \((0, 0)\) is not in this set.
|
Print one integer — the minimum possible total distance Maksim has to travel if he needs to visit all key points in a way described above.
|
The picture corresponding to the first example: There is one of the possible answers of length \(15\).The picture corresponding to the second example: There is one of the possible answers of length \(9\).
|
Input: 82 21 42 33 13 41 14 31 2 | Output: 15
|
Hard
| 1 | 1,276 | 396 | 138 | 10 |
2,082 |
A
|
2082A
|
A. Binary Matrix
| 800 |
constructive algorithms; greedy
|
A matrix is called binary if all its elements are either \(0\) or \(1\).Ecrade calls a binary matrix \(A\) good if the following two properties hold: The bitwise XOR of all numbers in each row of matrix \(A\) is equal to \(0\). The bitwise XOR of all numbers in each column of matrix \(A\) is equal to \(0\). Ecrade has a binary matrix of size \(n \cdot m\). He is interested in the minimum number of elements that need to be changed for the matrix to become good.However, it seems a little difficult, so please help him!
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 400\)). The description of the test cases follows. The first line of each test case contains two integers \(n, m\) (\(1 \le n, m \le 100\)).This is followed by \(n\) lines, each containing exactly \(m\) characters consisting only of \(0\) and \(1\), describing the elements of Ecrade's matrix.It is guaranteed that the sum of \(n \cdot m\) across all test cases does not exceed \(5 \cdot 10^4\).
|
For each test case, output a single integer, the minimum number of elements that need to be changed.
|
In the first test case, he needs to change 2 elements to obtain the following matrix \(\begin{pmatrix}1&1&0\\1&0&1\\0&1&1\end{pmatrix}\).In the second test case, he can make no changes to obtain the following matrix \(\begin{pmatrix}0&0&0\\0&0&0\\0&0&0\end{pmatrix}\).In the third test case, he needs to change 3 elements to obtain the following matrix \(\begin{pmatrix}1&0&1\\0&0&0\\1&0&1\end{pmatrix}\).
|
Input: 73 30101010103 30000000003 31000100013 31010100003 30000100001 401014 10101 | Output: 2 0 3 3 1 2 2
|
Beginner
| 2 | 521 | 505 | 100 | 20 |
2,086 |
C
|
2086C
|
C. Disappearing Permutation
| 1,300 |
dfs and similar; dp; dsu; graphs; greedy; implementation
|
A permutation of integers from \(1\) to \(n\) is an array of size \(n\) where each integer from \(1\) to \(n\) appears exactly once.You are given a permutation \(p\) of integers from \(1\) to \(n\). You have to process \(n\) queries. During the \(i\)-th query, you replace \(p_{d_i}\) with \(0\). Each element is replaced with \(0\) exactly once. The changes made in the queries are saved, that is, after the \(i\)-th query, all integers \(p_{d_1}, p_{d_2}, \dots, p_{d_i}\) are zeroes.After each query, you have to find the minimum number of operations required to fix the array; in other words, to transform the current array into any permutation of integers from \(1\) to \(n\) (possibly into the original permutation \(p\), possibly into some other permutation).The operation you can perform to fix the array is the following one: choose the integer \(i\) from \(1\) to \(n\), replace the \(i\)-th element of the array with \(i\). Note that the answer for each query is calculated independently, meaning you do not actually apply any operations, just calculate the minimum number of operations.
|
Each test consists of several test cases. The first line contains one integer \(t\) (\(1 \le t \le 10^{4}\)) — the number of test cases. Then the test cases follow.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 \(p_1, p_2, \dots, p_n\) (\(1 \le p_{i} \le n\)) — the original permutation. All \(p_i\) are distinct.The third line of each test case contains \(n\) integers \(d_1, d_2, \dots, d_n\) (\(1 \le d_{i} \le n\)). All \(d_{i}\) are distinct.Additional constraint on the input: the sum of \(n\) across all test cases does not exceed \(2 \cdot 10^{5}\).
|
For each test case, output a line containing \(n\) integers, where the \(i\)-th integer should be equal to the minimum number of operations required to fix the array which was obtained after the \(i\)-th query (i.e., the permutation \(p\) where all integers \(p_{d_1}, p_{d_2}, \dots, p_{d_i}\) are replaced by zeroes).
|
In the first test case, after each query, every integer which was replaced by \(0\) can be restored by one operation.In the second test case, you can act as follows: Query \(1\): \(p = [4, 5, 3, 0, 2]\), it can be transformed into \([{\color{red}1}, 5, 3, {\color{red}4}, 2]\). Query \(2\): \(p = [4, 5, 3, 0, 0]\), it can be transformed into \([{\color{red}1}, {\color{red}2}, 3, {\color{red}4}, {\color{red}5}]\). Query \(3\): \(p = [0, 5, 3, 0, 0]\), it can be transformed into \([{\color{red}1}, {\color{red}2}, 3, {\color{red}4}, {\color{red}5}]\). Query \(4\): \(p = [0, 5, 0, 0, 0]\), it can be transformed into \([{\color{red}1}, {\color{red}2}, {\color{red}3}, {\color{red}4}, {\color{red}5}]\). Query \(5\): \(p = [0, 0, 0, 0, 0]\), it can be transformed into \([{\color{red}1}, {\color{red}2}, {\color{red}3}, {\color{red}4}, {\color{red}5}]\). The numbers that were changed are highlighted in red.
|
Input: 331 2 33 2 154 5 3 1 24 5 1 3 274 3 1 2 7 5 61 2 3 4 5 6 7 | Output: 1 2 3 2 4 4 5 5 4 4 4 4 7 7 7
|
Easy
| 6 | 1,098 | 658 | 319 | 20 |
1,737 |
C
|
1737C
|
C. Ela and Crickets
| 1,500 |
constructive algorithms; games; implementation; math
|
Ela likes Chess a lot. During breaks, she usually challenges her co-worker in DTL to some chess games. She's not an expert at classic chess, but she's very interested in Chess variants, where she has to adapt to new rules and test her tactical mindset to win the game.The problem, which involves a non-standard chess pieces type that is described below, reads: given \(3\) white crickets on a \(n \cdot n\) board, arranged in an ""L"" shape next to each other, there are no other pieces on the board. Ela wants to know with a finite number of moves, can she put any white cricket on the square on row \(x\), column \(y\)?An ""L""-shape piece arrangement can only be one of the below: For simplicity, we describe the rules for crickets on the board where only three white crickets are. It can move horizontally, vertically, or diagonally, but only to a square in some direction that is immediately after another cricket piece (so that it must jump over it). If the square immediately behind the piece is unoccupied, the cricket will occupy the square. Otherwise (when the square is occupied by another cricket, or does not exist), the cricket isn't allowed to make such a move.See an example of valid crickets' moves on the pictures in the Note section.
|
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 \(n\) (\(4 \le n \le 10^5\)) — denotes the size of the chessboard.The second line of each test case contains 6 numbers: \(r_1\), \(c_1\), \(r_2\), \(c_2\), \(r_3\), \(c_3\) (\(1 \le r_1, c_1, r_2, c_2, r_3, c_3 \le n\)) — coordinates of the crickets. The input ensures that the three crickets are arranged in an ""L"" shape that the legend stated.The third line of each test case contains 2 numbers: \(x\), \(y\) (\(1 \le x, y \le n\)) — coordinates of the target square.
|
For each test case, print ""YES"" or ""NO"" to denotes whether Ela can put a cricket on the target square.
|
Here's the solution for the first test case. The red square denotes where the crickets need to reach. Note that in chess horizontals are counted from bottom to top, as well as on this picture.
|
Input: 687 2 8 2 7 15 182 2 1 2 2 15 582 2 1 2 2 16 681 1 1 2 2 15 582 2 1 2 2 18 888 8 8 7 7 84 8 | Output: YES NO YES NO YES YES
|
Medium
| 4 | 1,252 | 674 | 106 | 17 |
1,623 |
D
|
1623D
|
D. Robot Cleaner Revisit
| 2,300 |
implementation; math; probabilities
|
The statement of this problem shares a lot with problem A. The differences are that in this problem, the probability is introduced, and the constraint is different.A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of \(n\) rows and \(m\) columns. The rows of the floor are numbered from \(1\) to \(n\) from top to bottom, and columns of the floor are numbered from \(1\) to \(m\) from left to right. The cell on the intersection of the \(r\)-th row and the \(c\)-th column is denoted as \((r,c)\). The initial position of the robot is \((r_b, c_b)\).In one second, the robot moves by \(dr\) rows and \(dc\) columns, that is, after one second, the robot moves from the cell \((r, c)\) to \((r + dr, c + dc)\). Initially \(dr = 1\), \(dc = 1\). If there is a vertical wall (the left or the right walls) in the movement direction, \(dc\) is reflected before the movement, so the new value of \(dc\) is \(-dc\). And if there is a horizontal wall (the upper or lower walls), \(dr\) is reflected before the movement, so the new value of \(dr\) is \(-dr\).Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at \((r_d, c_d)\). The job of the robot is to clean that dirty cell. After a lot of testings in problem A, the robot is now broken. It cleans the floor as described above, but at each second the cleaning operation is performed with probability \(\frac p {100}\) only, and not performed with probability \(1 - \frac p {100}\). The cleaning or not cleaning outcomes are independent each second.Given the floor size \(n\) and \(m\), the robot's initial position \((r_b, c_b)\) and the dirty cell's position \((r_d, c_d)\), find the expected time for the robot to do its job.It can be shown that the answer can be expressed as an irreducible fraction \(\frac x y\), where \(x\) and \(y\) are integers and \(y \not \equiv 0 \pmod{10^9 + 7} \). Output the integer equal to \(x \cdot y^{-1} \bmod (10^9 + 7)\). In other words, output such an integer \(a\) that \(0 \le a < 10^9 + 7\) and \(a \cdot y \equiv x \pmod {10^9 + 7}\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10\)). Description of the test cases follows.A test case consists of only one line, containing \(n\), \(m\), \(r_b\), \(c_b\), \(r_d\), \(c_d\), and \(p\) (\(4 \le n \cdot m \le 10^5\), \(n, m \ge 2\), \(1 \le r_b, r_d \le n\), \(1 \le c_b, c_d \le m\), \(1 \le p \le 99\)) — the sizes of the room, the initial position of the robot, the position of the dirt cell and the probability of cleaning in percentage.
|
For each test case, print a single integer — the expected time for the robot to clean the dirty cell, modulo \(10^9 + 7\).
|
In the first test case, the robot has the opportunity to clean the dirty cell every second. Using the geometric distribution, we can find out that with the success rate of \(25\%\), the expected number of tries to clear the dirty cell is \(\frac 1 {0.25} = 4\). But because the first moment the robot has the opportunity to clean the cell is before the robot starts moving, the answer is \(3\). Illustration for the first example. The blue arc is the robot. The red star is the target dirt cell. The purple square is the initial position of the robot. Each second the robot has an opportunity to clean a row and a column, denoted by yellow stripes. In the second test case, the board size and the position are different, but the robot still has the opportunity to clean the dirty cell every second, and it has the same probability of cleaning. Therefore the answer is the same as in the first example. Illustration for the second example. The third and the fourth case are almost the same. The only difference is that the position of the dirty cell and the robot are swapped. But the movements in both cases are identical, hence the same result.
|
Input: 6 2 2 1 1 2 1 25 3 3 1 2 2 2 25 10 10 1 1 10 10 75 10 10 10 10 1 1 75 5 5 1 3 2 2 10 97 98 3 5 41 43 50 | Output: 3 3 15 15 332103349 99224487
|
Expert
| 3 | 2,202 | 520 | 122 | 16 |
48 |
E
|
48E
|
E. Ivan the Fool VS Gorynych the Dragon
| 2,100 |
dp; games; graphs
|
Once upon a time in a kingdom far, far away… Okay, let’s start at the point where Ivan the Fool met Gorynych the Dragon. Ivan took out his magic sword and the battle began. First Gorynych had h heads and t tails. With each strike of the sword Ivan can either cut off several heads (from 1 to n, but not more than Gorynych has at the moment), or several tails (from 1 to m, but not more than Gorynych has at the moment). At the same time, horrible though it seems, Gorynych the Dragon can also grow new heads and tails. And the number of growing heads and tails is determined uniquely by the number of heads or tails cut by the current strike. When the total number of heads and tails exceeds R, Gorynych the Dragon strikes its final blow and destroys Ivan the Fool. That’s why Ivan aims to cut off all the dragon’s heads and tails as quickly as possible and win. The events can also develop in a third way: neither of the opponents can win over the other one and they will continue fighting forever.The tale goes like this; easy to say, hard to do. Your task is to write a program that will determine the battle’s outcome. Consider that Ivan strikes consecutively. After each blow Gorynych grows a number of new heads and tails depending on the number of cut ones. Gorynych the Dragon is defeated if after the blow he loses all his heads and tails and can’t grow new ones. Ivan fights in the optimal way (fools are lucky), i.e. if Ivan can win, he wins having struck the least number of blows; if it is impossible to defeat Gorynych, but is possible to resist him for an infinitely long period of time, then that’s the strategy Ivan chooses; if Gorynych wins in any case, Ivan aims to resist him for as long as possible.
|
The first line contains three integers h, t and R (0 ≤ h, t, R ≤ 200, 0 < h + t ≤ R) which represent the initial numbers of Gorynych’s heads and tails and the largest total number of heads and tails with which Gorynych the Dragon does not yet attack. The next line contains integer n (1 ≤ n ≤ 200). The next n contain pairs of non-negative numbers ""hi ti"" which represent the number of heads and the number of tails correspondingly, that will grow if Gorynych has i heads (1 ≤ i ≤ n) cut. The next line contains an integer m (1 ≤ m ≤ 200) and then — the description of Gorynych’s behavior when his tails are cut off in the format identical to the one described above. All the numbers in the input file do not exceed 200.
|
Print ""Ivan"" (without quotes) in the first line if Ivan wins, or ""Zmey"" (that means a dragon in Russian) if Gorynych the Dragon wins. In the second line print a single integer which represents the number of blows Ivan makes. If the battle will continue forever, print in the first line ""Draw"".
|
Input: 2 2 421 00 130 10 10 0 | Output: Ivan2
|
Hard
| 3 | 1,720 | 722 | 299 | 0 |
|
1,690 |
G
|
1690G
|
G. Count the Trains
| 2,000 |
binary search; data structures; greedy; sortings
|
There are \(n\) of independent carriages on the rails. The carriages are numbered from left to right from \(1\) to \(n\). The carriages are not connected to each other. The carriages move to the left, so that the carriage with number \(1\) moves ahead of all of them.The \(i\)-th carriage has its own engine, which can accelerate the carriage to \(a_i\) km/h, but the carriage cannot go faster than the carriage in front of it. See example for explanation.All carriages start moving to the left at the same time, and they naturally form trains. We will call trains — consecutive moving carriages having the same speed.For example, we have \(n=5\) carriages and array \(a = [10, 13, 5, 2, 6]\). Then the final speeds of the carriages will be \([10, 10, 5, 2, 2]\). Respectively, \(3\) of the train will be formed.There are also messages saying that some engine has been corrupted: message ""k d"" means that the speed of the \(k\)-th carriage has decreased by \(d\) (that is, there has been a change in the maximum speed of the carriage \(a_k = a_k - d\)). Messages arrive sequentially, the processing of the next message takes into account the changes from all previous messages.After each message determine the number of formed trains.
|
The first line of input data contains a single integer \(t\) (\(1 \le t \le 10^4\)) —the number of input test cases.This is followed by descriptions of the test cases.The first line of each test case is empty.The second line of the test case contains two integers \(n\) and \(m\) (\(1 \le n,m \le 10^5\)) —the number of carriages and the number of messages to slow down the carriage, respectively.The third line contains \(n\) integers: \(a_1, a_2, \dots, a_n\) (\(0 \le a_i \le 10^9\)) — the number \(a_i\) means that the carriage with number \(i\) can reach a speed of \(a_i\) km/h. The next \(m\) lines contain two integers \(k_j\) and \(d_j\) (\(1 \le k_j \le n\), \(0 \le d_j \le a_{k_j}\)) —this is the message that the speed of the carriage with number \(k_j\) has decreased by \(d_j\). In other words, there has been a change in its maximum speed \(a_{k_j} = a_{k_j} - d_j\). Note that at any time the speed of each carriage is non-negative. In other words, \(a_i \ge s_i\), where \(s_i\) —is the sum of such \(d_j\) that \(k_j=i\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\). Similarly, it is guaranteed that the sum of \(m\) over all test cases does not exceed \(10^5\).
|
Print \(t\) lines. On each line print the answer for the corresponding test case.For each test case print \(m\) numbers: the number of trains formed after each message.
|
For the first test case: Initially array \(a = [6, 2, 3, 7]\). After the first message, the array \(a = [6, 2, 1, 7]\). Accordingly, the speeds of the carriages are \([6, 2, 1, 1]\) and will form \(3\) of the train. After the second message the array \(a = [6, 2, 1, 0]\). Accordingly, the speeds of the carriages are \([6, 2, 1, 0]\), and \(4\) of the train will be formed. For the second test case: Initially, the array \(a = [10, 13, 5, 2, 6]\). After the first message, the array \(a = [10, 9, 5, 2, 6]\). Accordingly, the speeds of the carriages are equal: \([10, 9, 5, 2, 2]\), and \(4\) of the train will be formed. After the second message the array \(a = [10, 9, 5, 2, 4]\). Accordingly, the speeds of the carriages are \([10, 9, 5, 2, 2]\), and \(4\) of the train will be formed. After the third message the array \(a = [5, 9, 5, 2, 4]\). Accordingly, the speeds of the carriages are \([5, 5, 5, 2, 2]\), and \(2\) of the train will be formed. After the fourth message the array \(a = [5, 9, 3, 2, 4]\). Accordingly, the speeds of the carriages are \([5, 5, 3, 2, 2]\), and \(3\) of the train will be formed.
|
Input: 34 26 2 3 73 24 75 410 13 5 2 62 45 21 53 213 4769 514 336 173 181 373 519 338 985 709 729 702 16812 5816 2227 2335 117 | Output: 3 4 4 4 2 3 5 6 6 5
|
Hard
| 4 | 1,236 | 1,220 | 168 | 16 |
439 |
B
|
439B
|
B. Devu, the Dumb Guy
| 1,200 |
implementation; sortings
|
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.Let us say that his initial per chapter learning power of a subject is x hours. In other words he can learn a chapter of a particular subject in x hours.Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.You can teach him the n subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.Please be careful that answer might not fit in 32 bit data type.
|
The first line will contain two space separated integers n, x (1 ≤ n, x ≤ 105). The next line will contain n space separated integers: c1, c2, ..., cn (1 ≤ ci ≤ 105).
|
Output a single integer representing the answer to the problem.
|
Look at the first example. Consider the order of subjects: 1, 2. When you teach Devu the first subject, it will take him 3 hours per chapter, so it will take 12 hours to teach first subject. After teaching first subject, his per chapter learning time will be 2 hours. Now teaching him second subject will take 2 × 1 = 2 hours. Hence you will need to spend 12 + 2 = 14 hours.Consider the order of subjects: 2, 1. When you teach Devu the second subject, then it will take him 3 hours per chapter, so it will take 3 × 1 = 3 hours to teach the second subject. After teaching the second subject, his per chapter learning time will be 2 hours. Now teaching him the first subject will take 2 × 4 = 8 hours. Hence you will need to spend 11 hours.So overall, minimum of both the cases is 11 hours.Look at the third example. The order in this example doesn't matter. When you teach Devu the first subject, it will take him 3 hours per chapter. When you teach Devu the second subject, it will take him 2 hours per chapter. When you teach Devu the third subject, it will take him 1 hours per chapter. In total it takes 6 hours.
|
Input: 2 34 1 | Output: 11
|
Easy
| 2 | 991 | 166 | 63 | 4 |
2,057 |
E2
|
2057E2
|
E2. Another Exercise on Graphs (hard version)
| 2,500 |
binary search; dfs and similar; dp; dsu; graphs; shortest paths; sortings
|
This is the hard version of the problem. The difference between the versions is that in this version, there is no additional constraint on \(m\). You can hack only if you solved all versions of this problem. Recently, the instructors of ""T-generation"" needed to create a training contest. They were missing one problem, and there was not a single problem on graphs in the contest, so they came up with the following problem.You are given a connected weighted undirected graph with \(n\) vertices and \(m\) edges, which does not contain self-loops or multiple edges.There are \(q\) queries of the form \((a, b, k)\): among all paths from vertex \(a\) to vertex \(b\), find the smallest \(k\)-th maximum weight of edges on the path\(^{\dagger}\).The instructors thought that the problem sounded very interesting, but there is one catch. They do not know how to solve it. Help them and solve the problem, as there are only a few hours left until the contest starts.\(^{\dagger}\) Let \(w_1 \ge w_2 \ge \ldots \ge w_{h}\) be the weights of all edges in a path, in non-increasing order. The \(k\)-th maximum weight of the edges on this path is \(w_{k}\).
|
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 100\)) — the number of test cases. The description of the test cases follows.The first line of each set of test case contains three integers \(n, m\) and \(q\) (\(2 \le n \le 400\), \(n - 1 \le m \le \frac{n \cdot (n - 1)}{2}\), \(1 \le q \le 3 \cdot 10^5\)) — the number of vertices, the number of edges, and the number of questions, respectively.Each of the following \(m\) lines of each set of test case contains three integers \(v, u\) and \(w\) (\(1 \le v, u \le n\), \(1 \le w \le 10^9\)) — the ends of the next edge of the graph and its weight, respectively. It is guaranteed that the graph does not contain self-loops and multiple edges.Each of the following \(q\) lines of each set of test case contains three integers \(a, b\) and \(k\) (\(1 \le a, b \le n\), \(k \ge 1\)) — the next question. It is guaranteed that any path from vertex \(a\) to vertex \(b\) contains at least \(k\) edges.It is guaranteed that the sum of the values of \(n\) across all sets of test cases does not exceed \(400\).It is guaranteed that the sum of the values of \(q\) across all sets of test cases does not exceed \(3 \cdot 10^5\).
|
For each set of test case, output the answers to all questions.
|
In the first set of test cases, one of the optimal paths in the first query is the path \(1 \rightarrow 3 \rightarrow 4\); the \(2\)-nd maximum weight of the edges on this path is \(1\). In the second query, one of the optimal paths is \(2 \rightarrow 4 \rightarrow 3\); \(1\)-st maximum weight of the edges is \(2\).In the second set of input data, one of the optimal paths in the first query is the path \(1 \rightarrow 2 \rightarrow 4 \rightarrow 5 \rightarrow 6\); the \(3\)-rd maximum weight of the edges on this path is \(2\).
|
Input: 34 4 21 2 22 4 21 3 43 4 11 4 22 3 16 7 31 2 102 3 33 4 94 5 25 6 12 4 104 6 101 6 31 6 22 4 111 17 101 4 51 3 191 2 103 2 134 5 14 6 113 5 93 6 182 7 175 8 155 10 86 9 47 10 207 8 168 11 39 11 610 11 143 11 13 11 31 11 11 11 41 11 38 2 210 4 13 9 23 9 16 7 3 | Output: 1 2 2 9 9 11 3 11 1 3 10 8 4 11 4
|
Expert
| 7 | 1,151 | 1,224 | 63 | 20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.