contest_id
int32 1
2.13k
| index
stringclasses 62
values | problem_id
stringlengths 2
6
| title
stringlengths 0
67
| rating
int32 0
3.5k
| tags
stringlengths 0
139
| statement
stringlengths 0
6.96k
| input_spec
stringlengths 0
2.32k
| output_spec
stringlengths 0
1.52k
| note
stringlengths 0
5.06k
| sample_tests
stringlengths 0
1.02k
| difficulty_category
stringclasses 6
values | tag_count
int8 0
11
| statement_length
int32 0
6.96k
| input_spec_length
int16 0
2.32k
| output_spec_length
int16 0
1.52k
| contest_year
int16 0
21
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,395 |
B
|
1395B
|
B. Boboniu Plays Chess
| 1,100 |
constructive algorithms
|
Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.You are a new applicant for his company. Boboniu will test you with the following chess question:Consider a \(n\times m\) grid (rows are numbered from \(1\) to \(n\), and columns are numbered from \(1\) to \(m\)). You have a chess piece, and it stands at some cell \((S_x,S_y)\) which is not on the border (i.e. \(2 \le S_x \le n-1\) and \(2 \le S_y \le m-1\)).From the cell \((x,y)\), you can move your chess piece to \((x,y')\) (\(1\le y'\le m, y' \neq y\)) or \((x',y)\) (\(1\le x'\le n, x'\neq x\)). In other words, the chess piece moves as a rook. From the cell, you can move to any cell on the same row or column.Your goal is to visit each cell exactly once. Can you find a solution?Note that cells on the path between two adjacent cells in your route are not counted as visited, and it is not required to return to the starting point.
|
The only line of the input contains four integers \(n\), \(m\), \(S_x\) and \(S_y\) (\(3\le n,m\le 100\), \(2 \le S_x \le n-1\), \(2 \le S_y \le m-1\)) β the number of rows, the number of columns, and the initial position of your chess piece, respectively.
|
You should print \(n\cdot m\) lines.The \(i\)-th line should contain two integers \(x_i\) and \(y_i\) (\(1 \leq x_i \leq n\), \(1 \leq y_i \leq m\)), denoting the \(i\)-th cell that you visited. You should print exactly \(nm\) pairs \((x_i, y_i)\), they should cover all possible pairs \((x_i, y_i)\), such that \(1 \leq x_i \leq n\), \(1 \leq y_i \leq m\).We can show that under these constraints there always exists a solution. If there are multiple answers, print any.
|
Possible routes for two examples:
|
Input: 3 3 2 2 | Output: 2 2 1 2 1 3 2 3 3 3 3 2 3 1 2 1 1 1
|
Easy
| 1 | 989 | 256 | 471 | 13 |
939 |
F
|
939F
|
F. Cutlet
| 2,400 |
data structures; dp
|
Arkady wants to have a dinner. He has just returned from a shop where he has bought a semifinished cutlet. He only needs to fry it. The cutlet should be fried for 2n seconds, in particular, it should be fried for n seconds on one side and n seconds on the other side. Arkady has already got a frying pan and turn on fire, but understood that maybe he won't be able to flip the cutlet exactly after n seconds after the beginning of cooking.Arkady is too busy with sorting sticker packs in his favorite messenger and can flip the cutlet only in some periods of time. Namely, there are k periods of time in which he can do it, the i-th of them is an interval of time from li seconds after he starts cooking till ri seconds, inclusive. Arkady decided that it's not required to flip the cutlet exactly in the middle of cooking, instead, he will flip it several times in such a way that the cutlet will be fried exactly n seconds on one side and n seconds on the other side in total.Help Arkady and find out if it's possible for him to cook the cutlet, if he is able to flip the cutlet only in given periods of time; and if yes, find the minimum number of flips he needs to cook the cutlet.
|
The first line contains two integers n and k (1 β€ n β€ 100 000, 1 β€ k β€ 100) β the number of seconds the cutlet should be cooked on each side and number of periods of time in which Arkady can flip it.The next k lines contain descriptions of these intervals. Each line contains two integers li and ri (0 β€ li β€ ri β€ 2Β·n), meaning that Arkady can flip the cutlet in any moment starting from li seconds after the beginning of cooking and finishing at ri seconds after beginning of cooking. In particular, if li = ri then Arkady can flip the cutlet only in the moment li = ri. It's guaranteed that li > ri - 1 for all 2 β€ i β€ k.
|
Output ""Hungry"" if Arkady won't be able to fry the cutlet for exactly n seconds on one side and exactly n seconds on the other side.Otherwise, output ""Full"" in the first line, and the minimum number of times he should flip the cutlet in the second line.
|
In the first example Arkady should flip the cutlet in time moment 3 seconds after he starts cooking and in time moment 13 seconds after he starts cooking.In the second example, Arkady can flip the cutlet at 10 seconds after he starts cooking.
|
Input: 10 23 511 13 | Output: Full2
|
Expert
| 2 | 1,184 | 623 | 257 | 9 |
1,286 |
A
|
1286A
|
A. Garland
| 1,800 |
dp; greedy; sortings
|
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of \(n\) light bulbs in a single row. Each bulb has a number from \(1\) to \(n\) (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by \(2\)). For example, the complexity of 1 4 2 3 5 is \(2\) and the complexity of 1 3 5 7 6 4 2 is \(1\).No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.
|
The first line contains a single integer \(n\) (\(1 \le n \le 100\)) β the number of light bulbs on the garland.The second line contains \(n\) integers \(p_1,\ p_2,\ \ldots,\ p_n\) (\(0 \le p_i \le n\)) β the number on the \(i\)-th bulb, or \(0\) if it was removed.
|
Output a single number β the minimum complexity of the garland.
|
In the first example, one should place light bulbs as 1 5 4 2 3. In that case, the complexity would be equal to 2, because only \((5, 4)\) and \((2, 3)\) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.
|
Input: 5 0 5 0 2 3 | Output: 2
|
Medium
| 3 | 846 | 265 | 63 | 12 |
1,180 |
B
|
1180B
|
B. Nick and Array
| 1,500 |
greedy; implementation
|
Nick had received an awesome array of integers \(a=[a_1, a_2, \dots, a_n]\) as a gift for his \(5\) birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product \(a_1 \cdot a_2 \cdot \dots a_n\) of its elements seemed to him not large enough.He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index \(i\) (\(1 \le i \le n\)) and do \(a_i := -a_i - 1\).For example, he can change array \([3, -1, -4, 1]\) to an array \([-4, -1, 3, 1]\) after applying this operation to elements with indices \(i=1\) and \(i=3\). Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index. Help Kolya and print the array with the maximal possible product of elements \(a_1 \cdot a_2 \cdot \dots a_n\) which can be received using only this operation in some order.If there are multiple answers, print any of them.
|
The first line contains integer \(n\) (\(1 \leq n \leq 10^{5}\)) β number of integers in the array.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(-10^{6} \leq a_i \leq 10^{6}\)) β elements of the array
|
Print \(n\) numbers β elements of the array with the maximal possible product of elements which can be received using only this operation in some order from the given array.If there are multiple answers, print any of them.
|
Input: 4 2 2 2 2 | Output: -3 -3 -3 -3
|
Medium
| 2 | 1,312 | 223 | 222 | 11 |
|
319 |
C
|
319C
|
C. Kalila and Dimna in the Logging Industry
| 2,100 |
dp; geometry
|
Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money. The manager of logging factory wants them to go to the jungle and cut n trees with heights a1, a2, ..., an. They bought a chain saw from a shop. Each time they use the chain saw on the tree number i, they can decrease the height of this tree by one unit. Each time that Kalila and Dimna use the chain saw, they need to recharge it. Cost of charging depends on the id of the trees which have been cut completely (a tree is cut completely if its height equal to 0). If the maximum id of a tree which has been cut completely is i (the tree that have height ai in the beginning), then the cost of charging the chain saw would be bi. If no tree is cut completely, Kalila and Dimna cannot charge the chain saw. The chainsaw is charged in the beginning. We know that for each i < j, ai < aj and bi > bj and also bn = 0 and a1 = 1. Kalila and Dimna want to cut all the trees completely, with minimum cost. They want you to help them! Will you?
|
The first line of input contains an integer n (1 β€ n β€ 105). The second line of input contains n integers a1, a2, ..., an (1 β€ ai β€ 109). The third line of input contains n integers b1, b2, ..., bn (0 β€ bi β€ 109).It's guaranteed that a1 = 1, bn = 0, a1 < a2 < ... < an and b1 > b2 > ... > bn.
|
The only line of output must contain the minimum cost of cutting all the trees completely.Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
Input: 51 2 3 4 55 4 3 2 0 | Output: 25
|
Hard
| 2 | 1,064 | 292 | 239 | 3 |
|
1,711 |
A
|
1711A
|
A. Perfect Permutation
| 800 |
constructive algorithms
|
You are given a positive integer \(n\).The weight of a permutation \(p_1, p_2, \ldots, p_n\) is the number of indices \(1\le i\le n\) such that \(i\) divides \(p_i\). Find a permutation \(p_1,p_2,\dots, p_n\) with the minimum possible weight (among all permutations of length \(n\)).A permutation is an array consisting of \(n\) distinct integers from \(1\) to \(n\) in arbitrary order. For example, \([2,3,1,5,4]\) is a permutation, but \([1,2,2]\) is not a permutation (\(2\) appears twice in the array) and \([1,3,4]\) is also not a permutation (\(n=3\) but there is \(4\) in the array).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \leq t \leq 10^4\)). The description of the test cases follows.The only line of each test case contains a single integer \(n\) (\(1 \leq n \leq 10^5\)) β the length of permutation.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
|
For each test case, print a line containing \(n\) integers \(p_1, p_2,\dots, p_n\) so that the permutation \(p\) has the minimum possible weight.If there are several possible answers, you can print any of them.
|
In the first test case, the only valid permutation is \(p=[1]\). Its weight is \(1\).In the second test case, one possible answer is the permutation \(p=[2,1,4,3]\). One can check that \(1\) divides \(p_1\) and \(i\) does not divide \(p_i\) for \(i=2,3,4\), so the weight of this permutation is \(1\). It is impossible to find a permutation of length \(4\) with a strictly smaller weight.
|
Input: 214 | Output: 1 2 1 4 3
|
Beginner
| 1 | 590 | 364 | 210 | 17 |
555 |
C
|
555C
|
C. Case of Chocolate
| 2,200 |
data structures
|
Andrewid the Android is a galaxy-known detective. Now he does not investigate any case and is eating chocolate out of boredom.A bar of chocolate can be presented as an n Γ n table, where each cell represents one piece of chocolate. The columns of the table are numbered from 1 to n from left to right and the rows are numbered from top to bottom. Let's call the anti-diagonal to be a diagonal that goes the lower left corner to the upper right corner of the table. First Andrewid eats all the pieces lying below the anti-diagonal. Then he performs the following q actions with the remaining triangular part: first, he chooses a piece on the anti-diagonal and either direction 'up' or 'left', and then he begins to eat all the pieces starting from the selected cell, moving in the selected direction until he reaches the already eaten piece or chocolate bar edge.After each action, he wants to know how many pieces he ate as a result of this action.
|
The first line contains integers n (1 β€ n β€ 109) and q (1 β€ q β€ 2Β·105) β the size of the chocolate bar and the number of actions.Next q lines contain the descriptions of the actions: the i-th of them contains numbers xi and yi (1 β€ xi, yi β€ n, xi + yi = n + 1) β the numbers of the column and row of the chosen cell and the character that represents the direction (L β left, U β up).
|
Print q lines, the i-th of them should contain the number of eaten pieces as a result of the i-th action.
|
Pictures to the sample tests:The pieces that were eaten in the same action are painted the same color. The pieces lying on the anti-diagonal contain the numbers of the action as a result of which these pieces were eaten.In the second sample test the Andrewid tries to start eating chocolate for the second time during his fifth action, starting from the cell at the intersection of the 10-th column and the 1-st row, but this cell is already empty, so he does not eat anything.
|
Input: 6 53 4 U6 1 L2 5 L1 6 U4 3 U | Output: 43212
|
Hard
| 1 | 948 | 383 | 105 | 5 |
677 |
C
|
677C
|
C. Vanya and Label
| 1,500 |
bitmasks; combinatorics; implementation; strings
|
While walking down the street Vanya saw a label ""Hide&Seek"". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bitwise AND is equal to s. As this number can be large, output it modulo 109 + 7.To represent the string as a number in numeral system with base 64 Vanya uses the following rules: digits from '0' to '9' correspond to integers from 0 to 9; letters from 'A' to 'Z' correspond to integers from 10 to 35; letters from 'a' to 'z' correspond to integers from 36 to 61; letter '-' correspond to integer 62; letter '_' correspond to integer 63.
|
The only line of the input contains a single word s (1 β€ |s| β€ 100 000), consisting of digits, lowercase and uppercase English letters, characters '-' and '_'.
|
Print a single integer β the number of possible pairs of words, such that their bitwise AND is equal to string s modulo 109 + 7.
|
For a detailed definition of bitwise AND we recommend to take a look in the corresponding article in Wikipedia.In the first sample, there are 3 possible solutions: z&_ = 61&63 = 61 = z _&z = 63&61 = 61 = z z&z = 61&61 = 61 = z
|
Input: z | Output: 3
|
Medium
| 4 | 755 | 159 | 128 | 6 |
825 |
E
|
825E
|
E. Minimal Labels
| 2,300 |
data structures; dfs and similar; graphs; greedy
|
You are given a directed acyclic graph with n vertices and m edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected.You should assign labels to all vertices in such a way that: Labels form a valid permutation of length n β an integer sequence such that each integer from 1 to n appears exactly once in it. If there exists an edge from vertex v to vertex u then labelv should be smaller than labelu. Permutation should be lexicographically smallest among all suitable. Find such sequence of labels to satisfy all the conditions.
|
The first line contains two integer numbers n, m (2 β€ n β€ 105, 1 β€ m β€ 105).Next m lines contain two integer numbers v and u (1 β€ v, u β€ n, v β u) β edges of the graph. Edges are directed, graph doesn't contain loops or multiple edges.
|
Print n numbers β lexicographically smallest correct permutation of labels of vertices.
|
Input: 3 31 21 33 2 | Output: 1 3 2
|
Expert
| 4 | 577 | 235 | 87 | 8 |
|
1,827 |
B1
|
1827B1
|
B1. Range Sorting (Easy Version)
| 2,000 |
binary search; dp; dsu; greedy; trees; two pointers
|
The only difference between this problem and the hard version is the constraints on \(t\) and \(n\).You are given an array \(a\), consisting of \(n\) distinct integers \(a_1, a_2, \ldots, a_n\). Define the beauty of an array \(p_1, p_2, \ldots p_k\) as the minimum amount of time needed to sort this array using an arbitrary number of range-sort operations. In each range-sort operation, you will do the following: Choose two integers \(l\) and \(r\) (\(1 \le l < r \le k\)). Sort the subarray \(p_l, p_{l + 1}, \ldots, p_r\) in \(r - l\) seconds. Please calculate the sum of beauty over all subarrays of array \(a\).A subarray of an array is defined as a sequence of consecutive elements of the array.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 5 \cdot 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 5 \cdot 10^3\)) β the length of the array \(a\).The second line of each test case consists of \(n\) integers \(a_1,a_2,\ldots, a_n\) (\(1\le a_i\le 10^9\)). It is guaranteed that all elements of \(a\) are pairwise distinct.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5 \cdot 10^3\).
|
For each test case, output the sum of beauty over all subarrays of array \(a\).
|
In the first test case: The subarray \([6]\) is already sorted, so its beauty is \(0\). The subarray \([4]\) is already sorted, so its beauty is \(0\). You can sort the subarray \([6, 4]\) in one operation by choosing \(l = 1\) and \(r = 2\). Its beauty is equal to \(1\). The sum of beauty over all subarrays of the given array is equal to \(0 + 0 + 1 = 1\).In the second test case: The subarray \([3]\) is already sorted, so its beauty is \(0\). The subarray \([10]\) is already sorted, so its beauty is \(0\). The subarray \([6]\) is already sorted, so its beauty is \(0\). The subarray \([3, 10]\) is already sorted, so its beauty is \(0\). You can sort the subarray \([10, 6]\) in one operation by choosing \(l = 1\) and \(r = 2\). Its beauty is equal to \(2 - 1 = 1\). You can sort the subarray \([3, 10, 6]\) in one operation by choosing \(l = 2\) and \(r = 3\). Its beauty is equal to \(3 - 2 = 1\). The sum of beauty over all subarrays of the given array is equal to \(0 + 0 + 0 + 0 + 1 + 1 = 2\).
|
Input: 526 433 10 644 8 7 259 8 2 4 6122 6 13 3 15 5 10 8 16 9 11 18 | Output: 1 2 8 16 232
|
Hard
| 6 | 702 | 564 | 79 | 18 |
526 |
B
|
526B
|
B. Om Nom and Dark Park
| 1,400 |
dfs and similar; greedy; implementation
|
Om Nom is the main character of a game ""Cut the Rope"". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 β€ i < 2n + 1) there is a road to the square . Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square has ai lights.Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.
|
The first line contains integer n (1 β€ n β€ 10) β the number of roads on the path from the entrance to any exit.The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 β the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and . All numbers ai are positive integers, not exceeding 100.
|
Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.
|
Picture for the sample test. Green color denotes the additional street lights.
|
Input: 21 2 3 4 5 6 | Output: 5
|
Easy
| 3 | 1,526 | 373 | 111 | 5 |
1,808 |
E3
|
1808E3
|
E3. Minibuses on Venus (hard version)
| 2,800 |
brute force; combinatorics; dp; math
|
This is the hard version of the problem. The only difference between the three versions is the constraints on \(n\) and \(k\). You can make hacks only if all versions of the problem are solved.Maxim is a minibus driver on Venus.To ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting of \(n\) digits. However, as we know, the residents of Venus use a numeral system with base \(k\), rather than the decimal system. Therefore, the ticket number can be considered as a sequence of \(n\) integers from \(0\) to \(k-1\), inclusive.The residents of Venus consider a ticket to be lucky if there is a digit on it that is equal to the sum of the remaining digits, modulo \(k\). For example, if \(k=10\), then the ticket \(7135\) is lucky because \(7 + 1 + 5 \equiv 3 \pmod{10}\). On the other hand, the ticket \(7136\) is not lucky because no digit is equal to the sum of the others modulo \(10\).Once, while on a trip, Maxim wondered: how many lucky tickets exist? At the same time, Maxim understands that this number can be very large, so he is interested only in the answer modulo some prime number \(m\).
|
The only line of the input contains three integers \(n\), \(k\) and \(m\) (\(1 \le n \le 10^{18}\), \(1 \le k \le 2000\), \(10^8 \le m \le 10^9 + 7\), \(m\) is a prime number) β the number of digits on the ticket, the base of the numeral system on Venus, and the module for answer calculation.
|
Print one integer β the number of lucky tickets modulo \(m\), i. e. the remainder after dividing the answer by \(m\).
|
In the first example, there are only four lucky tickets: \(000\), \(011\), \(101\), and \(110\).
|
Input: 3 2 1000000007 | Output: 4
|
Master
| 4 | 1,127 | 293 | 117 | 18 |
10 |
D
|
10D
|
D. LCIS
| 2,800 |
dp
|
This problem differs from one which was on the online contest.The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 β€ i1 < i2 < ... < ik β€ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
|
The first line contains an integer n (1 β€ n β€ 500) β the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] β elements of the first sequence. The third line contains an integer m (1 β€ m β€ 500) β the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] β elements of the second sequence.
|
In the first line output k β the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
|
Input: 72 3 1 6 5 4 641 3 5 6 | Output: 33 5 6
|
Master
| 1 | 598 | 395 | 215 | 0 |
|
358 |
C
|
358C
|
C. Dima and Containers
| 2,000 |
constructive algorithms; greedy; implementation
|
Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck.Inna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands: Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end. Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers. Every time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation.As we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!
|
The first line contains integer n (1 β€ n β€ 105) β the number of Inna's commands. Then n lines follow, describing Inna's commands. Each line consists an integer: Integer a (1 β€ a β€ 105) means that Inna gives Dima a command to add number a into one of containers. Integer 0 shows that Inna asks Dima to make at most three extractions from different containers.
|
Each command of the input must correspond to one line of the output β Dima's action.For the command of the first type (adding) print one word that corresponds to Dima's choice: pushStack β add to the end of the stack; pushQueue β add to the end of the queue; pushFront β add to the beginning of the deck; pushBack β add to the end of the deck. For a command of the second type first print an integer k (0 β€ k β€ 3), that shows the number of extract operations, then print k words separated by space. The words can be: popStack β extract from the end of the stack; popQueue β extract from the beginning of the line; popFront β extract from the beginning from the deck; popBack β extract from the end of the deck. The printed operations mustn't extract numbers from empty containers. Also, they must extract numbers from distinct containers.The printed sequence of actions must lead to the maximum number of kisses. If there are multiple sequences of actions leading to the maximum number of kisses, you are allowed to print any of them.
|
Input: 100101201230 | Output: 0pushStack1 popStackpushStackpushQueue2 popStack popQueuepushStackpushQueuepushFront3 popStack popQueue popFront
|
Hard
| 3 | 1,427 | 358 | 1,034 | 3 |
|
913 |
B
|
913B
|
B. Christmas Spruce
| 1,200 |
implementation; trees
|
Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here.
|
The first line contains one integer n β the number of vertices in the tree (3 β€ n β€ 1 000). Each of the next n - 1 lines contains one integer pi (1 β€ i β€ n - 1) β the index of the parent of the i + 1-th vertex (1 β€ pi β€ i).Vertex 1 is the root. It's guaranteed that the root has at least 2 children.
|
Print ""Yes"" if the tree is a spruce and ""No"" otherwise.
|
The first example:The second example:It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.The third example:
|
Input: 4111 | Output: Yes
|
Easy
| 2 | 515 | 299 | 59 | 9 |
2,086 |
E
|
2086E
|
E. Zebra-like Numbers
| 2,400 |
bitmasks; brute force; constructive algorithms; dfs and similar; dp; greedy; math
|
We call a positive integer zebra-like if its binary representation has alternating bits up to the most significant bit, and the least significant bit is equal to \(1\). For example, the numbers \(1\), \(5\), and \(21\) are zebra-like, as their binary representations \(1\), \(101\), and \(10101\) meet the requirements, while the number \(10\) is not zebra-like, as the least significant bit of its binary representation \(1010\) is \(0\).We define the zebra value of a positive integer \(e\) as the minimum integer \(p\) such that \(e\) can be expressed as the sum of \(p\) zebra-like numbers (possibly the same, possibly different)Given three integers \(l\), \(r\), and \(k\), calculate the number of integers \(x\) such that \(l \le x \le r\) and the zebra value of \(x\) equals \(k\).
|
Each test consists of several test cases. The first line contains a single integer \(t\) (\(1 \le t \le 100\)) β the number of test cases. The description of test cases follows.The only line of each test case contains three integers \(l\), \(r\) (\(1 \le l \le r \le 10^{18}\)) and \(k\) (\(1 \le k \le 10^{18}\)).
|
For each test case, output a single integer β the number of integers in \([l, r]\) with zebra value \(k\).
|
In the first test case, there are \(13\) suitable numbers: \(3, 7, 11, 15, 23, 27, 31, 43, 47, 63, 87, 91, 95\). Each of them can be represented as a sum of \(3\) zebra-like numbers.
|
Input: 51 100 31 1 115 77 22 10 1001234567 123456789101112131 12 | Output: 13 1 3 0 4246658701
|
Expert
| 7 | 788 | 314 | 106 | 20 |
877 |
B
|
877B
|
B. Nikita and string
| 1,500 |
brute force; dp
|
One day Nikita found the string containing letters ""a"" and ""b"" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters ""a"" and the 2-nd contains only letters ""b"".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?
|
The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters ""a"" and ""b"".
|
Print a single integer β the maximum possible size of beautiful string Nikita can get.
|
It the first sample the string is already beautiful.In the second sample he needs to delete one of ""b"" to make it beautiful.
|
Input: abba | Output: 4
|
Medium
| 2 | 484 | 134 | 86 | 8 |
1,876 |
E
|
1876E
|
E. Ball-Stackable
| 3,300 |
constructive algorithms; data structures; dp; trees
|
With a problem title like that, there is no way this is going to be a graph problem.Chaneka has a graph with \(n\) vertices and \(n-1\) edges. Some of the edges are directed and some of the edges are undirected. Edge \(i\) connects vertex \(u_i\) to vertex \(v_i\). If \(t_i=0\), edge \(i\) is undirected. If \(t_i=1\), edge \(i\) is directed in the direction from \(u_i\) to \(v_i\). It is known that if you make all edges undirected, the graph becomes a tree\(^\dagger\).Chaneka wants to direct all undirected edges and colour each edge (different edges can have the same colour).After doing that, suppose Chaneka starts a walk from an arbitrary vertex \(x\) to an arbitrary vertex \(y\) (it is possible that \(x=y\)) going through one or more edges. She is allowed to go through each edge either following the direction or opposite to the direction of the edge. She is also allowed to visit a vertex or an edge more than once. During the walk, Chaneka maintains a stack of balls that is initially empty before the walk. Each time Chaneka goes through an edge, she does the following: If Chaneka goes through it in the right direction, she puts a new ball with a colour that is the same as the edge's colour to the top of the stack. If Chaneka goes through it in the opposite direction, she removes the ball that is on the top of the stack. A walk is stackable if and only if the stack is not empty before each time Chaneka goes through an edge in the opposite direction.A walk is ball-stackable if and only if it is stackable and each time Chaneka goes through an edge in the opposite direction, the colour of the ball removed from the stack is the same as the colour of the edge traversed.Is it possible to direct all undirected edges and colour each edge such that all stackable walks are also ball-stackable? If it is possible, find a construction example that uses the maximum number of different colours among all valid ways of directing and colouring. If there are multiple such solutions, output any of them.\(^\dagger\) A tree is a connected graph with no cycles.
|
The first line contains a single integer \(n\) (\(2\leq n\leq10^5\)) β the number of vertices in the graph.The \(i\)-th of the next \(n-1\) lines contains three integers \(u_i\), \(v_i\), and \(t_i\) (\(1 \leq u_i,v_i \leq n\); \(0\leq t_i\leq1\)) β an undirected edge connecting vectices \(u_i\) and \(v_i\) if \(t_i=0\), or a directed edge from vertex \(u_i\) to vertex \(v_i\) if \(t_i=1\). If you make all edges undirected, the graph becomes a tree.
|
A single line containing \(-1\) if it is impossible.Otherwise, the output consists of \(n\) lines describing your construction. The first line contains an integer \(z\) representing the number of different colours used. The \(i\)-th of the next \(n-1\) lines contains three integers \(p\), \(q\), and \(c\) (\(1\leq p,q\leq n\); \(1\leq c\leq z\)) β the edge connecting vertices \(p\) and \(q\) in the graph is directed from vertex \(p\) to vertex \(q\) and is coloured with colour \(c\). If there are multiple such solutions, output any of them.Note that since there should be \(z\) different colours in your construction, that means each colour from \(1\) to \(z\) must appear at least once in the graph.
|
The following is the given graph. Chaneka can direct all undirected edges and colour each edge as follows. As an example, consider a stackable walk \(3β1β5β2β5β4β5\). Let's show that that walk is ball-stackable. Chaneka starts in vertex \(3\). The stack is \([]\). Chaneka moves to vertex \(1\). She puts a ball of colour \(3\). The stack is \([3]\). Chaneka moves to vertex \(5\). She puts a ball of colour \(2\). The stack is \([3,2]\). Chaneka moves to vertex \(2\). She removes a ball of colour \(2\) (same colour as the edge). The stack is \([3]\). Chaneka moves to vertex \(5\). She puts a ball of colour \(2\). The stack is \([3,2]\). Chaneka moves to vertex \(4\). She puts a ball of colour \(1\). The stack is \([3,2,1]\). Chaneka moves to vertex \(5\). She removes a ball of colour \(1\) (same colour as the edge). The stack is \([3,2]\). Since every time Chaneka removes a ball from the stack, it has the same colour as the edge traversed, then the walk above is ball-stackable. It can be shown that if we direct and colour the edges as shown above, any possible stackable walk is also ball-stackable.
|
Input: 5 2 5 1 1 3 0 5 4 0 1 5 1 | Output: 3 1 5 2 5 4 1 2 5 2 3 1 3
|
Master
| 4 | 2,074 | 453 | 706 | 18 |
1,422 |
A
|
1422A
|
A. Fence
| 800 |
geometry; math
|
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths \(a\), \(b\), and \(c\). Now he needs to find out some possible integer length \(d\) of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to \(a\), \(b\), \(c\), and \(d\). Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
|
The first line contains a single integer \(t\) β the number of test cases (\(1 \le t \le 1000\)). The next \(t\) lines describe the test cases.Each line contains three integers \(a\), \(b\), and \(c\) β the lengths of the three fence segments (\(1 \le a, b, c \le 10^9\)).
|
For each test case print a single integer \(d\) β the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
|
We can build a quadrilateral with sides \(1\), \(2\), \(3\), \(4\).We can build a quadrilateral with sides \(12\), \(34\), \(56\), \(42\).
|
Input: 2 1 2 3 12 34 56 | Output: 4 42
|
Beginner
| 2 | 663 | 272 | 213 | 14 |
1,702 |
A
|
1702A
|
A. Round Down the Price
| 800 |
constructive algorithms
|
At the store, the salespeople want to make all prices round. In this problem, a number that is a power of \(10\) is called a round number. For example, the numbers \(10^0 = 1\), \(10^1 = 10\), \(10^2 = 100\) are round numbers, but \(20\), \(110\) and \(256\) are not round numbers. So, if an item is worth \(m\) bourles (the value of the item is not greater than \(10^9\)), the sellers want to change its value to the nearest round number that is not greater than \(m\). They ask you: by how many bourles should you decrease the value of the item to make it worth exactly \(10^k\) bourles, where the value of \(k\) β is the maximum possible (\(k\) β any non-negative integer).For example, let the item have a value of \(178\)-bourles. Then the new price of the item will be \(100\), and the answer will be \(178-100=78\).
|
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 is a string containing a single integer \(m\) (\(1 \le m \le 10^9\)) β the price of the item.
|
For each test case, output on a separate line a single integer \(d\) (\(0 \le d < m\)) such that if you reduce the cost of the item by \(d\) bourles, the cost of the item will be the maximal possible round number. More formally: \(m - d = 10^k\), where \(k\) β the maximum possible non-negative integer.
|
In the example: \(1 - 0 = 10^0\), \(2 - 1 = 10^0\), \(178 - 78 = 10^2\), \(20 - 10 = 10^1\), \(999999999 - 899999999 = 10^8\), \(9000 - 8000 = 10^3\), \(987654321 - 887654321 = 10^8\). Note that in each test case, we get the maximum possible round number.
|
Input: 712178209999999999000987654321 | Output: 0 1 78 10 899999999 8000 887654321
|
Beginner
| 1 | 821 | 220 | 303 | 17 |
2,052 |
F
|
2052F
|
F. Fix Flooded Floor
| 1,700 |
constructive algorithms; dp; graphs
|
Archimedes conducted his famous experiments on buoyancy. But not everyone knows that while he was taking a bath, he was too focused and didn't notice the moment when the water overflowed over the edge of the bath and flooded the floor near the wall. His expensive parquet was irreversibly damaged!Archimedes noticed that not all was lost, and there were still several undamaged parquet pieces. The parquet near the wall had the shape of a long narrow stripe of \(2\times n\) cells. Archimedes had an unlimited supply of \(1\times 2\) parquet pieces that could be placed parallel or perpendicular to the wall. Archimedes didn't want to cut the parquet pieces. As a great scientist, he figured out that there was exactly one way to restore the parquet by filling the damaged area of the parquet with the non-overlapping \(1\times 2\) cell shaped pieces.Help historians to check Archimedes' calculations. For the given configuration of the \(2\times n\) parquet floor, determine whether there is exactly one way to fill the damaged parquet cells with the \(1\times 2\) cell parquet pieces. If Archimedes was wrong, find out whether there are multiple ways to restore the parquet, or there are no ways at all.
|
The first line contains a single integer \(T\) (\(1 \le T \le 10^4\)) β the number of test cases to solve.Then the description of test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2\cdot 10^5\)) β the length of the parquet floor.The following two lines contain exactly \(n\) characters each and describe the parquet, where '.' denotes a damaged cell and '#' denotes an undamaged cell.The total sum of \(n\) in all \(T\) test cases doesn't exceed \(2\cdot 10^5\).
|
For each test case, print ""Unique"" if there is exactly one way to restore the parquet, ""Multiple"" if there are multiple ways to do so, or ""None"" if it is impossible to restore the parquet.
|
Input: 410#.......####..#.##..6...#....#...8................3###### | Output: Unique None Multiple Unique
|
Medium
| 3 | 1,205 | 511 | 194 | 20 |
|
159 |
E
|
159E
|
E. Zebra Tower
| 1,700 |
*special; data structures; greedy; sortings
|
Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters β color ci and size si. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower. A Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes.
|
The first line contains an integer n (2 β€ n β€ 105) β the number of cubes. Next n lines contain the descriptions of the cubes, one description per line. A cube description consists of two space-separated integers ci and si (1 β€ ci, si β€ 109) β the i-th cube's color and size, correspondingly. It is guaranteed that there are at least two cubes of different colors.
|
Print the description of the Zebra Tower of the maximum height in the following form. In the first line print the tower's height, in the second line print the number of cubes that form the tower, and in the third line print the space-separated indices of cubes in the order in which they follow in the tower from the bottom to the top. Assume that the cubes are numbered from 1 to n in the order in which they were given in the input.If there are several existing Zebra Towers with maximum heights, it is allowed to print any of them. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
|
Input: 41 21 32 43 3 | Output: 932 3 1
|
Medium
| 4 | 692 | 363 | 687 | 1 |
|
1,093 |
F
|
1093F
|
F. Vasya and Array
| 2,400 |
dp
|
Vasya has got an array consisting of \(n\) integers, and two integers \(k\) and \(len\) in addition. All numbers in the array are either between \(1\) and \(k\) (inclusive), or equal to \(-1\). The array is good if there is no segment of \(len\) consecutive equal numbers.Vasya will replace each \(-1\) with some number from \(1\) to \(k\) (inclusive) in such a way that the resulting array is good. Tell him the number of ways to do this replacement. Since the answer may be large, print it modulo \(998244353\).
|
The first line contains three integers \(n, k\) and \(len\) (\(1 \le n \le 10^5, 1 \le k \le 100, 1 \le len \le n\)).The second line contains \(n\) numbers β the array. Each number is either \(-1\) or between \(1\) and \(k\) (inclusive).
|
Print one integer β the number of ways to replace each \(-1\) with some number from \(1\) to \(k\) (inclusive) so the array is good. The answer may be large, so print it modulo \(998244353\).
|
Possible answers in the first test: \([1, 2, 1, 1, 2]\); \([1, 2, 1, 2, 2]\). There is no way to make the array good in the second test, since first two elements are equal.There are too many answers in the third test, so we won't describe any of them.
|
Input: 5 2 3 1 -1 1 -1 2 | Output: 2
|
Expert
| 1 | 513 | 237 | 191 | 10 |
1,659 |
E
|
1659E
|
E. AND-MEX Walk
| 2,200 |
bitmasks; brute force; constructive algorithms; dfs and similar; dsu; graphs
|
There is an undirected, connected graph with \(n\) vertices and \(m\) weighted edges. A walk from vertex \(u\) to vertex \(v\) is defined as a sequence of vertices \(p_1,p_2,\ldots,p_k\) (which are not necessarily distinct) starting with \(u\) and ending with \(v\), such that \(p_i\) and \(p_{i+1}\) are connected by an edge for \(1 \leq i < k\).We define the length of a walk as follows: take the ordered sequence of edges and write down the weights on each of them in an array. Now, write down the bitwise AND of every nonempty prefix of this array. The length of the walk is the MEX of all these values.More formally, let us have \([w_1,w_2,\ldots,w_{k-1}]\) where \(w_i\) is the weight of the edge between \(p_i\) and \(p_{i+1}\). Then the length of the walk is given by \(\mathrm{MEX}(\{w_1,\,w_1\& w_2,\,\ldots,\,w_1\& w_2\& \ldots\& w_{k-1}\})\), where \(\&\) denotes the bitwise AND operation.Now you must process \(q\) queries of the form u v. For each query, find the minimum possible length of a walk from \(u\) to \(v\).The MEX (minimum excluded) of a set is the smallest non-negative integer that does not belong to the set. For instance: The MEX of \(\{2,1\}\) is \(0\), because \(0\) does not belong to the set. The MEX of \(\{3,1,0\}\) is \(2\), because \(0\) and \(1\) belong to the set, but \(2\) does not. The MEX of \(\{0,3,1,2\}\) is \(4\) because \(0\), \(1\), \(2\) and \(3\) belong to the set, but \(4\) does not.
|
The first line contains two integers \(n\) and \(m\) (\(2 \leq n \leq 10^5\); \(n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2},10^5\right)}\)).Each of the next \(m\) lines contains three integers \(a\), \(b\), and \(w\) (\(1 \leq a, b \leq n\), \(a \neq b\); \(0 \leq w < 2^{30}\)) indicating an undirected edge between vertex \(a\) and vertex \(b\) with weight \(w\). The input will not contain self-loops or duplicate edges, and the provided graph will be connected.The next line contains a single integer \(q\) (\(1 \leq q \leq 10^5\)).Each of the next \(q\) lines contains two integers \(u\) and \(v\) (\(1 \leq u, v \leq n\), \(u \neq v\)), the description of each query.
|
For each query, print one line containing a single integer β the answer to the query.
|
The following is an explanation of the first example. The graph in the first example. Here is one possible walk for the first query:$$$\(1 \overset{5}{\rightarrow} 3 \overset{3}{\rightarrow} 2 \overset{1}{\rightarrow} 1 \overset{5}{\rightarrow} 3 \overset{1}{\rightarrow} 4 \overset{2}{\rightarrow} 5.\)\(The array of weights is \)w=[5,3,1,5,1,2]\(. Now if we take the bitwise AND of every prefix of this array, we get the set \)\{5,1,0\}\(. The MEX of this set is \)2$$$. We cannot get a walk with a smaller length (as defined in the statement).
|
Input: 6 7 1 2 1 2 3 3 3 1 5 4 5 2 5 6 4 6 4 6 3 4 1 3 1 5 1 2 5 3 | Output: 2 0 1
|
Hard
| 6 | 1,438 | 673 | 85 | 16 |
212 |
D
|
212D
|
D. Cutting a Fence
| 2,500 |
binary search; data structures; dsu
|
Vasya the carpenter has an estate that is separated from the wood by a fence. The fence consists of n planks put in a line. The fence is not closed in a circle. The planks are numbered from left to right from 1 to n, the i-th plank is of height ai. All planks have the same width, the lower edge of each plank is located at the ground level.Recently a local newspaper ""Malevich and Life"" wrote that the most fashionable way to decorate a fence in the summer is to draw a fuchsia-colored rectangle on it, the lower side of the rectangle must be located at the lower edge of the fence.Vasya is delighted with this idea! He immediately bought some fuchsia-colored paint and began to decide what kind of the rectangle he should paint. Vasya is sure that the rectangle should cover k consecutive planks. In other words, he will paint planks number x, x + 1, ..., x + k - 1 for some x (1 β€ x β€ n - k + 1). He wants to paint the rectangle of maximal area, so the rectangle height equals min ai for x β€ i β€ x + k - 1, x is the number of the first colored plank.Vasya has already made up his mind that the rectangle width can be equal to one of numbers of the sequence k1, k2, ..., km. For each ki he wants to know the expected height of the painted rectangle, provided that he selects x for such fence uniformly among all n - ki + 1 possible values. Help him to find the expected heights.
|
The first line contains a single integer n (1 β€ n β€ 106) β the number of planks in the fence. The second line contains a sequence of integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the height of the i-th plank of the fence.The third line contains an integer m (1 β€ m β€ 106) and the next line contains m space-separated integers k1, k2, ..., km (1 β€ ki β€ n) where ki is the width of the desired fuchsia-colored rectangle in planks.
|
Print m whitespace-separated real numbers, the i-th number equals the expected value of the rectangle height, if its width in planks equals ki. The value will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
|
Let's consider the first sample test. There are three possible positions of the fence for k1 = 1. For the first position (x = 1) the height is 3, for the second one (x = 2) the height is 2, for the third one (x = 3) the height is 1. As the fence position is chosen uniformly, the expected height of the fence equals ; There are two possible positions of the fence for k2 = 2. For the first position (x = 1) the height is 2, for the second one (x = 2) the height is 1. The expected height of the fence equals ; There is the only possible position of the fence for k3 = 3. The expected height of the fence equals 1.
|
Input: 33 2 131 2 3 | Output: 2.0000000000000001.5000000000000001.000000000000000
|
Expert
| 3 | 1,382 | 434 | 237 | 2 |
120 |
I
|
120I
|
I. Luck is in Numbers
| 2,200 |
greedy
|
Vasya has been collecting transport tickets for quite a while now. His collection contains several thousands of tram, trolleybus and bus tickets. Vasya is already fed up with the traditional definition of what a lucky ticket is. Thus, he's looking for new perspectives on that. Besides, Vasya cannot understand why all tickets are only divided into lucky and unlucky ones. He thinks that all tickets are lucky but in different degrees. Having given the matter some thought, Vasya worked out the definition of a ticket's degree of luckiness. Let a ticket consist of 2n digits. Let's regard each digit as written as is shown on the picture: You have seen such digits on electronic clocks: seven segments are used to show digits. Each segment can either be colored or not. The colored segments form a digit. Vasya regards the digits as written in this very way and takes the right half of the ticket and puts it one the left one, so that the first digit coincides with the n + 1-th one, the second digit coincides with the n + 2-th one, ..., the n-th digit coincides with the 2n-th one. For each pair of digits, put one on another, he counts the number of segments colored in both digits and summarizes the resulting numbers. The resulting value is called the degree of luckiness of a ticket. For example, the degree of luckiness of ticket 03 equals four and the degree of luckiness of ticket 2345 equals six.You are given the number of a ticket containing 2n digits. Your task is to find among the tickets whose number exceeds the number of this ticket but also consists of 2n digits such ticket, whose degree of luckiness exceeds the degrees of luckiness of the given ticket. Moreover, if there are several such tickets, you should only choose the one with the smallest number.
|
The first line contains the number of the ticket that consists of k characters (k = 2n, 1 β€ n β€ 105).
|
Print the number of the sought ticket or ""-1"" (without the quotes) if no such ticket exists.
|
Input: 13 | Output: 20
|
Hard
| 1 | 1,776 | 101 | 94 | 1 |
|
2,107 |
F2
|
2107F2
|
F2. Cycling (Hard Version)
| 2,800 |
binary search; brute force; data structures; dp; greedy
|
This is the hard version of the problem. The difference between the versions is that in this version, \(1\le n\le 10^6\) and you need to output the answer for each prefix. You can hack only if you solved all versions of this problem.Leo works as a programmer in the city center, and his lover teaches at a high school in the suburbs. Every weekend, Leo would ride his bike to the suburbs to spend a nice weekend with his lover.There are \(n\) cyclists riding in front of Leo on this road right now. They are numbered \(1\), \(2\), \(\ldots\), \(n\) from front to back. Initially, Leo is behind the \(n\)-th cyclist. The \(i\)-th cyclist has an agility value \(a_i\). Leo wants to get ahead of the \(1\)-st cyclist. Leo can take the following actions as many times as he wants: Assuming that the first person in front of Leo is cyclist \(i\), he can go in front of cyclist \(i\) for a cost of \(a_i\). This puts him behind cyclist \(i - 1\). Using his super powers, swap \(a_i\) and \(a_j\) (\(1\le i < j\le n\)) for a cost of \((j - i)\). Leo wants to know the minimum cost to get in front of the \(1\)-st cyclist. In addition, he wants to know the answer for each \(1\le i \le n\), \([a_1, a_2, \ldots, a_i]\) as the original array. The problems of different \(i\) are independent. To be more specific, in the \(i\)-th problem, Leo starts behind the \(i\)-th cyclist instead of the \(n\)-th cyclist, and cyclists numbered \(i + 1, i + 2, \ldots, n\) are not present.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The first line of each test case contains a positive integer \(n\) (\(1 \leq n \leq 10^6\)), representing the number of the cyclists.The second line of each test case contains \(n\) integers \(a_1, \ldots, a_n\) (\(1 \leq a_i \leq 10^9\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^6\).
|
For each test case, print \(n\) integers, the answers for the array \([a_1, a_2, \ldots, a_i]\) for each \(i = 1, 2, \ldots n\) in this order.
|
In the first test case, one possible way to move from the position behind the \(n\)-th cyclist to the position in front of the \(1\)-st cyclist is: Leo swaps \(a_2\) \((i=2)\) and \(a_3\) \((j=3)\), then the array becomes \([1,4,2]\); it costs \(j-i=3-2=1\). Leo is behind the \(3\)-rd cyclist and moves behind the \(2\)-nd cyclist; it costs \(a_3=2\). Leo swaps \(a_1\) \((i=1)\) and \(a_2\) \((j=2)\), then the array becomes \([4,1,2]\); it costs \(j-i=2-1=1\). Leo is behind the \(2\)-nd cyclist and moves behind the \(1\)-st cyclist; it costs \(a_2=1\). Leo swaps \(a_1\) \((i=1)\) and \(a_2\) \((j=2)\), then the array becomes \([1,4,2]\); it costs \(j-i=2-1=1\). Leo moves ahead of the \(1\)-st cyclist; it costs \(a_1=1\). So the total cost is \(1+2+1+1+1+1=7\). It can be proved that \(7\) is the minimum cost.In the second test case, to move ahead of the \(1\)-st cyclist from the position behind the \(n\)-th cyclist, Leo should not swap anyone's agility value. The total cost is \(1+1+1+1=4\).
|
Input: 431 2 441 1 1 121 244 1 3 2 | Output: 1 3 7 1 2 3 4 1 3 4 3 6 8
|
Master
| 5 | 1,467 | 485 | 142 | 21 |
2,111 |
D
|
2111D
|
D. Creating a Schedule
| 1,400 |
constructive algorithms; data structures; greedy; implementation; sortings
|
A new semester is about to begin, and it is necessary to create a schedule for the first day. There are a total of \(n\) groups and \(m\) classrooms in the faculty. It is also known that each group has exactly \(6\) classes on the first day, and the \(k\)-th class of each group takes place at the same time. Each class must be held in a classroom, and at the same time, there cannot be classes for more than one group in the same classroom.Each classroom has its own index (at least three digits), and all digits of this index, except for the last two, indicate the floor on which the classroom is located. For example, classroom \(479\) is located on the \(4\)-th floor, while classroom \(31415\) is on the \(314\)-th floor. Between floors, one can move by stairs; for any floor \(x > 1\), one can either go down to floor \(x - 1\) or go up to floor \(x + 1\); from the first floor, one can only go up to the second; from the floor \(10^7\) (which is the last one), it is possible to go only to the floor \(9999999\).The faculty's dean's office has decided to create the schedule in such a way that students move as much as possible between floors, meaning that the total number of movements between floors across all groups should be maximized. When the students move from one floor to another floor, they take the shortest path.For example, if there are \(n = 2\) groups and \(m = 4\) classrooms \([479, 290, 478, 293]\), the schedule can be arranged as follows: Class No.Group 1Group 2\(1\)\(290\)\(293\)\(2\)\(478\)\(479\)\(3\)\(293\)\(290\)\(4\)\(479\)\(478\)\(5\)\(293\)\(290\)\(6\)\(479\)\(478\) In such a schedule, the groups will move between the \(2\)nd and \(4\)th floors each time, resulting in a total of \(20\) movements between floors.Help the dean's office create any suitable schedule!
|
Each test consists of several test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^{3}\)) β the number of test cases. The description of the test cases follows.The first line of each test case contains two integers \(n\) and \(m\) (\(1 \le n \le m \le 10^{5}\)) β the number of groups and the number of available classrooms.The second line of each test case contains \(m\) integers \(a_{i}\) (\(100 \le a_{i} < 10^{9}\)) β the indices of the available classrooms.Additional constraints on the input: the numbers of all classrooms are pairwise distinct; the sum of \(m\) across all test cases does not exceed \(10^{5}\).
|
For each test case, output \(n\) lines, where the \(i\)-th line should contain \(6\) integers β the indices of the classrooms where the classes for the \(i\)-th group will be held.Each classroom must be occupied by at most one group during the \(k\)-th class.
|
In the third test case, the maximum number of moves between classrooms is \(50\).
|
Input: 32 4479 290 478 2931 1314156 10479 385 290 293 384 383 297 478 291 382 | Output: 290 478 293 479 293 479 293 479 290 478 290 478 31415 31415 31415 31415 31415 31415 479 290 479 290 479 290 290 479 290 479 290 479 293 478 293 478 293 478 297 385 297 385 297 385 478 293 478 293 478 293 291 384 291 384 291 384
|
Easy
| 5 | 1,804 | 643 | 259 | 21 |
590 |
B
|
590B
|
B. Chip 'n Dale Rescue Rangers
| 2,100 |
binary search; geometry; math
|
A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point (x1, y1), and the distress signal came from the point (x2, y2).Due to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed meters per second.Of course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector (vx, vy) for the nearest t seconds, and then will change to (wx, wy). These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point (x, y), while its own velocity relative to the air is equal to zero and the wind (ux, uy) is blowing, then after seconds the new position of the dirigible will be .Gadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer.It is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air.
|
The first line of the input contains four integers x1, y1, x2, y2 (|x1|, |y1|, |x2|, |y2| β€ 10 000) β the coordinates of the rescuers' headquarters and the point, where signal of the distress came from, respectively. The second line contains two integers and t (0 < v, t β€ 1000), which are denoting the maximum speed of the chipmunk dirigible relative to the air and the moment of time when the wind changes according to the weather forecast, respectively. Next follow one per line two pairs of integer (vx, vy) and (wx, wy), describing the wind for the first t seconds and the wind that will blow at all the remaining time, respectively. It is guaranteed that and .
|
Print a single real value β the minimum time the rescuers need to get to point (x2, y2). You answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
|
Input: 0 0 5 53 2-1 -1-1 0 | Output: 3.729935587093555327
|
Hard
| 3 | 1,773 | 666 | 321 | 5 |
|
883 |
B
|
883B
|
B. Berland Army
| 2,600 |
constructive algorithms; graphs; greedy
|
There are n military men in the Berland army. Some of them have given orders to other military men by now. Given m pairs (xi, yi), meaning that the military man xi gave the i-th order to another military man yi.It is time for reform! The Berland Ministry of Defence plans to introduce ranks in the Berland army. Each military man should be assigned a rank β integer number between 1 and k, inclusive. Some of them have been already assigned a rank, but the rest of them should get a rank soon.Help the ministry to assign ranks to the rest of the army so that: for each of m orders it is true that the rank of a person giving the order (military man xi) is strictly greater than the rank of a person receiving the order (military man yi); for each rank from 1 to k there is at least one military man with this rank.
|
The first line contains three integers n, m and k (1 β€ n β€ 2Β·105, 0 β€ m β€ 2Β·105, 1 β€ k β€ 2Β·105) β number of military men in the Berland army, number of orders and number of ranks.The second line contains n integers r1, r2, ..., rn, where ri > 0 (in this case 1 β€ ri β€ k) means that the i-th military man has been already assigned the rank ri; ri = 0 means the i-th military man doesn't have a rank yet.The following m lines contain orders one per line. Each order is described with a line containing two integers xi, yi (1 β€ xi, yi β€ n, xi β yi). This line means that the i-th order was given by the military man xi to the military man yi. For each pair (x, y) of military men there could be several orders from x to y.
|
Print n integers, where the i-th number is the rank of the i-th military man. If there are many solutions, print any of them.If there is no solution, print the only number -1.
|
Input: 5 3 30 3 0 0 22 43 43 5 | Output: 1 3 3 2 2
|
Expert
| 3 | 814 | 719 | 175 | 8 |
|
319 |
B
|
319B
|
B. Psychos in a Line
| 1,900 |
data structures; implementation
|
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
|
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
|
Print the number of steps, so that the line remains the same afterward.
|
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps.
|
Input: 1010 9 7 8 6 5 3 4 2 1 | Output: 2
|
Hard
| 2 | 515 | 253 | 71 | 3 |
1,311 |
F
|
1311F
|
F. Moving Points
| 1,900 |
data structures; divide and conquer; implementation; sortings
|
There are \(n\) points on a coordinate axis \(OX\). The \(i\)-th point is located at the integer point \(x_i\) and has a speed \(v_i\). It is guaranteed that no two points occupy the same coordinate. All \(n\) points move with the constant speed, the coordinate of the \(i\)-th point at the moment \(t\) (\(t\) can be non-integer) is calculated as \(x_i + t \cdot v_i\).Consider two points \(i\) and \(j\). Let \(d(i, j)\) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points \(i\) and \(j\) coincide at some moment, the value \(d(i, j)\) will be \(0\).Your task is to calculate the value \(\sum\limits_{1 \le i < j \le n}\) \(d(i, j)\) (the sum of minimum distances over all pairs of points).
|
The first line of the input contains one integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) β the number of points.The second line of the input contains \(n\) integers \(x_1, x_2, \dots, x_n\) (\(1 \le x_i \le 10^8\)), where \(x_i\) is the initial coordinate of the \(i\)-th point. It is guaranteed that all \(x_i\) are distinct.The third line of the input contains \(n\) integers \(v_1, v_2, \dots, v_n\) (\(-10^8 \le v_i \le 10^8\)), where \(v_i\) is the speed of the \(i\)-th point.
|
Print one integer β the value \(\sum\limits_{1 \le i < j \le n}\) \(d(i, j)\) (the sum of minimum distances over all pairs of points).
|
Input: 3 1 3 2 -100 2 3 | Output: 3
|
Hard
| 4 | 780 | 479 | 134 | 13 |
|
884 |
B
|
884B
|
B. Japanese Crosswords Strike Back
| 1,100 |
implementation
|
A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect.For example: If x = 6 and the crossword is 111011, then its encoding is an array {3, 2}; If x = 8 and the crossword is 01101010, then its encoding is an array {2, 1, 1}; If x = 5 and the crossword is 11111, then its encoding is an array {5}; If x = 5 and the crossword is 00000, then its encoding is an empty array. Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!
|
The first line contains two integer numbers n and x (1 β€ n β€ 100000, 1 β€ x β€ 109) β the number of elements in the encoding and the length of the crossword Mishka picked.The second line contains n integer numbers a1, a2, ..., an (1 β€ ai β€ 10000) β the encoding.
|
Print YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO.
|
Input: 2 41 3 | Output: NO
|
Easy
| 1 | 890 | 260 | 101 | 8 |
|
865 |
B
|
865B
|
B. Ordering Pizza
| 1,900 |
binary search; sortings; ternary search
|
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?
|
The first line of input will contain integers N and S (1 β€ N β€ 105, 1 β€ S β€ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow.The i-th such line contains integers si, ai, and bi (1 β€ si β€ 105, 1 β€ ai β€ 105, 1 β€ bi β€ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.
|
Print the maximum total happiness that can be achieved.
|
In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3Β·5 + 4Β·6 + 5Β·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3Β·7 + 4Β·7 + 5Β·5 = 74.
|
Input: 3 123 5 74 6 75 9 5 | Output: 84
|
Hard
| 3 | 705 | 461 | 55 | 8 |
1,520 |
E
|
1520E
|
E. Arranging The Sheep
| 1,400 |
greedy; math
|
You are playing the game ""Arranging The Sheep"". The goal of this game is to make the sheep line up. The level in the game is described by a string of length \(n\), consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the corresponding square exists and is empty. The game ends as soon as the sheep are lined up, that is, there should be no empty cells between any sheep.For example, if \(n=6\) and the level is described by the string ""**.*.."", then the following game scenario is possible: the sheep at the \(4\) position moves to the right, the state of the level: ""**..*.""; the sheep at the \(2\) position moves to the right, the state of the level: ""*.*.*.""; the sheep at the \(1\) position moves to the right, the state of the level: "".**.*.""; the sheep at the \(3\) position moves to the right, the state of the level: "".*.**.""; the sheep at the \(2\) position moves to the right, the state of the level: ""..***.""; the sheep are lined up and the game ends. For a given level, determine the minimum number of moves you need to make to complete the level.
|
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)). Then \(t\) test cases follow.The first line of each test case contains one integer \(n\) (\(1 \le n \le 10^6\)).The second line of each test case contains a string of length \(n\), consisting of the characters '.' (empty space) and '*' (sheep) β the description of the level.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^6\).
|
For each test case output the minimum number of moves you need to make to complete the level.
|
Input: 5 6 **.*.. 5 ***** 3 .*. 3 ... 10 *.*...*.** | Output: 1 0 0 0 9
|
Easy
| 2 | 1,174 | 425 | 93 | 15 |
|
1,946 |
C
|
1946C
|
C. Tree Cutting
| 1,600 |
binary search; dp; greedy; implementation; trees
|
You are given a tree with \(n\) vertices.Your task is to find the maximum number \(x\) such that it is possible to remove exactly \(k\) edges from this tree in such a way that the size of each remaining connected component\(^{\dagger}\) is at least \(x\).\(^{\dagger}\) Two vertices \(v\) and \(u\) are in the same connected component if there exists a sequence of numbers \(t_1, t_2, \ldots, t_k\) of arbitrary length \(k\), such that \(t_1 = v\), \(t_k = u\), and for each \(i\) from \(1\) to \(k - 1\), vertices \(t_i\) and \(t_{i+1}\) are connected by an edge.
|
Each test consists of several sets of input data. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β the number of sets of input data. This is followed by a description of the sets of input data.The first line of each set of input data contains two integers \(n\) and \(k\) (\(1 \le k < n \le 10^5\)) β the number of vertices in the tree and the number of edges to be removed.Each of the next \(n - 1\) lines of each set of input data contains two integers \(v\) and \(u\) (\(1 \le v, u \le n\)) β the next edge of the tree.It is guaranteed that the sum of the values of \(n\) for all sets of input data does not exceed \(10^5\).
|
For each set of input data, output a single line containing the maximum number \(x\) such that it is possible to remove exactly \(k\) edges from the tree in such a way that the size of each remaining connected component is at least \(x\).
|
The tree in the first set of input data: After removing the edge \(1\) β \(3\), the tree will look as follows: The tree has split into two connected components. The first component consists of two vertices: \(1\) and \(2\). The second connected component consists of three vertices: \(3, 4\) and \(5\). In both connected components, there are at least two vertices. It can be shown that the answer \(3\) is not achievable, so the answer is \(2\).
|
Input: 65 11 21 33 43 52 11 26 11 22 33 44 55 63 11 21 38 21 21 32 42 53 63 73 86 21 22 31 44 55 6 | Output: 2 1 3 1 1 2
|
Medium
| 5 | 564 | 650 | 238 | 19 |
1,256 |
A
|
1256A
|
A. Payment Without Change
| 1,000 |
math
|
You have \(a\) coins of value \(n\) and \(b\) coins of value \(1\). You always pay in exact change, so you want to know if there exist such \(x\) and \(y\) that if you take \(x\) (\(0 \le x \le a\)) coins of value \(n\) and \(y\) (\(0 \le y \le b\)) coins of value \(1\), then the total value of taken coins will be \(S\).You have to answer \(q\) independent test cases.
|
The first line of the input contains one integer \(q\) (\(1 \le q \le 10^4\)) β the number of test cases. Then \(q\) test cases follow.The only line of the test case contains four integers \(a\), \(b\), \(n\) and \(S\) (\(1 \le a, b, n, S \le 10^9\)) β the number of coins of value \(n\), the number of coins of value \(1\), the value \(n\) and the required total value.
|
For the \(i\)-th test case print the answer on it β YES (without quotes) if there exist such \(x\) and \(y\) that if you take \(x\) coins of value \(n\) and \(y\) coins of value \(1\), then the total value of taken coins will be \(S\), and NO otherwise.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
|
Input: 4 1 2 3 4 1 2 3 6 5 2 6 27 3 3 5 18 | Output: YES NO NO YES
|
Beginner
| 1 | 370 | 370 | 396 | 12 |
|
1,781 |
B
|
1781B
|
B. Going to the Cinema
| 1,000 |
brute force; greedy; sortings
|
A company of \(n\) people is planning a visit to the cinema. Every person can either go to the cinema or not. That depends on how many other people will go. Specifically, every person \(i\) said: ""I want to go to the cinema if and only if at least \(a_i\) other people will go, not counting myself"". That means that person \(i\) will become sad if: they go to the cinema, and strictly less than \(a_i\) other people go; or they don't go to the cinema, and at least \(a_i\) other people go. In how many ways can a set of people going to the cinema be chosen so that nobody becomes sad?
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows.Each test case consists of two lines. The first line contains a single integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) β the number of people in the company.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le n - 1\)) β integers from peoples' claims.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, print a single integer β the number of different ways to choose a set of people going to the cinema so that nobody becomes sad.
|
In the first test case, both people want to go to the cinema if and only if the other person goes. There are two valid options: either both people go, or neither of them goes. However, if just one of them goes, both will be sad.In the second test case, everyone has to go to the cinema. In any other case, someone will be sad.In the third test case, there are three valid options: person number \(2\) goes to the cinema; or persons with indices \(2, 3, 4, 7\) go; or all eight people go.
|
Input: 421 170 1 2 3 4 5 686 0 3 3 6 7 2 753 0 0 3 3 | Output: 2 1 3 2
|
Beginner
| 3 | 586 | 531 | 147 | 17 |
1,385 |
E
|
1385E
|
E. Directing Edges
| 2,000 |
constructive algorithms; dfs and similar; graphs
|
You are given a graph consisting of \(n\) vertices and \(m\) edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges.You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges.You have to answer \(t\) independent test cases.
|
The first line of the input contains one integer \(t\) (\(1 \le t \le 2 \cdot 10^4\)) β the number of test cases. Then \(t\) test cases follow.The first line of the test case contains two integers \(n\) and \(m\) (\(2 \le n \le 2 \cdot 10^5\), \(1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})\)) β the number of vertices and the number of edges in the graph, respectively.The next \(m\) lines describe edges of the graph. The \(i\)-th edge is described with three integers \(t_i\), \(x_i\) and \(y_i\) (\(t_i \in [0; 1]\), \(1 \le x_i, y_i \le n\)) β the type of the edge (\(t_i = 0\) if the edge is undirected and \(t_i = 1\) if the edge is directed) and vertices this edge connects (the undirected edge connects vertices \(x_i\) and \(y_i\) and directed edge is going from the vertex \(x_i\) to the vertex \(y_i\)). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (\(x_i, y_i\)) there are no other pairs (\(x_i, y_i\)) or (\(y_i, x_i\))).It is guaranteed that both sum \(n\) and sum \(m\) do not exceed \(2 \cdot 10^5\) (\(\sum n \le 2 \cdot 10^5\); \(\sum m \le 2 \cdot 10^5\)).
|
For each test case print the answer β ""NO"" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print ""YES"" on the first line and \(m\) lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any.
|
Explanation of the second test case of the example:Explanation of the third test case of the example:
|
Input: 43 10 1 35 50 2 11 1 51 5 40 5 21 3 54 51 1 20 4 31 3 10 2 31 2 44 51 4 11 1 30 1 21 2 41 3 2 | Output: YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO
|
Hard
| 3 | 548 | 1,170 | 407 | 13 |
153 |
C
|
153C
|
C. Caesar Cipher
| 2,200 |
*special
|
Caesar cipher is one of the simplest encryption techniques. To transform the original message into encrypted one using key k, one has to replace each letter with a letter which is k positions later in the alphabet (if this takes the position beyond Z, the rest of it is counted from the start of the alphabet). In a more formal way, if letters of the alphabet are enumerated starting with 0, the result of encryption for character x will be (26 is the number of letters in the Latin alphabet).You are given the original message and the encryption key k. Output the resulting cipher.
|
The first line of input contains the original message β a sequence uppercase Latin letters (Β«AΒ»-Β«ZΒ»). The length of the message is from 1 to 10, inclusive.The second line contains an integer k (0 β€ k β€ 25).
|
Output the result of encryption.
|
Input: CODEFORCES5 | Output: HTIJKTWHJX
|
Hard
| 1 | 582 | 206 | 32 | 1 |
|
1,312 |
E
|
1312E
|
E. Array Shrinking
| 2,100 |
dp; greedy
|
You are given an array \(a_1, a_2, \dots, a_n\). You can perform the following operation any number of times: Choose a pair of two neighboring equal elements \(a_i = a_{i + 1}\) (if there is at least one such pair). Replace them by one element with value \(a_i + 1\). After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array \(a\) you can get?
|
The first line contains the single integer \(n\) (\(1 \le n \le 500\)) β the initial length of the array \(a\).The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 1000\)) β the initial array \(a\).
|
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
|
In the first test, this is one of the optimal sequences of operations: \(4\) \(3\) \(2\) \(2\) \(3\) \(\rightarrow\) \(4\) \(3\) \(3\) \(3\) \(\rightarrow\) \(4\) \(4\) \(3\) \(\rightarrow\) \(5\) \(3\).In the second test, this is one of the optimal sequences of operations: \(3\) \(3\) \(4\) \(4\) \(4\) \(3\) \(3\) \(\rightarrow\) \(4\) \(4\) \(4\) \(4\) \(3\) \(3\) \(\rightarrow\) \(4\) \(4\) \(4\) \(4\) \(4\) \(\rightarrow\) \(5\) \(4\) \(4\) \(4\) \(\rightarrow\) \(5\) \(5\) \(4\) \(\rightarrow\) \(6\) \(4\).In the third and fourth tests, you can't perform the operation at all.
|
Input: 5 4 3 2 2 3 | Output: 2
|
Hard
| 2 | 451 | 227 | 132 | 13 |
412 |
A
|
412A
|
A. Poster
| 900 |
greedy; implementation
|
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!
|
The first line contains two integers, n and k (1 β€ k β€ n β€ 100) β the number of characters in the slogan and the initial position of the ladder, correspondingly. The next line contains the slogan as n characters written without spaces. Each character of the slogan is either a large English letter, or digit, or one of the characters: '.', '!', ',', '?'.
|
In t lines, print the actions the programmers need to make. In the i-th line print: ""LEFT"" (without the quotes), if the i-th action was ""move the ladder to the left""; ""RIGHT"" (without the quotes), if the i-th action was ""move the ladder to the right""; ""PRINT x"" (without the quotes), if the i-th action was to ""go up the ladder, paint character x, go down the ladder"". The painting time (variable t) must be minimum possible. If there are multiple optimal painting plans, you can print any of them.
|
Note that the ladder cannot be shifted by less than one meter. The ladder can only stand in front of some square of the poster. For example, you cannot shift a ladder by half a meter and position it between two squares. Then go up and paint the first character and the second character.
|
Input: 2 2R1 | Output: PRINT 1LEFTPRINT R
|
Beginner
| 2 | 1,480 | 354 | 510 | 4 |
1,677 |
F
|
1677F
|
F. Tokitsukaze and Gems
| 3,500 |
dp; math
|
Tokitsukaze has a sequence with length of \(n\). She likes gems very much. There are \(n\) kinds of gems. The gems of the \(i\)-th kind are on the \(i\)-th position, and there are \(a_i\) gems of the same kind on that position. Define \(G(l,r)\) as the multiset containing all gems on the segment \([l,r]\) (inclusive).A multiset of gems can be represented as \(S=[s_1,s_2,\ldots,s_n]\), which is a non-negative integer sequence of length \(n\) and means that \(S\) contains \(s_i\) gems of the \(i\)-th kind in the multiset. A multiset \(T=[t_1,t_2,\ldots,t_n]\) is a multisubset of \(S=[s_1,s_2,\ldots,s_n]\) if and only if \(t_i\le s_i\) for any \(i\) satisfying \(1\le i\le n\).Now, given two positive integers \(k\) and \(p\), you need to calculate the result of$$$\(\sum_{l=1}^n \sum_{r=l}^n\sum\limits_{[t_1,t_2,\cdots,t_n] \subseteq G(l,r)}\left(\left(\sum_{i=1}^n p^{t_i}t_i^k\right)\left(\sum_{i=1}^n[t_i>0]\right)\right),\)\(where \)[t_i>0]=1\( if \)t_i>0\( and \)[t_i>0]=0\( if \)t_i=0\(.Since the answer can be quite large, print it modulo \)998\,244\,353$$$.
|
The first line contains three integers \(n\), \(k\) and \(p\) (\(1\le n \le 10^5\); \(1\le k\le 10^5\); \(2\le p\le 998\,244\,351\)) β the length of the sequence, the numbers \(k\) and \(p\).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1\le a_i\le 998\,244\,351\)) β the number of gems on the \(i\)-th position.
|
Print a single integers β the result modulo \(998\,244\,353\).
|
Input: 5 2 2 1 1 1 2 2 | Output: 6428
|
Master
| 2 | 1,072 | 335 | 62 | 16 |
|
1,304 |
F2
|
1304F2
|
F2. Animal Observation (hard version)
| 2,400 |
data structures; dp; greedy
|
The only difference between easy and hard versions is the constraint on \(k\).Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for \(n\) days, starting from day \(1\) to day \(n\). The forest can be divided into \(m\) areas, numbered from \(1\) to \(m\). He'll use the cameras in the following way: On every odd day (\(1\)-st, \(3\)-rd, \(5\)-th, ...), bring the red camera to the forest and record a video for \(2\) days. On every even day (\(2\)-nd, \(4\)-th, \(6\)-th, ...), bring the blue camera to the forest and record a video for \(2\) days. If he starts recording on the \(n\)-th day with one of the cameras, the camera records for only one day. Each camera can observe \(k\) consecutive areas of the forest. For example, if \(m=5\) and \(k=3\), he can put a camera to observe one of these three ranges of areas for two days: \([1,3]\), \([2,4]\), and \([3,5]\).Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for \(n\) days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.
|
The first line contains three integers \(n\), \(m\), and \(k\) (\(1 \le n \le 50\), \(1 \le m \le 2 \cdot 10^4\), \(1 \le k \le m\)) β the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next \(n\) lines contain \(m\) integers each. The \(j\)-th integer in the \(i+1\)-st line is the number of animals that can be seen on the \(i\)-th day in the \(j\)-th area. Each number of animals is between \(0\) and \(1000\), inclusive.
|
Print one integer β the maximum number of animals that can be observed.
|
The optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
|
Input: 4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 | Output: 25
|
Expert
| 3 | 1,372 | 498 | 71 | 13 |
524 |
F
|
524F
|
F. And Yet Another Bracket Sequence
| 2,700 |
data structures; greedy; hashing; string suffix structures; strings
|
Polycarpus has a finite sequence of opening and closing brackets. In order not to fall asleep in a lecture, Polycarpus is having fun with his sequence. He is able to perform two operations: adding any bracket in any position (in the beginning, the end, or between any two existing brackets); cyclic shift β moving the last bracket from the end of the sequence to the beginning. Polycarpus can apply any number of operations to his sequence and adding a cyclic shift in any order. As a result, he wants to get the correct bracket sequence of the minimum possible length. If there are several such sequences, Polycarpus is interested in the lexicographically smallest one. Help him find such a sequence.Acorrect bracket sequence is a sequence of opening and closing brackets, from which you can get a correct arithmetic expression by adding characters ""1"" and ""+"" . Each opening bracket must correspond to a closed one. For example, the sequences ""(())()"", ""()"", ""(()(()))"" are correct and "")("", ""(()"" and ""(()))("" are not.The sequence a1 a2... an is lexicographically smaller than sequence b1 b2... bn, if there is such number i from 1 to n, thatak = bk for 1 β€ k < i and ai < bi. Consider that ""("" < "")"".
|
The first line contains Polycarpus's sequence consisting of characters ""("" and "")"". The length of a line is from 1 to 1 000 000.
|
Print a correct bracket sequence of the minimum length that Polycarpus can obtain by his operations. If there are multiple such sequences, print the lexicographically minimum one.
|
The sequence in the first example is already correct, but to get the lexicographically minimum answer, you need to perform four cyclic shift operations. In the second example you need to add a closing parenthesis between the second and third brackets and make a cyclic shift. You can first make the shift, and then add the bracket at the end.
|
Input: ()(()) | Output: (())()
|
Master
| 5 | 1,224 | 132 | 179 | 5 |
1,854 |
E
|
1854E
|
E. Game Bundles
| 3,000 |
brute force; constructive algorithms; dp; greedy; math
|
Rishi is developing games in the 2D metaverse and wants to offer game bundles to his customers. Each game has an associated enjoyment value. A game bundle consists of a subset of games whose total enjoyment value adds up to \(60\).Your task is to choose \(k\) games, where \(1 \leq k \leq 60\), along with their respective enjoyment values \(a_1, a_2, \dots, a_k\), in such a way that exactly \(m\) distinct game bundles can be formed.
|
The input is a single integer \(m\) (\(1 \le m \le 10^{10}\)) β the desired number of game bundles.
|
The first line should contain an integer \(k\) (\(1 \le k \le 60\)) β the number of games.The second line should contain \(k\) integers, \(a_1, a_2, \dots, a_k\) (\(1 \le a_1, a_2, \dots, a_k \le 60\)) β the enjoyment values of the \(k\) games.
|
In the first sample, any subset of size \(3\) is a game bundle. There are \(4\) such subsets.
|
Input: 4 | Output: 4 20 20 20 20
|
Master
| 5 | 435 | 99 | 244 | 18 |
159 |
B
|
159B
|
B. Matchmaker
| 1,100 |
*special; greedy; sortings
|
Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, aj = xi.Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.
|
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 105) β the number of markers and the number of caps, correspondingly. Next n lines describe the markers. The i-th line contains two space-separated integers xi, yi (1 β€ xi, yi β€ 1000) β the i-th marker's color and diameter, correspondingly.Next m lines describe the caps. The j-th line contains two space-separated integers aj, bj (1 β€ aj, bj β€ 1000) β the color and diameter of the j-th cap, correspondingly.
|
Print two space-separated integers u, v, where u is the number of closed markers and v is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.
|
In the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed β the first and the third markers.
|
Input: 3 41 23 42 45 42 41 11 2 | Output: 3 2
|
Easy
| 3 | 591 | 488 | 357 | 1 |
1,187 |
D
|
1187D
|
D. Subarray Sorting
| 2,400 |
data structures; sortings
|
You are given an array \(a_1, a_2, \dots, a_n\) and an array \(b_1, b_2, \dots, b_n\).For one operation you can sort in non-decreasing order any subarray \(a[l \dots r]\) of the array \(a\).For example, if \(a = [4, 2, 2, 1, 3, 1]\) and you choose subbarray \(a[2 \dots 5]\), then the array turns into \([4, 1, 2, 2, 3, 1]\). You are asked to determine whether it is possible to obtain the array \(b\) by applying this operation any number of times (possibly zero) to the array \(a\).
|
The first line contains one integer \(t\) (\(1 \le t \le 3 \cdot 10^5\)) β the number of queries.The first line of each query contains one integer \(n\) (\(1 \le n \le 3 \cdot 10^5\)).The second line of each query contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le n\)).The third line of each query contains \(n\) integers \(b_1, b_2, \dots, b_n\) (\(1 \le b_i \le n\)).It is guaranteed that \(\sum n \le 3 \cdot 10^5\) over all queries in a test.
|
For each query print YES (in any letter case) if it is possible to obtain an array \(b\) and NO (in any letter case) otherwise.
|
In first test case the can sort subarray \(a_1 \dots a_5\), then \(a\) will turn into \([1, 1, 4, 4, 7, 5, 6]\), and then sort subarray \(a_5 \dots a_6\).
|
Input: 4 7 1 7 1 4 4 5 6 1 1 4 4 5 7 6 5 1 1 3 3 5 1 1 3 3 5 2 1 1 1 2 3 1 2 3 3 2 1 | Output: YES YES NO NO
|
Expert
| 2 | 484 | 462 | 127 | 11 |
44 |
I
|
44I
|
I. Toys
| 2,300 |
brute force; combinatorics
|
Little Masha loves arranging her toys into piles on the floor. And she also hates it when somebody touches her toys. One day Masha arranged all her n toys into several piles and then her elder brother Sasha came and gathered all the piles into one. Having seen it, Masha got very upset and started crying. Sasha still can't calm Masha down and mom is going to come home soon and punish Sasha for having made Masha crying. That's why he decides to restore the piles' arrangement. However, he doesn't remember at all the way the toys used to lie. Of course, Masha remembers it, but she can't talk yet and can only help Sasha by shouting happily when he arranges the toys in the way they used to lie. That means that Sasha will have to arrange the toys in every possible way until Masha recognizes the needed arrangement. The relative position of the piles and toys in every pile is irrelevant, that's why the two ways of arranging the toys are considered different if can be found two such toys that when arranged in the first way lie in one and the same pile and do not if arranged in the second way. Sasha is looking for the fastest way of trying all the ways because mom will come soon. With every action Sasha can take a toy from any pile and move it to any other pile (as a result a new pile may appear or the old one may disappear). Sasha wants to find the sequence of actions as a result of which all the pile arrangement variants will be tried exactly one time each. Help Sasha. As we remember, initially all the toys are located in one pile.
|
The first line contains an integer n (1 β€ n β€ 10) β the number of toys.
|
In the first line print the number of different variants of arrangement of toys into piles. Then print all the ways of arranging toys into piles in the order in which Sasha should try them (i.e. every next way must result from the previous one through the operation described in the statement). Every way should be printed in the following format. In every pile the toys should be arranged in ascending order of the numbers. Then the piles should be sorted in ascending order of the numbers of the first toys there. Output every way on a single line. Cf. the example to specify the output data format. If the solution is not unique, output any of them.
|
Input: 3 | Output: 5{1,2,3}{1,2},{3}{1},{2,3}{1},{2},{3}{1,3},{2}
|
Expert
| 2 | 1,548 | 71 | 652 | 0 |
|
487 |
C
|
487C
|
C. Prefix Product Sequence
| 2,300 |
constructive algorithms; math; number theory
|
Consider a sequence [a1, a2, ... , an]. Define its prefix product sequence .Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1].
|
The only input line contains an integer n (1 β€ n β€ 105).
|
In the first output line, print ""YES"" if such sequence exists, or print ""NO"" if no such sequence exists.If any solution exists, you should output n more lines. i-th line contains only an integer ai. The elements of the sequence should be different positive integers no larger than n.If there are multiple solutions, you are allowed to print any of them.
|
For the second sample, there are no valid sequences.
|
Input: 7 | Output: YES1436527
|
Expert
| 3 | 204 | 56 | 357 | 4 |
1,148 |
B
|
1148B
|
B. Born This Way
| 1,600 |
binary search; brute force; two pointers
|
Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.There are \(n\) flights from A to B, they depart at time moments \(a_1\), \(a_2\), \(a_3\), ..., \(a_n\) and arrive at B \(t_a\) moments later.There are \(m\) flights from B to C, they depart at time moments \(b_1\), \(b_2\), \(b_3\), ..., \(b_m\) and arrive at C \(t_b\) moments later.The connection time is negligible, so one can use the \(i\)-th flight from A to B and the \(j\)-th flight from B to C if and only if \(b_j \ge a_i + t_a\).You can cancel at most \(k\) flights. If you cancel a flight, Arkady can not use it.Arkady wants to be in C as early as possible, while you want him to be in C as late as possible. Find the earliest time Arkady can arrive at C, if you optimally cancel \(k\) flights. If you can cancel \(k\) or less flights in such a way that it is not possible to reach C at all, print \(-1\).
|
The first line contains five integers \(n\), \(m\), \(t_a\), \(t_b\) and \(k\) (\(1 \le n, m \le 2 \cdot 10^5\), \(1 \le k \le n + m\), \(1 \le t_a, t_b \le 10^9\)) β the number of flights from A to B, the number of flights from B to C, the flight time from A to B, the flight time from B to C and the number of flights you can cancel, respectively.The second line contains \(n\) distinct integers in increasing order \(a_1\), \(a_2\), \(a_3\), ..., \(a_n\) (\(1 \le a_1 < a_2 < \ldots < a_n \le 10^9\)) β the times the flights from A to B depart.The third line contains \(m\) distinct integers in increasing order \(b_1\), \(b_2\), \(b_3\), ..., \(b_m\) (\(1 \le b_1 < b_2 < \ldots < b_m \le 10^9\)) β the times the flights from B to C depart.
|
If you can cancel \(k\) or less flights in such a way that it is not possible to reach C at all, print \(-1\).Otherwise print the earliest time Arkady can arrive at C if you cancel \(k\) flights in such a way that maximizes this time.
|
Consider the first example. The flights from A to B depart at time moments \(1\), \(3\), \(5\), and \(7\) and arrive at B at time moments \(2\), \(4\), \(6\), \(8\), respectively. The flights from B to C depart at time moments \(1\), \(2\), \(3\), \(9\), and \(10\) and arrive at C at time moments \(2\), \(3\), \(4\), \(10\), \(11\), respectively. You can cancel at most two flights. The optimal solution is to cancel the first flight from A to B and the fourth flight from B to C. This way Arkady has to take the second flight from A to B, arrive at B at time moment \(4\), and take the last flight from B to C arriving at C at time moment \(11\).In the second example you can simply cancel all flights from A to B and you're done.In the third example you can cancel only one flight, and the optimal solution is to cancel the first flight from A to B. Note that there is still just enough time to catch the last flight from B to C.
|
Input: 4 5 1 1 2 1 3 5 7 1 2 3 9 10 | Output: 11
|
Medium
| 3 | 984 | 744 | 234 | 11 |
1,703 |
C
|
1703C
|
C. Cypher
| 800 |
brute force; implementation; strings
|
Luca has a cypher made up of a sequence of \(n\) wheels, each with a digit \(a_i\) written on it. On the \(i\)-th wheel, he made \(b_i\) moves. Each move is one of two types: up move (denoted by \(\texttt{U}\)): it increases the \(i\)-th digit by \(1\). After applying the up move on \(9\), it becomes \(0\). down move (denoted by \(\texttt{D}\)): it decreases the \(i\)-th digit by \(1\). After applying the down move on \(0\), it becomes \(9\). Example for \(n=4\). The current sequence is 0 0 0 0. Luca knows the final sequence of wheels and the moves for each wheel. Help him find the original sequence and crack the cypher.
|
The first line contains a single integer \(t\) (\(1 \leq t \leq 100\)) β the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \leq n \leq 100\)) β the number of wheels.The second line contains \(n\) integers \(a_i\) (\(0 \leq a_i \leq 9\)) β the digit shown on the \(i\)-th wheel after all moves have been performed.Then \(n\) lines follow, the \(i\)-th of which contains the integer \(b_i\) (\(1 \leq b_i \leq 10\)) and \(b_i\) characters that are either \(\texttt{U}\) or \(\texttt{D}\) β the number of moves performed on the \(i\)-th wheel, and the moves performed. \(\texttt{U}\) and \(\texttt{D}\) represent an up move and a down move respectively.
|
For each test case, output \(n\) space-separated digits β the initial sequence of the cypher.
|
In the first test case, we can prove that initial sequence was \([2,1,1]\). In that case, the following moves were performed: On the first wheel: \(2 \xrightarrow[\texttt{D}]{} 1 \xrightarrow[\texttt{D}]{} 0 \xrightarrow[\texttt{D}]{} 9\). On the second wheel: \(1 \xrightarrow[\texttt{U}]{} 2 \xrightarrow[\texttt{D}]{} 1 \xrightarrow[\texttt{U}]{} 2 \xrightarrow[\texttt{U}]{} 3\). On the third wheel: \(1 \xrightarrow[\texttt{D}]{} 0 \xrightarrow[\texttt{U}]{} 1\). The final sequence was \([9,3,1]\), which matches the input.
|
Input: 339 3 13 DDD4 UDUU2 DU20 99 DDDDDDDDD9 UUUUUUUUU50 5 9 8 310 UUUUUUUUUU3 UUD8 UUDUUDDD10 UUDUUDUDDU4 UUUU | Output: 2 1 1 9 0 0 4 9 6 9
|
Beginner
| 3 | 628 | 695 | 93 | 17 |
2,041 |
I
|
2041I
|
I. Auto Complete
| 2,300 |
binary search; data structures; hashing; implementation; sortings; strings; trees
|
You are designing a snazzy new text editor, and you want to add a nifty auto-complete feature to help users save time. Here is how it will work: if a user types ""App"", your editor will magically suggest the word ""Application""! Even better, users can personalize the words that auto-complete in your editor.Your editor will support 4 kinds of operations (Let's say the current text in your editor is \(t\)): Add an auto complete pattern \(p_i\). Delete an auto complete pattern \(p_i\). Append a string \(s\) to the end of \(t\). Delete \(c\) characters from the end of \(t\). Note that if \(c\) is larger then the length of \(t\), delete all the characters from \(t\). After each action, your editor should suggest an auto-complete candidate \(i\) that matches the following criteria: The string \(p_i\) has a prefix equal to \(t\). If there are multiple \(p_i\), pick the longest one. If there are still multiple \(p_i\), pick the one with the smallest lexicographic order. If there are still multiple \(p_i\), pick the one with the smallest ID. To simplify the question, for each action, print the suggested auto complete pattern ID. If there's no match, print -1.For example, let us say we have three candidates: ""alice"", ""bob"", and ""charlie"", with ID 1, 2, and 3. At first, there is nothing on the screen, so ""charlie"" (3) should be suggested because it is the longest. Then, let us say the user types ""b"". You should suggest ""bob"" (2) because it is the only one that starts with ""b"". Finally, let us say the user type ""body"". You should print -1 because there is no matched pattern.
|
The first line contains an integer \(n\), followed by \(n\) lines, with each line containing an action.There are four types of actions: \(i\) \(p_i\) \(i\) \(s\) \(c\) The add actions are followed by an integer \(i\) and a pattern \(p_i\), which means the user wants to add a pattern with ID \(i\). The delete actions are followed by an integer \(i\), which means the user wants to delete \(p_i\) from the pattern set. The append actions are followed by a string \(s\), which means the user appends \(s\) to the end of \(t\). The backspace actions are followed by an integer \(c\), which means the user deletes \(c\) characters from the end of \(t\). All the parameters are splitted by a single space character. \(1 \leq n \leq 10^6\) The total number of characters in all \(p_i\) and \(s\) does not exceed \(2\times 10^6\). \(1 \leq c \leq 2\times 10^6\) The strings \(p_i\) and \(s\) may contain any printable characters, excluding all space characters (ASCII number in the range from \(33\) to \(126\)). The ID \(i\) for each add operation is unique. The ID \(i\) for each delete is guaranteed to be valid. Each ID \(i\) satisfies \(0\le i \le n\).
|
The program should output \(n\) lines. For each action, output an integer \(i\), which means that after the action, \(p_i\) is the suggested auto complete candidate. If there is no \(p_i\) that matches the requirement, output -1.
|
Input: 6 add 1 pattern1_alice add 2 pattern2_bob add 3 pattern3_charlie append pattern append 2_bobabc backspace 3 | Output: 1 1 3 3 -1 2
|
Expert
| 7 | 1,607 | 1,151 | 229 | 20 |
|
1,294 |
E
|
1294E
|
E. Obtain a Permutation
| 1,900 |
greedy; implementation; math
|
You are given a rectangular matrix of size \(n \times m\) consisting of integers from \(1\) to \(2 \cdot 10^5\).In one move, you can: choose any element of the matrix and change its value to any integer between \(1\) and \(n \cdot m\), inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some \(j\) (\(1 \le j \le m\)) and set \(a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j}\) simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where \(a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m\) (i.e. \(a_{i, j} = (i - 1) \cdot m + j\)) with the minimum number of moves performed.
|
The first line of the input contains two integers \(n\) and \(m\) (\(1 \le n, m \le 2 \cdot 10^5, n \cdot m \le 2 \cdot 10^5\)) β the size of the matrix.The next \(n\) lines contain \(m\) integers each. The number at the line \(i\) and position \(j\) is \(a_{i, j}\) (\(1 \le a_{i, j} \le 2 \cdot 10^5\)).
|
Print one integer β the minimum number of moves required to obtain the matrix, where \(a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m\) (\(a_{i, j} = (i - 1)m + j\)).
|
In the first example, you can set \(a_{1, 1} := 7, a_{1, 2} := 8\) and \(a_{1, 3} := 9\) then shift the first, the second and the third columns cyclically, so the answer is \(6\). It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is \(0\).In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is \(2\).
|
Input: 3 3 3 2 1 1 2 3 4 5 6 | Output: 6
|
Hard
| 3 | 914 | 305 | 232 | 12 |
321 |
C
|
321C
|
C. Ciel the Commander
| 2,100 |
constructive algorithms; dfs and similar; divide and conquer; greedy; trees
|
Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has n cities connected by n - 1 undirected roads, and for any two cities there always exists a path between them.Fox Ciel needs to assign an officer to each city. Each officer has a rank β a letter from 'A' to 'Z'. So there will be 26 different ranks, and 'A' is the topmost, so 'Z' is the bottommost.There are enough officers of each rank. But there is a special rule must obey: if x and y are two distinct cities and their officers have the same rank, then on the simple path between x and y there must be a city z that has an officer with higher rank. The rule guarantee that a communications between same rank officers will be monitored by higher rank officer.Help Ciel to make a valid plan, and if it's impossible, output ""Impossible!"".
|
The first line contains an integer n (2 β€ n β€ 105) β the number of cities in Tree Land.Each of the following n - 1 lines contains two integers a and b (1 β€ a, b β€ n, a β b) β they mean that there will be an undirected road between a and b. Consider all the cities are numbered from 1 to n.It guaranteed that the given graph will be a tree.
|
If there is a valid plane, output n space-separated characters in a line β i-th character is the rank of officer in the city with number i. Otherwise output ""Impossible!"".
|
In the first example, for any two officers of rank 'B', an officer with rank 'A' will be on the path between them. So it is a valid solution.
|
Input: 41 21 31 4 | Output: A B B B
|
Hard
| 5 | 821 | 339 | 173 | 3 |
794 |
D
|
794D
|
D. Labelling Cities
| 2,400 |
dfs and similar; graphs; hashing
|
Oleg the bank client lives in Bankopolia. There are n cities in Bankopolia and some pair of cities are connected directly by bi-directional roads. The cities are numbered from 1 to n. There are a total of m roads in Bankopolia, the i-th road connects cities ui and vi. It is guaranteed that from each city it is possible to travel to any other city using some of the roads.Oleg wants to give a label to each city. Suppose the label of city i is equal to xi. Then, it must hold that for all pairs of cities (u, v) the condition |xu - xv| β€ 1 holds if and only if there is a road connecting u and v.Oleg wonders if such a labeling is possible. Find an example of such labeling if the task is possible and state that it is impossible otherwise.
|
The first line of input contains two space-separated integers n and m (2 β€ n β€ 3Β·105, 1 β€ m β€ 3Β·105) β the number of cities and the number of roads.Next, m lines follow. The i-th line contains two space-separated integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the cities connected by the i-th road. It is guaranteed that there is at most one road between each pair of cities and it is possible to travel from any city to any other city using some roads.
|
If the required labeling is not possible, output a single line containing the string ""NO"" (without quotes).Otherwise, output the string ""YES"" (without quotes) on the first line. On the next line, output n space-separated integers, x1, x2, ..., xn. The condition 1 β€ xi β€ 109 must hold for all i, and for all pairs of cities (u, v) the condition |xu - xv| β€ 1 must hold if and only if there is a road connecting u and v.
|
For the first sample, x1 = 2, x2 = 3, x3 = x4 = 1 is a valid labeling. Indeed, (3, 4), (1, 2), (1, 3), (1, 4) are the only pairs of cities with difference of labels not greater than 1, and these are precisely the roads of Bankopolia.For the second sample, all pairs of cities have difference of labels not greater than 1 and all pairs of cities have a road connecting them.For the last sample, it is impossible to construct a labeling satisfying the given constraints.
|
Input: 4 41 21 31 43 4 | Output: YES2 3 1 1
|
Expert
| 3 | 741 | 453 | 423 | 7 |
270 |
A
|
270A
|
A. Fancy Fence
| 1,100 |
geometry; implementation; math
|
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to a?
|
The first line of input contains an integer t (0 < t < 180) β the number of tests. Each of the following t lines contains a single integer a (0 < a < 180) β the angle the robot can make corners at measured in degrees.
|
For each test, output on a single line ""YES"" (without quotes), if the robot can build a fence Emuskald wants, and ""NO"" (without quotes), if it is impossible.
|
In the first test case, it is impossible to build the fence, since there is no regular polygon with angle .In the second test case, the fence is a regular triangle, and in the last test case β a square.
|
Input: 3306090 | Output: NOYESYES
|
Easy
| 3 | 395 | 217 | 161 | 2 |
632 |
E
|
632E
|
E. Thief in a Shop
| 2,400 |
divide and conquer; dp; fft; math
|
A thief made his way to a shop.As usual he has his lucky knapsack with him. The knapsack can contain k objects. There are n kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind i is ai.The thief is greedy, so he will take exactly k products (it's possible for some kinds to take several products of that kind).Find all the possible total costs of products the thief can nick into his knapsack.
|
The first line contains two integers n and k (1 β€ n, k β€ 1000) β the number of kinds of products and the number of products the thief will take.The second line contains n integers ai (1 β€ ai β€ 1000) β the costs of products for kinds from 1 to n.
|
Print the only line with all the possible total costs of stolen products, separated by a space. The numbers should be printed in the ascending order.
|
Input: 3 21 2 3 | Output: 2 3 4 5 6
|
Expert
| 4 | 451 | 245 | 149 | 6 |
|
1,896 |
C
|
1896C
|
C. Matching Arrays
| 1,400 |
binary search; constructive algorithms; greedy; sortings
|
You are given two arrays \(a\) and \(b\) of size \(n\). The beauty of the arrays \(a\) and \(b\) is the number of indices \(i\) such that \(a_i > b_i\).You are also given an integer \(x\). Determine whether it is possible to rearrange the elements of \(b\) such that the beauty of the arrays becomes \(x\). If it is possible, output one valid rearrangement of \(b\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows.The first line of each test case contains two integers \(n\) and \(x\) (\(1 \le n \le 2\cdot 10^5\), \(0 \le x \le n\)) β the size of arrays \(a\) and \(b\) and the desired beauty of the arrays.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 2n\)) β the elements of array \(a\).The third line of each test case contains \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(1 \le b_i \le 2n\)) β the elements of array \(b\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot 10^5\).
|
For each test case, output ""NO"" if it is not possible to rearrange \(b\) to make the beauty of the arrays equal to \(x\).Otherwise, output ""YES"". Then, on the next line, output \(n\) integers which represent the rearrangement of \(b\).If there are multiple solutions, you may output any of them.You can output ""YES"" and ""NO"" in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
|
In test cases 1 and 2, the beauty of the arrays has to be \(0\) since \(a_1 = 1 \le 2 = b_1\).In test cases 3, 4, 5 and 6, the only possible beauty of the arrays is \(x = 1\) and \(x = 2\). In particular, if \(b\) is rearranged to \([2, 4, 1]\), then \(a_3 = 3 > 1 = b_3\), so the beauty of the arrays is \(1\). If \(b\) is kept in the same order as given the input, then \(a_2 = 4 > b_2 = 1\) and \(a_3 = 3 > 2 = b_3\), so the beauty of the arrays is \(2\).
|
Input: 71 0121 1123 02 4 34 1 23 12 4 34 1 23 22 4 34 1 23 32 4 34 1 25 26 4 5 6 29 7 9 1 1 | Output: YES 2 NO NO YES 2 4 1 YES 4 1 2 NO YES 1 9 9 7 1
|
Easy
| 4 | 366 | 719 | 468 | 18 |
1,091 |
B
|
1091B
|
B. New Year and the Treasure Geolocation
| 1,200 |
brute force; constructive algorithms; greedy; implementation
|
Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point \(T\), which coordinates to be found out.Bob travelled around the world and collected clues of the treasure location at \(n\) obelisks. These clues were in an ancient language, and he has only decrypted them at home. Since he does not know which clue belongs to which obelisk, finding the treasure might pose a challenge. Can you help him?As everyone knows, the world is a two-dimensional plane. The \(i\)-th obelisk is at integer coordinates \((x_i, y_i)\). The \(j\)-th clue consists of \(2\) integers \((a_j, b_j)\) and belongs to the obelisk \(p_j\), where \(p\) is some (unknown) permutation on \(n\) elements. It means that the treasure is located at \(T=(x_{p_j} + a_j, y_{p_j} + b_j)\). This point \(T\) is the same for all clues.In other words, each clue belongs to exactly one of the obelisks, and each obelisk has exactly one clue that belongs to it. A clue represents the vector from the obelisk to the treasure. The clues must be distributed among the obelisks in such a way that they all point to the same position of the treasure.Your task is to find the coordinates of the treasure. If there are multiple solutions, you may print any of them.Note that you don't need to find the permutation. Permutations are used only in order to explain the problem.
|
The first line contains an integer \(n\) (\(1 \leq n \leq 1000\)) β the number of obelisks, that is also equal to the number of clues.Each of the next \(n\) lines contains two integers \(x_i\), \(y_i\) (\(-10^6 \leq x_i, y_i \leq 10^6\)) β the coordinates of the \(i\)-th obelisk. All coordinates are distinct, that is \(x_i \neq x_j\) or \(y_i \neq y_j\) will be satisfied for every \((i, j)\) such that \(i \neq j\). Each of the next \(n\) lines contains two integers \(a_i\), \(b_i\) (\(-2 \cdot 10^6 \leq a_i, b_i \leq 2 \cdot 10^6\)) β the direction of the \(i\)-th clue. All coordinates are distinct, that is \(a_i \neq a_j\) or \(b_i \neq b_j\) will be satisfied for every \((i, j)\) such that \(i \neq j\). It is guaranteed that there exists a permutation \(p\), such that for all \(i,j\) it holds \(\left(x_{p_i} + a_i, y_{p_i} + b_i\right) = \left(x_{p_j} + a_j, y_{p_j} + b_j\right)\).
|
Output a single line containing two integers \(T_x, T_y\) β the coordinates of the treasure.If there are multiple answers, you may print any of them.
|
As \(n = 2\), we can consider all permutations on two elements. If \(p = [1, 2]\), then the obelisk \((2, 5)\) holds the clue \((7, -2)\), which means that the treasure is hidden at \((9, 3)\). The second obelisk \((-6, 4)\) would give the clue \((-1,-3)\) and the treasure at \((-7, 1)\). However, both obelisks must give the same location, hence this is clearly not the correct permutation.If the hidden permutation is \([2, 1]\), then the first clue belongs to the second obelisk and the second clue belongs to the first obelisk. Hence \((-6, 4) + (7, -2) = (2,5) + (-1,-3) = (1, 2)\), so \(T = (1,2)\) is the location of the treasure. In the second sample, the hidden permutation is \([2, 3, 4, 1]\).
|
Input: 2 2 5 -6 4 7 -2 -1 -3 | Output: 1 2
|
Easy
| 4 | 1,379 | 896 | 149 | 10 |
847 |
L
|
847L
|
L. Berland SU Computer Network
| 2,400 |
constructive algorithms; dfs and similar; graphs; hashing; trees
|
In the computer network of the Berland State University there are n routers numbered from 1 to n. Some pairs of routers are connected by patch cords. Information can be transmitted over patch cords in both direction. The network is arranged in such a way that communication between any two routers (directly or through other routers) is possible. There are no cycles in the network, so there is only one path between each pair of routers over patch cords.Unfortunately, the exact topology of the network was lost by administrators. In order to restore it, the following auxiliary information was collected.For each patch cord p, directly connected to the router i, list of routers located behind the patch cord p relatively i is known. In other words, all routers path from which to the router i goes through p are known. So for each router i there are ki lists, where ki is the number of patch cords connected to i.For example, let the network consists of three routers connected in chain 1 - 2 - 3. Then: the router 1: for the single patch cord connected to the first router there is a single list containing two routers: 2 and 3; the router 2: for each of the patch cords connected to the second router there is a list: one list contains the router 1 and the other β the router 3; the router 3: for the single patch cord connected to the third router there is a single list containing two routers: 1 and 2. Your task is to help administrators to restore the network topology, i. e. to identify all pairs of routers directly connected by a patch cord.
|
The first line contains a single integer n (2 β€ n β€ 1000) β the number of routers in the network.The i-th of the following n lines contains a description of the lists for the router i.The description of each list begins with the number of routers in it. Then the symbol ':' follows, and after that the numbers of routers from the list are given. This numbers are separated by comma. Lists are separated by symbol '-'.It is guaranteed, that for each router i the total number of routers in its lists equals to n - 1 and all the numbers in lists of each router are distinct. For each router i lists do not contain the number i.
|
Print -1 if no solution exists.In the other case print to the first line n - 1 β the total number of patch cords in the network. In each of the following n - 1 lines print two integers β the routers which are directly connected by a patch cord. Information about each patch cord must be printed exactly once.Patch cords and routers can be printed in arbitrary order.
|
The first example is analyzed in the statement.The answer to the second example is shown on the picture. The first router has one list, which contains all other routers. The second router has three lists: the first β the single router 4, the second β the single router 1, the third β two routers 3 and 5. The third router has one list, which contains all other routers. The fourth router also has one list, which contains all other routers. The fifth router has two lists: the first β the single router 3, the second β three routers 1, 2 and 4.
|
Input: 32:3,21:1-1:32:1,2 | Output: 22 12 3
|
Expert
| 5 | 1,553 | 625 | 366 | 8 |
1,832 |
F
|
1832F
|
F. Zombies
| 3,200 |
binary search; dp
|
Polycarp plays a computer game in a post-apocalyptic setting. The zombies have taken over the world, and Polycarp with a small team of survivors is defending against hordes trying to invade their base. The zombies are invading for \(x\) minutes starting from minute \(0\). There are \(n\) entrances to the base, and every minute one zombie attempts to enter through every entrance.The survivors can defend the entrances against the zombies. There are two options: manually β shoot the zombies coming through a certain entrance; automatically β set up an electric fence on a certain entrance to fry the zombies. If an entrance is defended either or both ways during some minute, no zombie goes through.Every entrance is defended by a single dedicated survivor. The \(i\)-th entrance is defended manually from minute \(l_i\) until minute \(r_i\), non-inclusive β \([l_i, r_i)\).There are \(k\) generators that can be used to defend the entrances automatically. Every entrance should be connected to exactly one generator, but a generator can be connected to multiple entrances (or even none of them). Each generator will work for exactly \(m\) consecutive minutes. Polycarp can choose when to power on each generator independently of each other, the \(m\) minute long interval should be fully inside the \([0, x)\) time interval.Polycarp is a weird gamer. He wants the game to be as difficult as possible for him. So he wants to connect each entrance to a generator and choose the time for each generator in such a way that as many zombies as possible enter the base. Please, help him to achieve that!
|
The first line contains four integers \(n, k, x\) and \(m\) (\(1 \le k \le n \le 2000\); \(1 \le m \le x \le 10^9\)) β the number of entrances, the number of generators, the duration of the zombie invasion and the duration of all generators.The \(i\)-th of the next \(n\) lines contains two integers \(l_i\) and \(r_i\) (\(0 \le l_i < r_i \le x\)) β the time interval the \(i\)-th entrance is defended manually.
|
Print a single integer β the largest number of zombies that can enter the base after Polycarp connects each entrance to some generator and chooses the time for each generator.
|
Input: 3 3 10 3 0 2 1 7 4 7 | Output: 18
|
Master
| 2 | 1,599 | 411 | 175 | 18 |
|
1,012 |
D
|
1012D
|
D. AB-Strings
| 2,800 |
constructive algorithms; strings
|
There are two strings s and t, consisting only of letters a and b. You can make the following operation several times: choose a prefix of s, a prefix of t and swap them. Prefixes can be empty, also a prefix can coincide with a whole string. Your task is to find a sequence of operations after which one of the strings consists only of a letters and the other consists only of b letters. The number of operations should be minimized.
|
The first line contains a string s (1 β€ |s| β€ 2Β·105).The second line contains a string t (1 β€ |t| β€ 2Β·105).Here |s| and |t| denote the lengths of s and t, respectively. It is guaranteed that at least one of the strings contains at least one a letter and at least one of the strings contains at least one b letter.
|
The first line should contain a single integer n (0 β€ n β€ 5Β·105) β the number of operations.Each of the next n lines should contain two space-separated integers ai, bi β the lengths of prefixes of s and t to swap, respectively.If there are multiple possible solutions, you can print any of them. It's guaranteed that a solution with given constraints exists.
|
In the first example, you can solve the problem in two operations: Swap the prefix of the first string with length 1 and the prefix of the second string with length 0. After this swap, you'll have strings ab and bbb. Swap the prefix of the first string with length 1 and the prefix of the second string with length 3. After this swap, you'll have strings bbbb and a. In the second example, the strings are already appropriate, so no operations are needed.
|
Input: babbb | Output: 21 01 3
|
Master
| 2 | 432 | 313 | 358 | 10 |
427 |
E
|
427E
|
E. Police Patrol
| 2,000 |
greedy; implementation; math; ternary search
|
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station. The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
|
The first line of the input will have two integers n (1 β€ n β€ 106) and m (1 β€ m β€ 106) separated by spaces. The next line will contain n integers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x, 0) of the plane. The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane.Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.
|
Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.
|
Input: 3 61 2 3 | Output: 4
|
Hard
| 4 | 1,299 | 701 | 110 | 4 |
|
1,662 |
H
|
1662H
|
H. Boundary
| 0 |
brute force; math
|
Bethany would like to tile her bathroom. The bathroom has width \(w\) centimeters and length \(l\) centimeters. If Bethany simply used the basic tiles of size \(1 \times 1\) centimeters, she would use \(w \cdot l\) of them. However, she has something different in mind. On the interior of the floor she wants to use the \(1 \times 1\) tiles. She needs exactly \((w-2) \cdot (l-2)\) of these. On the floor boundary she wants to use tiles of size \(1 \times a\) for some positive integer \(a\). The tiles can also be rotated by \(90\) degrees. For which values of \(a\) can Bethany tile the bathroom floor as described? Note that \(a\) can also be \(1\).
|
Each test contains multiple test cases. The first line contains an integer \(t\) (\(1\le t\le 100\)) β the number of test cases. The descriptions of the \(t\) test cases follow.Each test case consist of a single line, which contains two integers \(w\), \(l\) (\(3 \leq w, l \leq 10^{9}\)) β the dimensions of the bathroom.
|
For each test case, print an integer \(k\) (\(0\le k\)) β the number of valid values of \(a\) for the given test case β followed by \(k\) integers \(a_1, a_2,\dots, a_k\) (\(1\le a_i\)) β the valid values of \(a\). The values \(a_1, a_2, \dots, a_k\) have to be sorted from smallest to largest.It is guaranteed that under the problem constraints, the output contains at most \(200\,000\) integers.
|
In the first test case, the bathroom is \(3\) centimeters wide and \(5\) centimeters long. There are three values of \(a\) such that Bethany can tile the floor as described in the statement, namely \(a=1\), \(a=2\) and \(a=3\). The three tilings are represented in the following pictures.
|
Input: 33 512 12314159265 358979323 | Output: 3 1 2 3 3 1 2 11 2 1 2
|
Beginner
| 2 | 652 | 322 | 397 | 16 |
774 |
H
|
774H
|
H. Repairing Of String
| 2,200 |
*special; constructive algorithms
|
Stepan had a favorite string s which consisted of the lowercase letters of the Latin alphabet. After graduation, he decided to remember it, but it was a long time ago, so he can't now remember it. But Stepan remembers some information about the string, namely the sequence of integers c1, c2, ..., cn, where n equals the length of the string s, and ci equals the number of substrings in the string s with the length i, consisting of the same letters. The substring is a sequence of consecutive characters in the string s.For example, if the Stepan's favorite string is equal to ""tttesst"", the sequence c looks like: c = [7, 3, 1, 0, 0, 0, 0].Stepan asks you to help to repair his favorite string s according to the given sequence c1, c2, ..., cn.
|
The first line contains the integer n (1 β€ n β€ 2000) β the length of the Stepan's favorite string.The second line contains the sequence of integers c1, c2, ..., cn (0 β€ ci β€ 2000), where ci equals the number of substrings of the string s with the length i, consisting of the same letters.It is guaranteed that the input data is such that the answer always exists.
|
Print the repaired Stepan's favorite string. If there are several answers, it is allowed to print any of them. The string should contain only lowercase letters of the English alphabet.
|
In the first test Stepan's favorite string, for example, can be the string ""kkrrrq"", because it contains 6 substrings with the length 1, consisting of identical letters (they begin in positions 1, 2, 3, 4, 5 and 6), 3 substrings with the length 2, consisting of identical letters (they begin in positions 1, 3 and 4), and 1 substring with the length 3, consisting of identical letters (it begins in the position 3).
|
Input: 66 3 1 0 0 0 | Output: kkrrrq
|
Hard
| 2 | 748 | 363 | 184 | 7 |
1,580 |
A
|
1580A
|
A. Portal
| 1,700 |
brute force; data structures; dp; greedy; implementation
|
CQXYM found a rectangle \(A\) of size \(n \times m\). There are \(n\) rows and \(m\) columns of blocks. Each block of the rectangle is an obsidian block or empty. CQXYM can change an obsidian block to an empty block or an empty block to an obsidian block in one operation.A rectangle \(M\) size of \(a \times b\) is called a portal if and only if it satisfies the following conditions: \(a \geq 5,b \geq 4\). For all \(1 < x < a\), blocks \(M_{x,1}\) and \(M_{x,b}\) are obsidian blocks. For all \(1 < x < b\), blocks \(M_{1,x}\) and \(M_{a,x}\) are obsidian blocks. For all \(1<x<a,1<y<b\), block \(M_{x,y}\) is an empty block. \(M_{1, 1}, M_{1, b}, M_{a, 1}, M_{a, b}\) can be any type. Note that the there must be \(a\) rows and \(b\) columns, not \(b\) rows and \(a\) columns.Note that corners can be any typeCQXYM wants to know the minimum number of operations he needs to make at least one sub-rectangle a portal.
|
The first line contains an integer \(t\) (\(t \geq 1\)), which is the number of test cases.For each test case, the first line contains two integers \(n\) and \(m\) (\(5 \le n \le 400\), \(4 \le m \le 400\)). Then \(n\) lines follow, each line contains \(m\) characters \(0\) or \(1\). If the \(j\)-th character of \(i\)-th line is \(0\), block \(A_{i,j}\) is an empty block. Otherwise, block \(A_{i,j}\) is an obsidian block.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(400\).It is guaranteed that the sum of \(m\) over all test cases does not exceed \(400\).
|
Output \(t\) answers, and each answer in a line.
|
In the first test case, the final portal is like this:11101001100110010111
|
Input: 1 5 4 1000 0000 0110 0000 0001 | Output: 12
|
Medium
| 5 | 919 | 591 | 48 | 15 |
713 |
B
|
713B
|
B. Searching Rectangles
| 2,200 |
binary search; constructive algorithms; interactive
|
Filya just learned new geometry object β rectangle. He is given a field consisting of n Γ n unit cells. Rows are numbered from bottom to top with integer from 1 to n. Columns are numbered from left to right with integers from 1 to n. Cell, located at the intersection of the row r and column c is denoted as (r, c). Filya has painted two rectangles, such that their sides are parallel to coordinate axes and each cell lies fully inside or fully outside each of them. Moreover, no cell lies in both rectangles.Later, hedgehog Filya became interested in the location of his rectangles but was unable to find the sheet of paper they were painted on. They were taken by Sonya and now she wants to play a little game with Filya. He tells her a query rectangle and she replies with the number of initial rectangles that lie fully inside the given query rectangle. The query rectangle should match the same conditions as initial rectangles. Rectangle lies fully inside the query if each o its cells lies inside the query.Filya knows Sonya really well, so is sure that if he asks more than 200 questions she will stop to reply.
|
The first line of the input contains an integer n (2 β€ n β€ 216) β size of the field.For each query an integer between 0 and 2 is returned β the number of initial rectangles that lie fully inside the query rectangle.
|
To make a query you have to print ""? x1 y1 x2 y2"" (without quotes) (1 β€ x1 β€ x2 β€ n, 1 β€ y1 β€ y2 β€ n), where (x1, y1) stands for the position of the bottom left cell of the query and (x2, y2) stands for the up right cell of the query. You are allowed to ask no more than 200 queries. After each query you should perform ""flush"" operation and read the answer.In case you suppose you've already determined the location of two rectangles (or run out of queries) you should print ""! x11 y11 x12 y12 x21 y21 x22 y22"" (without quotes), where first four integers describe the bottom left and up right cells of the first rectangle, and following four describe the corresponding cells of the second rectangle. You can print the rectangles in an arbitrary order. After you have printed the answer, print the end of the line and perform ""flush"". Your program should terminate immediately after it print the answer.
|
Input: 521011101 | Output: ? 1 1 5 5? 1 1 3 3? 1 1 3 1? 2 2 2 2? 3 3 5 5? 3 3 3 5? 3 3 3 4? 3 4 3 5! 2 2 2 2 3 4 3 5
|
Hard
| 3 | 1,119 | 215 | 911 | 7 |
|
1,268 |
D
|
1268D
|
D. Invertation in Tournament
| 3,200 |
brute force; divide and conquer; graphs; math
|
You are given a tournament β complete directed graph.In one operation you can pick any vertex \(v\) and change the direction of all edges with \(v\) on one of the ends (i.e all edges \(u \to v\) change their orientation to \(v \to u\) and vice versa).You want to make the tournament strongly connected with the smallest possible number of such operations if it is possible. Also, if it is possible, you need to find the number of ways to make this number of operations to make graph strongly connected (two ways are different if for some \(i\) vertex that we chose on \(i\)-th operation in one way is different from vertex that we chose on \(i\)-th operation in another way). You only need to find this value modulo \(998\,244\,353\).
|
The first line of input contains one integer \(n\) (\(3 \leq n \leq 2000\)): the number of vertices in the tournament.Following \(n\) lines contain a description of the given tournament, each of them contains a binary string of length \(n\). If \(j\)-th character of \(i\)-th string is equal to '1', then the graph has an edge \(i \to j\).It is guaranteed that there are no edges \(i \to i\) and the graph has exactly one edge among \(i \to j\) and \(j \to i\) for different \(i\) and \(j\).
|
If it is not possible to convert tournament to strongly connected with the given operations, output ""-1"".Otherwise, output two integers: the smallest number of operations that you need to make the given graph strongly connected and the number of ways to do this number of operations to make graph strongly connected, modulo \(998\,244\,353\).
|
Input: 3 010 001 100 | Output: 0 1
|
Master
| 4 | 734 | 491 | 344 | 12 |
|
1,168 |
C
|
1168C
|
C. And Reachability
| 2,200 |
bitmasks; dp
|
Toad Pimple has an array of integers \(a_1, a_2, \ldots, a_n\).We say that \(y\) is reachable from \(x\) if \(x<y\) and there exists an integer array \(p\) such that \(x = p_1 < p_2 < \ldots < p_k=y\), and \(a_{p_i}\, \&\, a_{p_{i+1}} > 0\) for all integers \(i\) such that \(1 \leq i < k\).Here \(\&\) denotes the bitwise AND operation.You are given \(q\) pairs of indices, check reachability for each of them.
|
The first line contains two integers \(n\) and \(q\) (\(2 \leq n \leq 300\,000\), \(1 \leq q \leq 300\,000\)) β the number of integers in the array and the number of queries you need to answer.The second line contains \(n\) space-separated integers \(a_1, a_2, \ldots, a_n\) (\(0 \leq a_i \leq 300\,000\)) β the given array.The next \(q\) lines contain two integers each. The \(i\)-th of them contains two space-separated integers \(x_i\) and \(y_i\) (\(1 \leq x_i < y_i \leq n\)). You need to check if \(y_i\) is reachable from \(x_i\).
|
Output \(q\) lines. In the \(i\)-th of them print ""Shi"" if \(y_i\) is reachable from \(x_i\), otherwise, print ""Fou"".
|
In the first example, \(a_3 = 0\). You can't reach it, because AND with it is always zero. \(a_2\, \&\, a_4 > 0\), so \(4\) is reachable from \(2\), and to go from \(1\) to \(4\) you can use \(p = [1, 2, 4]\).
|
Input: 5 3 1 3 0 2 1 1 3 2 4 1 4 | Output: Fou Shi Shi
|
Hard
| 2 | 411 | 537 | 121 | 11 |
1,047 |
B
|
1047B
|
B. Cover Points
| 900 |
geometry; math
|
There are \(n\) points on the plane, \((x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)\).You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
|
First line contains one integer \(n\) (\(1 \leq n \leq 10^5\)).Each of the next \(n\) lines contains two integers \(x_i\) and \(y_i\) (\(1 \leq x_i,y_i \leq 10^9\)).
|
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
|
Illustration for the first example: Illustration for the second example:
|
Input: 31 11 22 1 | Output: 3
|
Beginner
| 2 | 328 | 165 | 107 | 10 |
1,420 |
B
|
1420B
|
B. Rock and Lever
| 1,200 |
bitmasks; math
|
""You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you."" Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer \(n\), and an array \(a\) of positive integers. The task is to calculate the number of such pairs \((i,j)\) that \(i<j\) and \(a_i\) \(\&\) \(a_j \ge a_i \oplus a_j\), where \(\&\) denotes the bitwise AND operation, and \(\oplus\) denotes the bitwise XOR operation.Danik has solved this task. But can you solve it?
|
Each test contains multiple test cases.The first line contains one positive integer \(t\) (\(1 \le t \le 10\)) denoting the number of test cases. Description of the test cases follows.The first line of each test case contains one positive integer \(n\) (\(1 \le n \le 10^5\)) β length of the array.The second line contains \(n\) positive integers \(a_i\) (\(1 \le a_i \le 10^9\)) β elements of the array.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
|
For every test case print one non-negative integer β the answer to the problem.
|
In the first test case there is only one pair: \((4,7)\): for it \(4\) \(\&\) \(7 = 4\), and \(4 \oplus 7 = 3\).In the second test case all pairs are good.In the third test case there are two pairs: \((6,5)\) and \((2,3)\).In the fourth test case there are no good pairs.
|
Input: 5 5 1 4 3 7 10 3 1 1 1 4 6 2 5 3 2 2 4 1 1 | Output: 1 3 2 0 0
|
Easy
| 2 | 705 | 488 | 79 | 14 |
1,201 |
D
|
1201D
|
D. Treasure Hunting
| 2,100 |
binary search; dp; greedy; implementation
|
You are on the island which can be represented as a \(n \times m\) table. The rows are numbered from \(1\) to \(n\) and the columns are numbered from \(1\) to \(m\). There are \(k\) treasures on the island, the \(i\)-th of them is located at the position \((r_i, c_i)\).Initially you stand at the lower left corner of the island, at the position \((1, 1)\). If at any moment you are at the cell with a treasure, you can pick it up without any extra time. In one move you can move up (from \((r, c)\) to \((r+1, c)\)), left (from \((r, c)\) to \((r, c-1)\)), or right (from position \((r, c)\) to \((r, c+1)\)). Because of the traps, you can't move down.However, moving up is also risky. You can move up only if you are in a safe column. There are \(q\) safe columns: \(b_1, b_2, \ldots, b_q\). You want to collect all the treasures as fast as possible. Count the minimum number of moves required to collect all the treasures.
|
The first line contains integers \(n\), \(m\), \(k\) and \(q\) (\(2 \le n, \, m, \, k, \, q \le 2 \cdot 10^5\), \(q \le m\)) β the number of rows, the number of columns, the number of treasures in the island and the number of safe columns.Each of the next \(k\) lines contains two integers \(r_i, c_i\), (\(1 \le r_i \le n\), \(1 \le c_i \le m\)) β the coordinates of the cell with a treasure. All treasures are located in distinct cells.The last line contains \(q\) distinct integers \(b_1, b_2, \ldots, b_q\) (\(1 \le b_i \le m\)) β the indices of safe columns.
|
Print the minimum number of moves required to collect all the treasures.
|
In the first example you should use the second column to go up, collecting in each row treasures from the first column. In the second example, it is optimal to use the first column to go up. In the third example, it is optimal to collect the treasure at cell \((1;6)\), go up to row \(2\) at column \(6\), then collect the treasure at cell \((2;2)\), go up to the top row at column \(1\) and collect the last treasure at cell \((3;4)\). That's a total of \(15\) moves.
|
Input: 3 3 3 2 1 1 2 1 3 1 2 3 | Output: 6
|
Hard
| 4 | 925 | 563 | 72 | 12 |
2,108 |
A
|
2108A
|
A. Permutation Warm-Up
| 800 |
combinatorics; greedy; math
|
For a permutation \(p\) of length \(n\)\(^{\text{β}}\), we define the function:$$$\( f(p) = \sum_{i=1}^{n} \lvert p_i - i \rvert \)\(You are given a number \)n\(. You need to compute how many distinct values the function \)f(p)\( can take when considering all possible permutations of the numbers from \)1\( to \)n\(.\)^{\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 100\)). The description of the test cases follows. The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 500\)) β the number of numbers in the permutations.
|
For each test case, output a single integer β the number of distinct values of the function \(f(p)\) for the given length of permutations.
|
Consider the first two examples of the input.For \(n = 2\), there are only \(2\) permutations β \([1, 2]\) and \([2, 1]\). \(f([1, 2]) = \lvert 1 - 1 \rvert + \lvert 2 - 2 \rvert = 0\), \(f([2, 1]) = \lvert 2 - 1 \rvert + \lvert 1 - 2 \rvert = 1 + 1 = 2\). Thus, the function takes \(2\) distinct values.For \(n=3\), there are already \(6\) permutations: \([1, 2, 3]\), \([1, 3, 2]\), \([2, 1, 3]\), \([2, 3, 1]\), \([3, 1, 2]\), \([3, 2, 1]\), the function values of which will be \(0, 2, 2, 4, 4\), and \(4\) respectively, meaning there are a total of \(3\) values.
|
Input: 52381543 | Output: 2 3 17 57 463
|
Beginner
| 3 | 657 | 288 | 138 | 21 |
1,360 |
G
|
1360G
|
G. A/B Matrix
| 1,900 |
constructive algorithms; greedy; math
|
You are given four positive integers \(n\), \(m\), \(a\), \(b\) (\(1 \le b \le n \le 50\); \(1 \le a \le m \le 50\)). Find any such rectangular matrix of size \(n \times m\) that satisfies all of the following conditions: each row of the matrix contains exactly \(a\) ones; each column of the matrix contains exactly \(b\) ones; all other elements are zeros. If the desired matrix does not exist, indicate this.For example, for \(n=3\), \(m=6\), \(a=2\), \(b=1\), there exists a matrix satisfying the conditions above:$$$\( \begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 1 & 0 \end{vmatrix} \)$$$
|
The first line contains an integer \(t\) (\(1 \le t \le 1000\)) β the number of test cases. Then \(t\) test cases follow.Each test case is described by four positive integers \(n\), \(m\), \(a\), \(b\) (\(1 \le b \le n \le 50\); \(1 \le a \le m \le 50\)), where \(n\) and \(m\) are the sizes of the matrix, and \(a\) and \(b\) are the number of ones for rows and columns, respectively.
|
For each test case print: ""YES"" (without quotes) and the required matrix (if there are several answers, print any) if it exists, or ""NO"" (without quotes) if it does not exist. To print the matrix \(n \times m\), print \(n\) rows, each of which consists of \(m\) numbers \(0\) or \(1\) describing a row of the matrix. Numbers must be printed without spaces.
|
Input: 5 3 6 2 1 2 2 2 1 2 2 2 2 4 4 2 2 2 1 1 2 | Output: YES 010001 100100 001010 NO YES 11 11 YES 1100 1100 0011 0011 YES 1 1
|
Hard
| 3 | 631 | 385 | 360 | 13 |
|
220 |
E
|
220E
|
E. Little Elephant and Inversions
| 2,400 |
data structures; two pointers
|
The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 β€ l < r β€ n and sequence b = a1a2... alarar + 1... an has no more than k inversions. An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 β€ i < j β€ |b| and bi > bj, where |b| is the length of sequence b, and bj is its j-th element.Help the Little Elephant and count the number of the described pairs.
|
The first line contains two integers n and k (2 β€ n β€ 105, 0 β€ k β€ 1018) β the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 β€ ai β€ 109) β elements of array a.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.
|
In a single line print a single number β the answer to the problem.
|
Input: 3 11 3 2 | Output: 3
|
Expert
| 2 | 686 | 422 | 67 | 2 |
|
479 |
C
|
479C
|
C. Exams
| 1,400 |
greedy; sortings
|
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.According to the schedule, a student can take the exam for the i-th subject on the day number ai. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day bi (bi < ai). Thus, Valera can take an exam for the i-th subject either on day ai, or on day bi. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number ai.Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.
|
The first line contains a single positive integer n (1 β€ n β€ 5000) β the number of exams Valera will take.Each of the next n lines contains two positive space-separated integers ai and bi (1 β€ bi < ai β€ 109) β the date of the exam in the schedule and the early date of passing the i-th exam, correspondingly.
|
Print a single integer β the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date.
|
In the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5.In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject.
|
Input: 35 23 14 2 | Output: 2
|
Easy
| 2 | 1,134 | 308 | 207 | 4 |
1,188 |
D
|
1188D
|
D. Make Equal
| 3,100 |
dp
|
You are given \(n\) numbers \(a_1, a_2, \dots, a_n\). In one operation we can add to any one of those numbers a nonnegative integer power of \(2\).What is the smallest number of operations we need to perform to make all \(n\) numbers equal? It can be proved that under given constraints it doesn't exceed \(10^{18}\).
|
The first line contains a single integer \(n\) (\(1 \le n \le 10^5\)).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le 10^{17}\)).
|
Output exactly one integer β the smallest number of operations we need to perform to make all \(n\) numbers equal.
|
In the first example, all numbers are already equal. So the needed number of operation is \(0\).In the second example, we can apply the operation \(3\) times: add \(8\) to first \(2\), add \(8\) to second \(2\), add \(2\) to \(8\), making all numbers equal to \(10\). It can be proved that we can't make all numbers equal in less than \(3\) operations.
|
Input: 4 228 228 228 228 | Output: 0
|
Master
| 1 | 317 | 164 | 114 | 11 |
85 |
A
|
85A
|
A. Domino
| 1,300 |
constructive algorithms; implementation
|
We all know the problem about the number of ways one can tile a 2 Γ n field by 1 Γ 2 dominoes. You probably remember that it goes down to Fibonacci numbers. We will talk about some other problem below, there you also are going to deal with tiling a rectangular field with dominoes.You are given a 4 Γ n rectangular field, that is the field that contains four lines and n columns. You have to find for it any tiling by 1 Γ 2 dominoes such that each of the n - 1 potential vertical cuts along the grid lines intersects at least one domino, splitting it in two. No two dominoes in the sought tiling should overlap, each square of the field should be covered by exactly one domino. It is allowed to rotate the dominoes, that is, you can use 2 Γ 1 as well as 1 Γ 2 dominoes.Write a program that finds an arbitrary sought tiling.
|
The input contains one positive integer n (1 β€ n β€ 100) β the number of the field's columns.
|
If there's no solution, print ""-1"" (without the quotes). Otherwise, print four lines containing n characters each β that's the description of tiling, where each vertical cut intersects at least one domino. You should print the tiling, having painted the field in no more than 26 colors. Each domino should be painted a color. Different dominoes can be painted the same color, but dominoes of the same color should not be side-neighbouring. To indicate colors you should use lowercase Latin letters. Print any of the acceptable ways of tiling.
|
Input: 4 | Output: yyzzbccdbxxdyyaa
|
Easy
| 2 | 823 | 92 | 544 | 0 |
|
1,280 |
E
|
1280E
|
E. Kirchhoff's Current Loss
| 2,900 |
math
|
Your friend Kirchhoff is shocked with the current state of electronics design.""Ohmygosh! Watt is wrong with the field? All these circuits are inefficient! There's so much capacity for improvement. The electrical engineers must not conduct their classes very well. It's absolutely revolting"" he said.The negativity just keeps flowing out of him, but even after complaining so many times he still hasn't lepton the chance to directly change anything.""These circuits have too much total resistance. Wire they designed this way? It's just causing a massive loss of resistors! Their entire field could conserve so much money if they just maximized the potential of their designs. Why can't they just try alternative ideas?""The frequency of his protests about the electrical engineering department hertz your soul, so you have decided to take charge and help them yourself. You plan to create a program that will optimize the circuits while keeping the same circuit layout and maintaining the same effective resistance.A circuit has two endpoints, and is associated with a certain constant, \(R\), called its effective resistance. The circuits we'll consider will be formed from individual resistors joined together in series or in parallel, forming more complex circuits. The following image illustrates combining circuits in series or parallel. According to your friend Kirchhoff, the effective resistance can be calculated quite easily when joining circuits this way: When joining \(k\) circuits in series with effective resistances \(R_1, R_2, \ldots, R_k\), the effective resistance \(R\) of the resulting circuit is the sum $$$\(R = R_1 + R_2 + \ldots + R_k.\)\( When joining \)k\( circuits in parallel with effective resistances \)R_1, R_2, \ldots, R_k\(, the effective resistance \)R\( of the resulting circuit is found by solving for \)R\( in \)\(\frac{1}{R} = \frac{1}{R_1} + \frac{1}{R_2} + \ldots + \frac{1}{R_k},\)\( assuming all \)R_i > 0\(; if at least one \)R_i = 0\(, then the effective resistance of the whole circuit is simply \)R = 0\(. Circuits will be represented by strings. Individual resistors are represented by an asterisk, ""*"". For more complex circuits, suppose \)s_1, s_2, \ldots, s_k\( represent \)k \ge 2\( circuits. Then: ""(\)s_1\( S \)s_2\( S \)\ldots\( S \)s_k\()"" represents their series circuit; ""(\)s_1\( P \)s_2\( P \)\ldots\( P \)s_k\()"" represents their parallel circuit. For example, ""(* P (* S *) P *)"" represents the following circuit: Given a circuit, your task is to assign the resistances of the individual resistors such that they satisfy the following requirements: Each individual resistor has a nonnegative integer resistance value; The effective resistance of the whole circuit is \)r\(; The sum of the resistances of the individual resistors is minimized. If there are \)n\( individual resistors, then you need to output the list \)r_1, r_2, \ldots, r_n\( (\)0 \le r_i\(, and \)r_i\( is an integer), where \)r_i\( is the resistance assigned to the \)i\(-th individual resistor that appears in the input (from left to right). If it is impossible to accomplish the task, you must say so as well.If it is possible, then it is guaranteed that the minimum sum of resistances is at most \)10^{18}$$$.
|
The first line of input contains a single integer \(t\) (\(1 \le t \le 32000\)), denoting the number of test cases. The next lines contain descriptions of the test cases.Each test case consists of a single line containing the integer \(r\) (\(1 \le r \le 10^6\)), space, and then the string representing the circuit. It is guaranteed that the string is valid and follows the description above. The number of individual resistors (symbols ""*"") is at least \(1\) and at most \(80000\).It is guaranteed that the total number of individual resistors across all test cases is at most \(320000\).
|
For each test case, print a single line: If it's possible to achieve an effective resistance of \(r\), print ""REVOLTING"" (without quotes) and then \(n\) integers \(r_1, r_2, \ldots, r_n\) β the resistances assigned to the individual resistors. Here, \(n\) denotes the number of the individual resistors in the circuit. There may be multiple possible such assignments with a minimal sum of resistances of the individual resistors, you can output any of them; If it's impossible, print the string: ""LOSS"" (without quotes).
|
The following illustrates the third sample case: Here, the sum of the resistances of the individual resistors is \(2 + 1 + 1 = 4\), which can be shown to be the minimum. Note that there may be other assignments that achieve this minimum.
|
Input: 3 5 * 1 (* S *) 1 (* P (* S *)) | Output: REVOLTING 5 REVOLTING 1 0 REVOLTING 2 1 1
|
Master
| 1 | 3,253 | 592 | 524 | 12 |
1,028 |
D
|
1028D
|
D. Order book
| 2,100 |
combinatorics; data structures; greedy
|
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.At every moment of time, every SELL offer has higher price than every BUY offer. In this problem no two ever existed orders will have the same price.The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below. The presented order book says that someone wants to sell the product at price \(12\) and it's the best SELL offer because the other two have higher prices. The best BUY offer has price \(10\). There are two possible actions in this orderbook: Somebody adds a new order of some direction with some price. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer ""SELL \(20\)"" if there is already an offer ""BUY \(20\)"" or ""BUY \(25\)"" β in this case you just accept the best BUY offer.You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types: ""ADD \(p\)"" denotes adding a new order with price \(p\) and unknown direction. The order must not contradict with orders still not removed from the order book. ""ACCEPT \(p\)"" denotes accepting an existing best offer with price \(p\) and unknown direction.The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo \(10^9 + 7\). If it is impossible to correctly restore directions, then output \(0\).
|
The first line contains an integer \(n\) (\(1 \le n \le 363\,304\)) β the number of actions in the log.Each of the next \(n\) lines contains a string ""ACCEPT"" or ""ADD"" and an integer \(p\) (\(1 \le p \le 308\,983\,066\)), describing an action type and price. All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.
|
Output the number of ways to restore directions of ADD actions modulo \(10^9 + 7\).
|
In the first example each of orders may be BUY or SELL.In the second example the order with price \(1\) has to be BUY order, the order with the price \(3\) has to be SELL order.
|
Input: 6ADD 1ACCEPT 1ADD 2ACCEPT 2ADD 3ACCEPT 3 | Output: 8
|
Hard
| 3 | 2,276 | 425 | 83 | 10 |
643 |
E
|
643E
|
E. Bear and Destroying Subtrees
| 2,700 |
dp; math; probabilities; trees
|
Limak is a little grizzly bear. He will once attack Deerland but now he can only destroy trees in role-playing games. Limak starts with a tree with one vertex. The only vertex has index 1 and is a root of the tree.Sometimes, a game chooses a subtree and allows Limak to attack it. When a subtree is attacked then each of its edges is destroyed with probability , independently of other edges. Then, Limak gets the penalty β an integer equal to the height of the subtree after the attack. The height is defined as the maximum number of edges on the path between the root of the subtree and any vertex in the subtree.You must handle queries of two types. 1 v denotes a query of the first type. A new vertex appears and its parent is v. A new vertex has the next available index (so, new vertices will be numbered 2, 3, ...). 2 v denotes a query of the second type. For a moment let's assume that the game allows Limak to attack a subtree rooted in v. Then, what would be the expected value of the penalty Limak gets after the attack? In a query of the second type, Limak doesn't actually attack the subtree and thus the query doesn't affect next queries.
|
The first line of the input contains one integer q (1 β€ q β€ 500 000) β the number of queries.Then, q lines follow. The i-th of them contains two integers typei and vi (1 β€ typei β€ 2). If typei = 1 then vi denotes a parent of a new vertex, while if typei = 2 then you should print the answer for a subtree rooted in vi.It's guaranteed that there will be at least 1 query of the second type, that is, the output won't be empty.It's guaranteed that just before the i-th query a vertex vi already exists.
|
For each query of the second type print one real number βthe expected value of the penalty if Limak attacks the given subtree. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if .
|
Below, you can see the drawing for the first sample. Red circles denote queries of the second type.
|
Input: 71 11 12 11 21 32 22 1 | Output: 0.75000000000.50000000001.1875000000
|
Master
| 4 | 1,152 | 500 | 358 | 6 |
958 |
B1
|
958B1
|
B1. Maximum Control (easy)
| 1,000 |
implementation
|
The Resistance is trying to take control over all planets in a particular solar system. This solar system is shaped like a tree. More precisely, some planets are connected by bidirectional hyperspace tunnels in such a way that there is a path between every pair of the planets, but removing any tunnel would disconnect some of them.The Resistance already has measures in place that will, when the time is right, enable them to control every planet that is not remote. A planet is considered to be remote if it is connected to the rest of the planets only via a single hyperspace tunnel.How much work is there left to be done: that is, how many remote planets are there?
|
The first line of the input contains an integer N (2 β€ N β€ 1000) β the number of planets in the galaxy.The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 β€ u, v β€ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.
|
A single integer denoting the number of remote planets.
|
In the first example, only planets 2, 3 and 5 are connected by a single tunnel.In the second example, the remote planets are 2 and 3.Note that this problem has only two versions β easy and medium.
|
Input: 54 14 21 31 5 | Output: 3
|
Beginner
| 1 | 669 | 484 | 55 | 9 |
1,868 |
B2
|
1868B2
|
B2. Candy Party (Hard Version)
| 2,100 |
bitmasks; constructive algorithms; dp; greedy; implementation; math
|
This is the hard version of the problem. The only difference is that in this version everyone must give candies to no more than one person and receive candies from no more than one person. Note that a submission cannot pass both versions of the problem at the same time. You can make hacks only if both versions of the problem are solved.After Zhongkao examination, Daniel and his friends are going to have a party. Everyone will come with some candies.There will be \(n\) people at the party. Initially, the \(i\)-th person has \(a_i\) candies. During the party, they will swap their candies. To do this, they will line up in an arbitrary order and everyone will do the following no more than once: Choose an integer \(p\) (\(1 \le p \le n\)) and a non-negative integer \(x\), then give his \(2^{x}\) candies to the \(p\)-th person. Note that one cannot give more candies than currently he has (he might receive candies from someone else before) and he cannot give candies to himself. Daniel likes fairness, so he will be happy if and only if everyone receives candies from no more than one person. Meanwhile, his friend Tom likes average, so he will be happy if and only if all the people have the same number of candies after all swaps.Determine whether there exists a way to swap candies, so that both Daniel and Tom will be happy after the swaps.
|
The first line of input contains a single integer \(t\) (\(1\le t\le 1000\)) β the number of test cases. The description of test cases follows.The first line of each test case contains a single integer \(n\) (\(2\le n\le 2\cdot 10^5\)) β the number of people at the party.The second line of each test case contains \(n\) integers \(a_1,a_2,\ldots,a_n\) (\(1\le a_i\le 10^9\)) β the number of candies each person has.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot 10^5\).
|
For each test case, print ""Yes"" (without quotes) if exists a way to swap candies to make both Daniel and Tom happy, and print ""No"" (without quotes) otherwise.You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
|
In the first test case, the second person gives \(1\) candy to the first person, then all people have \(3\) candies. In the second test case, the fourth person gives \(1\) candy to the second person, the fifth person gives \(2\) candies to the first person, the third person does nothing. And after the swaps everyone has \(3\) candies.In the third test case, it's impossible for all people to have the same number of candies.In the fourth test case, the two people do not need to do anything.
|
Input: 632 4 351 2 3 4 561 4 7 1 5 4220092043 20092043129 9 8 2 4 4 3 5 1 1 1 162 12 7 16 11 12 | Output: Yes Yes No Yes No Yes
|
Hard
| 6 | 1,351 | 507 | 323 | 18 |
1,110 |
G
|
1110G
|
G. Tree-Tac-Toe
| 3,100 |
constructive algorithms; games; trees
|
The tic-tac-toe game is starting on a tree of \(n\) vertices. Some vertices are already colored in white while the remaining are uncolored.There are two players β white and black. The players make moves alternatively. The white player starts the game. In his turn, a player must select one uncolored vertex and paint it in his color.The player wins if he paints some path of three vertices in his color. In case all vertices are colored and neither player won, the game ends in a draw.Could you please find who will win the game or whether it ends as a draw, assuming both players play optimally?
|
The first line contains a single integer \(T\) (\(1 \le T \le 50\,000\)) β the number of test cases. Then descriptions of \(T\) test cases follow.The first line of each test contains a single integer \(n\) (\(1 \le n \le 5 \cdot 10^5\)) β the number of vertices in the tree.Each of the following \(n - 1\) lines contains integers \(v\), \(u\) (\(1 \le v, u \le n\)) denoting an edge of the tree connecting vertices \(v\) and \(u\).The last line of a test case contains a string of letters 'W' (for white) and 'N' (for not colored) of length \(n\) denoting already colored vertices. Vertexes already colored in white are denoted as 'W'.It's guaranteed that the given edges form a tree, that there is at least one uncolored vertex and that there is no path of three white vertices.It's guaranteed that sum of all \(n\) among all test cases is at most \(5 \cdot 10^5\).
|
For every test case, print either ""White"", ""Draw"" or ""Black"", depending on the result of the game.
|
In the first example, vertex \(4\) is already colored in white. The white player can win by coloring the vertex \(1\) in white first and the remaining vertex on his second turn. The process is illustrated with the pictures below. In the second example, we can show that no player can enforce their victory.
|
Input: 2 4 1 2 1 3 1 4 NNNW 5 1 2 2 3 3 4 4 5 NNNNN | Output: White Draw
|
Master
| 3 | 596 | 866 | 104 | 11 |
1,985 |
C
|
1985C
|
C. Good Prefixes
| 1,000 |
greedy
|
Alex thinks some array is good if there exists some element that can be represented as the sum of all other elements (the sum of all other elements is \(0\) if there are no other elements). For example, the array \([1,6,3,2]\) is good since \(1+3+2=6\). Furthermore, the array \([0]\) is also good. However, the arrays \([1,2,3,4]\) and \([1]\) are not good.Alex has an array \(a_1,a_2,\ldots,a_n\). Help him count the number of good non-empty prefixes of the array \(a\). In other words, count the number of integers \(i\) (\(1 \le i \le n\)) such that the length \(i\) prefix (i.e. \(a_1,a_2,\ldots,a_i\)) is good.
|
The first line of the input contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) β the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β the number of elements in the array.The second line of each test case contains \(n\) integers \(a_1,a_2,\ldots,a_n\) (\(0 \le a_i \le 10^9\)) β the elements of the array.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, output a single integer β the number of good non-empty prefixes of the array \(a\).
|
In the fourth test case, the array has five prefixes: prefix \([0]\) is a good array, as mentioned in the statement; prefix \([0, 1]\) is not a good array, since \(0 \ne 1\); prefix \([0, 1, 2]\) is not a good array, since \(0 \ne 1 + 2\), \(1 \ne 0 + 2\) and \(2 \ne 0 + 1\); prefix \([0, 1, 2, 1]\) is a good array, since \(2 = 0 + 1 + 1\); prefix \([0, 1, 2, 1, 4]\) is a good array, since \(4 = 0 + 1 + 2 + 1\). As you can see, three of them are good, so the answer is \(3\).
|
Input: 7101141 1 2 050 1 2 1 471 1 0 3 5 2 1271000000000 1000000000 1000000000 1000000000 1000000000 1000000000 294967296100 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 589934592 | Output: 1 0 3 3 4 1 2
|
Beginner
| 1 | 616 | 472 | 103 | 19 |
487 |
D
|
487D
|
D. Conveyor Belts
| 2,700 |
data structures
|
Automatic Bakery of Cyberland (ABC) recently bought an n Γ m rectangle table. To serve the diners, ABC placed seats around the table. The size of each seat is equal to a unit square, so there are 2(n + m) seats in total.ABC placed conveyor belts on each unit square on the table. There are three types of conveyor belts: ""^"", ""<"" and "">"". A ""^"" belt can bring things upwards. ""<"" can bring leftwards and "">"" can bring rightwards.Let's number the rows with 1 to n from top to bottom, the columns with 1 to m from left to right. We consider the seats above and below the top of the table are rows 0 and n + 1 respectively. Also we define seats to the left of the table and to the right of the table to be column 0 and m + 1. Due to the conveyor belts direction restriction there are currently no way for a diner sitting in the row n + 1 to be served.Given the initial table, there will be q events in order. There are two types of events: ""A x y"" means, a piece of bread will appear at row x and column y (we will denote such position as (x, y)). The bread will follow the conveyor belt, until arriving at a seat of a diner. It is possible that the bread gets stuck in an infinite loop. Your task is to simulate the process, and output the final position of the bread, or determine that there will be an infinite loop. ""C x y c"" means that the type of the conveyor belt at (x, y) is changed to c. Queries are performed separately meaning that even if the bread got stuck in an infinite loop, it won't affect further queries.
|
The first line of input contains three integers n, m and q (1 β€ n β€ 105, 1 β€ m β€ 10, 1 β€ q β€ 105), separated by a space.Next n lines, each line contains m characters, describing the table. The characters can only be one of ""<^>"".Next q lines, each line describes an event. The format is ""C x y c"" or ""A x y"" (Consecutive elements are separated by a space). It's guaranteed that 1 β€ x β€ n, 1 β€ y β€ m. c is a character from the set ""<^>"".There are at most 10000 queries of ""C"" type.
|
For each event of type ""A"", output two integers tx, ty in a line, separated by a space, denoting the destination of (x, y) is (tx, ty).If there is an infinite loop, you should output tx = ty = - 1.
|
For the first sample:If the bread goes from (2, 1), it will go out of the table at (1, 3).After changing the conveyor belt of (1, 2) to ""<"", when the bread goes from (2, 1) again, it will get stuck at ""><"", so output is ( - 1, - 1).
|
Input: 2 2 3>>^^A 2 1C 1 2 <A 2 1 | Output: 1 3-1 -1
|
Master
| 1 | 1,538 | 490 | 199 | 4 |
2,028 |
C
|
2028C
|
C. Alice's Adventures in Cutting Cake
| 1,600 |
binary search; dp; greedy; two pointers
|
Alice is at the Mad Hatter's tea party! There is a long sheet cake made up of \(n\) sections with tastiness values \(a_1, a_2, \ldots, a_n\). There are \(m\) creatures at the tea party, excluding Alice. Alice will cut the cake into \(m + 1\) pieces. Formally, she will partition the cake into \(m + 1\) subarrays, where each subarray consists of some number of adjacent sections. The tastiness of a piece is the sum of tastiness of its sections. Afterwards, she will divvy these \(m + 1\) pieces up among the \(m\) creatures and herself (her piece can be empty). However, each of the \(m\) creatures will only be happy when the tastiness of its piece is \(v\) or more.Alice wants to make sure every creature is happy. Limited by this condition, she also wants to maximize the tastiness of her own piece. Can you help Alice find the maximum tastiness her piece can have? If there is no way to make sure every creature is happy, output \(-1\).
|
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 three integers \(n, m, v\) (\(1\le m\le n\le 2\cdot 10^5\); \(1\le v\le 10^9\)) β the number of sections, the number of creatures, and the creatures' minimum requirement for tastiness, respectively.The next line contains \(n\) space separated integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^9\)) β the tastinesses of the sections.The sum of \(n\) over all test cases does not exceed \(2\cdot 10^5\).
|
For each test case, output the maximum tastiness Alice can achieve for her piece, or \(-1\) if there is no way to make sure every creature is happy.
|
For the first test case, Alice can give the first and second section as their own pieces, and then take the remaining \(10 + 1 + 1 + 10 = 22\) tastiness for herself. We can show that she cannot do any better.For the second test case, Alice could give the first and second section as one piece, and the sixth section as one piece. She can then take the remaining \(10 + 1 + 1 = 12\) tastiness for herself. We can show that she cannot do any better.For the seventh test case, Alice cannot give each creature a piece of at least \(12\) tastiness.
|
Input: 76 2 11 1 10 1 1 106 2 21 1 10 1 1 106 2 31 1 10 1 1 106 2 101 1 10 1 1 106 2 111 1 10 1 1 106 2 121 1 10 1 1 106 2 121 1 1 1 10 10 | Output: 22 12 2 2 2 0 -1
|
Medium
| 4 | 941 | 609 | 148 | 20 |
316 |
G1
|
316G1
|
G1. Good Substrings
| 1,700 |
hashing; strings
|
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l β€ r) are integers. Weβll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string ""ab"", complies with rules (""ab"", 1, 2) and (""aab"", 0, 1), but does not comply with rules (""cd"", 1, 2) and (""abab"", 0, 1).A substring s[l... r] (1 β€ l β€ r β€ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 β€ l β€ r β€ |p|) such that p[l... r] = t.Weβll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] β s[z... w].
|
The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 β€ li β€ ri β€ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.The input limits for scoring 30 points are (subproblem G1): 0 β€ n β€ 10. The length of string s and the maximum length of string p is β€ 200. The input limits for scoring 70 points are (subproblems G1+G2): 0 β€ n β€ 10. The length of string s and the maximum length of string p is β€ 2000. The input limits for scoring 100 points are (subproblems G1+G2+G3): 0 β€ n β€ 10. The length of string s and the maximum length of string p is β€ 50000.
|
Print a single integer β the number of good substrings of string s.
|
There are three good substrings in the first sample test: Β«aabΒ», Β«abΒ» and Β«bΒ».In the second test only substrings Β«eΒ» and Β«tΒ» are good.
|
Input: aaab2aa 0 0aab 1 1 | Output: 3
|
Medium
| 2 | 1,167 | 767 | 67 | 3 |
2,011 |
A
|
2011A
|
A. Problem Solving
| 0 |
*special
|
Jane has decided to solve a list of \(n\) problems on Codeforces. The \(i\)-th problem in her list has difficulty \(d_i\), and the last problem in the list is the hardest one (for every problem \(j < n\), \(d_j < d_n\)).Jane's problem-solving skill is some integer \(x\) (unknown to you). If a problem's difficulty is greater than \(x\), then Jane cannot solve it, otherwise she can solve it.Jane has solved all problems form the list, except for the last one β she found out that it was too difficult for her. Can you uniquely determine the value of \(x\) β Jane's problem solving skill?
|
The first line contains one integer \(t\) (\(1 \le t \le 1000\)) β the number of test cases.Each test case consists of two lines: the first line contains one integer \(n\) (\(2 \le n \le 50\)) β the number of problems; the second line contains \(n\) integers \(d_1, d_2, \dots, d_n\) (\(1 \le d_i \le 50\)). Additional constraint on the input: in every test case, the last problem is more difficult than every other problem (i. e. \(d_n > d_j\) for every \(j < n\)). This means that at least one possible value of \(x\) exists.
|
For each test case, print one line: if you can determine the value of \(x\) uniquely, print \(x\); otherwise, print Ambiguous. The checking program is case-sensitive, so if you print ambiguous or AMBIGUOUS, your answer will be considered wrong.
|
In the second test case of the example, the value of \(x\) could be \(11\), but it also could be \(10\) (other possible values for \(x\) also exist).
|
Input: 351 2 3 4 588 8 5 3 4 6 8 1243 3 3 4 | Output: 4 Ambiguous 3
|
Beginner
| 1 | 588 | 527 | 244 | 20 |
716 |
B
|
716B
|
B. Complete the Word
| 1,300 |
greedy; two pointers
|
ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a substring (contiguous segment of letters) of it of length 26 where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than 26, no such substring exists and thus it is not nice.Now, ZS the Coder tells you a word, where some of its letters are missing as he forgot them. He wants to determine if it is possible to fill in the missing letters so that the resulting word is nice. If it is possible, he needs you to find an example of such a word as well. Can you help him?
|
The first and only line of the input contains a single string s (1 β€ |s| β€ 50 000), the word that ZS the Coder remembers. Each character of the string is the uppercase letter of English alphabet ('A'-'Z') or is a question mark ('?'), where the question marks denotes the letters that ZS the Coder can't remember.
|
If there is no way to replace all the question marks with uppercase letters such that the resulting word is nice, then print - 1 in the only line.Otherwise, print a string which denotes a possible nice word that ZS the Coder learned. This string should match the string from the input, except for the question marks replaced with uppercase English letters.If there are multiple solutions, you may print any of them.
|
In the first sample case, ABCDEFGHIJKLMNOPQRZTUVWXYS is a valid answer beacuse it contains a substring of length 26 (the whole string in this case) which contains all the letters of the English alphabet exactly once. Note that there are many possible solutions, such as ABCDEFGHIJKLMNOPQRSTUVWXYZ or ABCEDFGHIJKLMNOPQRZTUVWXYS.In the second sample case, there are no missing letters. In addition, the given string does not have a substring of length 26 that contains all the letters of the alphabet, so the answer is - 1.In the third sample case, any string of length 26 that contains all letters of the English alphabet fits as an answer.
|
Input: ABC??FGHIJK???OPQR?TUVWXY? | Output: ABCDEFGHIJKLMNOPQRZTUVWXYS
|
Easy
| 2 | 616 | 312 | 415 | 7 |
2,061 |
A
|
2061A
|
A. Kevin and Arithmetic
| 800 |
math
|
To train young Kevin's arithmetic skills, his mother devised the following problem.Given \(n\) integers \(a_1, a_2, \ldots, a_n\) and a sum \(s\) initialized to \(0\), Kevin performs the following operation for \(i = 1, 2, \ldots, n\) in order: Add \(a_i\) to \(s\). If the resulting \(s\) is even, Kevin earns a point and repeatedly divides \(s\) by \(2\) until it becomes odd. Note that Kevin can earn at most one point per operation, regardless of how many divisions he does.Since these divisions are considered more beneficial for Kevin's development, his mother wants to rearrange \(a\) so that the number of Kevin's total points is maximized. Determine the maximum number of points.
|
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\leq n \leq 100\)) β the number of integers.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1\leq a_i \leq 10^9\)).
|
For each test case, output one integer β the maximum number of points.
|
In the first test case, the only arrangement of \(a\) is \([1]\). \(s\) becomes \(1\). Kevin earns no points.In the second test case, the only possible arrangement of \(a\) is \([2, 1]\). \(s\) becomes \(1\) and \(1\) successively. Kevin earns points in both operations.In the third test case, one possible arrangement of \(a\) is \([2, 4, 6]\). \(s\) becomes \(1\), \(5\), and \(11\) successively. Kevin earns a point in the first operation.
|
Input: 51121 232 4 641000000000 999999999 999999998 999999997103 1 4 1 5 9 2 6 5 3 | Output: 0 2 1 3 8
|
Beginner
| 1 | 688 | 366 | 70 | 20 |
413 |
A
|
413A
|
A. Data Recovery
| 1,200 |
implementation
|
Not so long ago company R2 bought company R1 and consequently, all its developments in the field of multicore processors. Now the R2 laboratory is testing one of the R1 processors.The testing goes in n steps, at each step the processor gets some instructions, and then its temperature is measured. The head engineer in R2 is keeping a report record on the work of the processor: he writes down the minimum and the maximum measured temperature in his notebook. His assistant had to write down all temperatures into his notebook, but (for unknown reasons) he recorded only m.The next day, the engineer's assistant filed in a report with all the m temperatures. However, the chief engineer doubts that the assistant wrote down everything correctly (naturally, the chief engineer doesn't doubt his notes). So he asked you to help him. Given numbers n, m, min, max and the list of m temperatures determine whether you can upgrade the set of m temperatures to the set of n temperatures (that is add n - m temperatures), so that the minimum temperature was min and the maximum one was max.
|
The first line contains four integers n, m, min, max (1 β€ m < n β€ 100; 1 β€ min < max β€ 100). The second line contains m space-separated integers ti (1 β€ ti β€ 100) β the temperatures reported by the assistant.Note, that the reported temperatures, and the temperatures you want to add can contain equal temperatures.
|
If the data is consistent, print 'Correct' (without the quotes). Otherwise, print 'Incorrect' (without the quotes).
|
In the first test sample one of the possible initial configurations of temperatures is [1, 2].In the second test sample one of the possible initial configurations of temperatures is [2, 1, 3].In the third test sample it is impossible to add one temperature to obtain the minimum equal to 1 and the maximum equal to 3.
|
Input: 2 1 1 21 | Output: Correct
|
Easy
| 1 | 1,082 | 314 | 115 | 4 |
1,665 |
C
|
1665C
|
C. Tree Infection
| 1,600 |
binary search; greedy; sortings; trees
|
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex \(v\) (different from root) is the previous to \(v\) vertex on the shortest path from the root to the vertex \(v\). Children of the vertex \(v\) are all vertices for which \(v\) is the parent.You are given a rooted tree with \(n\) vertices. The vertex \(1\) is the root. Initially, all vertices are healthy.Each second you do two operations, the spreading operation and, after that, the injection operation: Spreading: for each vertex \(v\), if at least one child of \(v\) is infected, you can spread the disease by infecting at most one other child of \(v\) of your choice. Injection: you can choose any healthy vertex and infect it. This process repeats each second until the whole tree is infected. You need to find the minimal number of seconds needed to infect the whole tree.
|
The input consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) β the number of the vertices in the given tree.The second line of each test case contains \(n - 1\) integers \(p_2, p_3, \ldots, p_n\) (\(1 \le p_i \le n\)), where \(p_i\) is the ancestor of the \(i\)-th vertex in the tree.It is guaranteed that the given graph is a tree.It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(2 \cdot 10^5\).
|
For each test case you should output a single integer β the minimal number of seconds needed to infect the whole tree.
|
The image depicts the tree from the first test case during each second.A vertex is black if it is not infected. A vertex is blue if it is infected by injection during the previous second. A vertex is green if it is infected by spreading during the previous second. A vertex is red if it is infected earlier than the previous second. Note that you are able to choose which vertices are infected by spreading and by injections.
|
Input: 571 1 1 2 2 455 5 1 42133 161 1 1 1 1 | Output: 4 4 2 3 4
|
Medium
| 4 | 900 | 637 | 118 | 16 |
1,355 |
E
|
1355E
|
E. Restorer Distance
| 2,100 |
binary search; greedy; math; sortings; ternary search
|
You have to restore the wall. The wall consists of \(N\) pillars of bricks, the height of the \(i\)-th pillar is initially equal to \(h_{i}\), the height is measured in number of bricks. After the restoration all the \(N\) pillars should have equal heights.You are allowed the following operations: put a brick on top of one pillar, the cost of this operation is \(A\); remove a brick from the top of one non-empty pillar, the cost of this operation is \(R\); move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is \(M\).You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes \(0\).What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
|
The first line of input contains four integers \(N\), \(A\), \(R\), \(M\) (\(1 \le N \le 10^{5}\), \(0 \le A, R, M \le 10^{4}\)) β the number of pillars and the costs of operations.The second line contains \(N\) integers \(h_{i}\) (\(0 \le h_{i} \le 10^{9}\)) β initial heights of pillars.
|
Print one integer β the minimal cost of restoration.
|
Input: 3 1 100 100 1 3 8 | Output: 12
|
Hard
| 5 | 821 | 289 | 52 | 13 |
|
77 |
D
|
77D
|
D. Domino Carpet
| 2,300 |
dp; implementation
|
...Mike the TV greets you again! Tired of the monotonous furniture? Sick of gray routine? Dreaming about dizzying changes in your humble abode? We have something to offer you! This domino carpet for only $99.99 will change your life! You can lay it on the floor, hang it on the wall or even on the ceiling! Among other things ... Having watched the commercial, virus Hexadecimal also wanted to get a Domino Carpet and wanted badly to be photographed in front of it. But of course, a virus will never consent to buying a licensed Carpet! So she ordered a truck of dominoes and decided to make such a Carpet herself. The original Domino Carpet is a field of squares n Γ m in size. Each square is half of a domino, and can be rotated either vertically or horizontally, independently from its neighbors. Vertically rotated domino halves look like this: And horizontally rotated halves look like this: Notice, that some halves looks the same in both rotations, but other halves differ.Dominoes bought by Hexadecimal are represented by uncuttable chips 1 Γ 2 in size, which can be laid either vertically or horizontally. If the chip is laid vertically, then both of it's halves should be laid vertically orientated; if the chip is laid horizontally, then both of it's halves should be laid horizontally.The samples of valid and invalid dominoes laid vertically and horizontally are: Virus Hexadecimal assembles her own Domino Carpet so that the following conditions are satisfied: each carpet square is covered by a domino chip, i.e. there are no empty squares; all domino chips lie entirely within the carpet and don't overlap with each other; if there is a horizontal domino chip with its left half in column j then there are no horizontal domino chips with their left halves in columns j - 1 or j + 1. Before starting to assemble her own Domino Carpet, the virus wants to know the number of ways to achieve the intended purpose modulo 109 + 7.You can assume that the virus has an infinitely large number of dominoes of each type.
|
The first line contains two integers n and m, separated by a space β the size of the Domino Carpet (1 β€ n, m β€ 250). Next 4n + 1 lines contain 4m + 1 symbols. Each square of the Domino Carpet, which is a domino half, is described by a 3 Γ 3 square. Symbol 'O' in this square indicates the presence of a point, symbol '.' β its absence. Each 3 Γ 3 square is delineated from adjacent squares by symbols '#' as shown in the examples. It is guaranteed that every box describes the correct half of a domino. In all pretests the Domino Carpets have the size of 2 Γ 2 and 4 Γ 4.
|
Print a single number, the number of ways to assemble the Domino Carpet modulo 109 + 7, using only standard dominoes of size 1 Γ 2.
|
A note to the first example: all correct ways to make Domino Carpet are represented below: And this way is incorrect:
|
Input: 3 4##################O..#...#O.O#...##.O.#.O.#.O.#...##..O#...#O.O#...###################O.O#OOO#O.O#...##.O.#...#...#.O.##O.O#OOO#O.O#...###################O.O#...#O.O#...##...#...#...#.O.##O.O#...#O.O#...################## | Output: 3
|
Expert
| 2 | 2,026 | 571 | 131 | 0 |
919 |
E
|
919E
|
E. Congruence Equation
| 2,100 |
chinese remainder theorem; math; number theory
|
Given an integer \(x\). Your task is to find out how many positive integers \(n\) (\(1 \leq n \leq x\)) satisfy $$$\(n \cdot a^n \equiv b \quad (\textrm{mod}\;p),\)\( where \)a, b, p$$$ are all known constants.
|
The only line contains four integers \(a,b,p,x\) (\(2 \leq p \leq 10^6+3\), \(1 \leq a,b < p\), \(1 \leq x \leq 10^{12}\)). It is guaranteed that \(p\) is a prime.
|
Print a single integer: the number of possible answers \(n\).
|
In the first sample, we can see that \(n=2\) and \(n=8\) are possible answers.
|
Input: 2 3 5 8 | Output: 2
|
Hard
| 3 | 210 | 163 | 61 | 9 |
1,760 |
D
|
1760D
|
D. Challenging Valleys
| 1,000 |
implementation; two pointers
|
You are given an array \(a[0 \dots n-1]\) of \(n\) integers. This array is called a ""valley"" if there exists exactly one subarray \(a[l \dots r]\) such that: \(0 \le l \le r \le n-1\), \(a_l = a_{l+1} = a_{l+2} = \dots = a_r\), \(l = 0\) or \(a_{l-1} > a_{l}\), \(r = n-1\) or \(a_r < a_{r+1}\). Here are three examples: The first image shows the array [\(3, 2, 2, 1, 2, 2, 3\)], it is a valley because only subarray with indices \(l=r=3\) satisfies the condition.The second image shows the array [\(1, 1, 1, 2, 3, 3, 4, 5, 6, 6, 6\)], it is a valley because only subarray with indices \(l=0, r=2\) satisfies the codition.The third image shows the array [\(1, 2, 3, 4, 3, 2, 1\)], it is not a valley because two subarrays \(l=r=0\) and \(l=r=6\) that satisfy the condition.You are asked whether the given array is a valley or not.Note that we consider the array to be indexed from \(0\).
|
The first line contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) β the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \leq n \leq 2\cdot10^5\)) β the length of the array.The second line of each test case contains \(n\) integers \(a_i\) (\(1 \leq a_i \leq 10^9\)) β the elements of the array.It is guaranteed that the sum of \(n\) over all test cases is smaller than \(2\cdot10^5\).
|
For each test case, output ""YES"" (without quotes) if the array is a valley, and ""NO"" (without quotes) otherwise.You can output the answer in any case (for example, the strings ""yEs"", ""yes"", ""Yes"" and ""YES"" will be recognized as a positive answer).
|
The first three test cases are explained in the statement.
|
Input: 673 2 2 1 2 2 3111 1 1 2 3 3 4 5 6 6 671 2 3 4 3 2 179 7 4 6 9 9 101100000000089 4 4 5 9 4 9 10 | Output: YES YES NO YES YES NO
|
Beginner
| 2 | 889 | 432 | 259 | 17 |
1,680 |
C
|
1680C
|
C. Binary String
| 1,600 |
binary search; greedy; strings; two pointers
|
You are given a string \(s\) consisting of characters 0 and/or 1.You have to remove several (possibly zero) characters from the beginning of the string, and then several (possibly zero) characters from the end of the string. The string may become empty after the removals. The cost of the removal is the maximum of the following two values: the number of characters 0 left in the string; the number of characters 1 removed from the string. What is the minimum cost of removal you can achieve?
|
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)) β the number of test cases.Each test case consists of one line containing the string \(s\) (\(1 \le |s| \le 2 \cdot 10^5\)), consisting of characters 0 and/or 1.The total length of strings \(s\) in all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, print one integer β the minimum cost of removal you can achieve.
|
Consider the test cases of the example: in the first test case, it's possible to remove two characters from the beginning and one character from the end. Only one 1 is deleted, only one 0 remains, so the cost is \(1\); in the second test case, it's possible to remove three characters from the beginning and six characters from the end. Two characters 0 remain, three characters 1 are deleted, so the cost is \(3\); in the third test case, it's optimal to remove four characters from the beginning; in the fourth test case, it's optimal to remove the whole string; in the fifth test case, it's optimal to leave the string as it is.
|
Input: 510111011010010010010010000111111000001111 | Output: 1 3 0 0 0
|
Medium
| 4 | 492 | 311 | 84 | 16 |
2,048 |
A
|
2048A
|
A. Kevin and Combination Lock
| 800 |
brute force; greedy; implementation; math; number theory
|
Kevin is trapped in Lakeside Village by Grace. At the exit of the village, there is a combination lock that can only be unlocked if Kevin solves it.The combination lock starts with an integer \( x \). Kevin can perform one of the following two operations zero or more times: If \( x \neq 33 \), he can select two consecutive digits \( 3 \) from \( x \) and remove them simultaneously. For example, if \( x = 13\,323 \), he can remove the second and third \( 3 \), changing \( x \) to \( 123 \). If \( x \geq 33 \), he can change \( x \) to \( x - 33 \). For example, if \( x = 99 \), he can choose this operation to change \( x \) to \( 99 - 33 = 66 \). When the value of \( x \) on the combination lock becomes \( 0 \), Kevin can unlock the lock and escape from Lakeside Village. Please determine whether it is possible for Kevin to unlock the combination lock and escape.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)).The only line of each test case contains a positive integer \(x\) (\(1\leq x\leq 10^9\)).
|
For each test case, output ""YES"" or ""NO"" (without quotes) in one line, representing whether Kevin can unlock the combination lock and escape. You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
|
For the first test case, \(165\xrightarrow{-33}132\xrightarrow{-33}99\xrightarrow{-33}66\xrightarrow{-33}33\xrightarrow{-33}0\).For the second test case, \(6369\xrightarrow{-33}6{\color{red}{33}}6\xrightarrow{\text{remove ""33""}}66\xrightarrow{-33}33\xrightarrow{-33}0\).For the third test case, it can be proven that, regardless of the operations performed, \(666\) cannot be transformed into \(0\).
|
Input: 51656369666114514133333332 | Output: YES YES NO NO YES
|
Beginner
| 5 | 873 | 207 | 307 | 20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.