problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
A. Find a Numbertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers d and s. Find minimal positive integer n which is divisible by d and has sum of digits equal to s.InputThe first line contains two positive integers d and s (1 \le d \le 500, 1 \le s \le 5000) separated by space.OutputPrint the required number or -1 if it doesn't exist.ExamplesInput13 50Output699998Input61 2Output1000000000000000000000000000001Input15 50Output-1
Input13 50
Output699998
3 seconds
256 megabytes
['dp', 'graphs', 'number theory', 'shortest paths', '*2200']
C. Colored Rookstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan is a novice painter. He has n dyes of different colors. He also knows exactly m pairs of colors which harmonize with each other.Ivan also enjoy playing chess. He has 5000 rooks. He wants to take k rooks, paint each of them in one of n colors and then place this k rooks on a chessboard of size 10^{9} \times 10^{9}.Let's call the set of rooks on the board connected if from any rook we can get to any other rook in this set moving only through cells with rooks from this set. Assume that rooks can jump over other rooks, in other words a rook can go to any cell which shares vertical and to any cell which shares horizontal.Ivan wants his arrangement of rooks to have following properties: For any color there is a rook of this color on a board; For any color the set of rooks of this color is connected; For any two different colors a b union of set of rooks of color a and set of rooks of color b is connected if and only if this two colors harmonize with each other.Please help Ivan find such an arrangement.InputThe first line of input contains 2 integers n, m (1 \le n \le 100, 0 \le m \le min(1000, \,\, \frac{n(n-1)}{2})) — number of colors and number of pairs of colors which harmonize with each other.In next m lines pairs of colors which harmonize with each other are listed. Colors are numbered from 1 to n. It is guaranteed that no pair occurs twice in this list.OutputPrint n blocks, i-th of them describes rooks of i-th color.In the first line of block print one number a_{i} (1 \le a_{i} \le 5000) — number of rooks of color i. In each of next a_{i} lines print two integers x and y (1 \le x, \,\, y \le 10^{9}) — coordinates of the next rook.All rooks must be on different cells.Total number of rooks must not exceed 5000.It is guaranteed that the solution exists.ExamplesInput3 21 22 3Output23 41 441 22 22 45 415 1Input3 31 22 33 1Output11 111 211 3Input3 11 3Output11 112 213 1NoteRooks arrangements for all three examples (red is color 1, green is color 2 and blue is color 3).
Input3 21 22 3
Output23 41 441 22 22 45 415 1
1 second
256 megabytes
['constructive algorithms', 'graphs', '*1700']
B. LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan has number b. He is sorting through the numbers a from 1 to 10^{18}, and for every a writes \frac{[a, \,\, b]}{a} on blackboard. Here [a, \,\, b] stands for least common multiple of a and b. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the board if he would finish the task. Help him to find the quantity of different numbers he would write on the board.InputThe only line contains one integer — b (1 \le b \le 10^{10}).OutputPrint one number — answer for the problem.ExamplesInput1Output1Input2Output2NoteIn the first example [a, \,\, 1] = a, therefore \frac{[a, \,\, b]}{a} is always equal to 1.In the second example [a, \,\, 2] can be equal to a or 2 \cdot a depending on parity of a. \frac{[a, \,\, b]}{a} can be equal to 1 and 2.
Input1
Output1
1 second
256 megabytes
['math', 'number theory', '*1200']
A. Birthdaytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan is collecting coins. There are only N different collectible coins, Ivan has K of them. He will be celebrating his birthday soon, so all his M freinds decided to gift him coins. They all agreed to three terms: Everyone must gift as many coins as others. All coins given to Ivan must be different. Not less than L coins from gifts altogether, must be new in Ivan's collection.But his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms.InputThe only line of input contains 4 integers N, M, K, L (1 \le K \le N \le 10^{18}; 1 \le M, \,\, L \le 10^{18}) — quantity of different coins, number of Ivan's friends, size of Ivan's collection and quantity of coins, that must be new in Ivan's collection.OutputPrint one number — minimal number of coins one friend can gift to satisfy all the conditions. If it is impossible to satisfy all three conditions print "-1" (without quotes).ExamplesInput20 15 2 3Output1Input10 11 2 4Output-1NoteIn the first test, one coin from each friend is enough, as he will be presented with 15 different coins and 13 of them will definitely be new.In the second test, Ivan has 11 friends, but there are only 10 different coins. So all friends can't present him different coins.
Input20 15 2 3
Output1
1 second
256 megabytes
['math', '*1400']
E. Random Forest Ranktime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's define rank of undirected graph as rank of its adjacency matrix in \mathbb{R}^{n \times n}.Given a tree. Each edge of this tree will be deleted with probability 1/2, all these deletions are independent. Let E be the expected rank of resulting forest. Find E \cdot 2^{n-1} modulo 998244353 (it is easy to show that E \cdot 2^{n-1} is an integer).InputFirst line of input contains n (1 \le n \le 5 \cdot 10^{5}) — number of vertices.Next n-1 lines contains two integers u v (1 \le u, \,\, v \le n; \,\, u \ne v) — indices of vertices connected by edge.It is guaranteed that given graph is a tree.OutputPrint one integer — answer to the problem.ExamplesInput31 22 3Output6Input41 21 31 4Output14Input41 22 33 4Output18
Input31 22 3
Output6
3 seconds
512 megabytes
['dp', 'graph matchings', 'math', 'trees', '*2800']
D. Computer Gametime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan plays some computer game. There are n quests in the game. Each quest can be upgraded once, this increases the reward for its completion. Each quest has 3 parameters a_{i}, b_{i}, p_{i}: reward for completing quest before upgrade, reward for completing quest after upgrade (a_{i} < b_{i}) and probability of successful completing the quest.Each second Ivan can try to complete one quest and he will succeed with probability p_{i}. In case of success Ivan will get the reward and opportunity to upgrade any one quest (not necessary the one he just completed). In case of failure he gets nothing. Quests do not vanish after completing.Ivan has t seconds. He wants to maximize expected value of his total gain after t seconds. Help him to calculate this value.InputFirst line contains 2 integers n ( 1 \le n \le 10^{5}) and t ( 1 \le t \le 10^{10}) — number of quests and total time.Following n lines contain description of quests. Each description is 3 numbers a_{i} b_{i} p_{i} (1 \le a_{i} < b_{i} \le 10^{8}, 0 < p_{i} < 1) — reward for completing quest before upgrade, reward for completing quest after upgrade and probability of successful completing of quest. a_{i} and b_{i} are integers. All probabilities are given with at most 9 decimal places.OutputPrint the expected value.Your answer will be accepted if absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac{|a-b|}{max⁡(b, \,\, 1)} \le 10^{-6}.ExamplesInput3 23 1000 0.51 2 0.483 20 0.3Output252.2500000000000Input2 21 1000 0.12 3 0.2Output20.7200000000000
Input3 23 1000 0.51 2 0.483 20 0.3
Output252.2500000000000
3 seconds
256 megabytes
['dp', 'greedy', 'math', 'probabilities', '*3100']
C. Knightstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan places knights on infinite chessboard. Initially there are n knights. If there is free cell which is under attack of at least 4 knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in the end does not depend on the order in which new knights are placed.Ivan asked you to find initial placement of exactly n knights such that in the end there will be at least \lfloor \frac{n^{2}}{10} \rfloor knights.InputThe only line of input contains one integer n (1 \le n \le 10^{3}) — number of knights in the initial placement.OutputPrint n lines. Each line should contain 2 numbers x_{i} and y_{i} (-10^{9} \le x_{i}, \,\, y_{i} \le 10^{9}) — coordinates of i-th knight. For all i \ne j, (x_{i}, \,\, y_{i}) \ne (x_{j}, \,\, y_{j}) should hold. In other words, all knights should be in different cells.It is guaranteed that the solution exists.ExamplesInput4Output1 13 11 54 4Input7Output2 11 24 15 22 65 76 6NoteLet's look at second example:Green zeroes are initial knights. Cell (3, \,\, 3) is under attack of 4 knights in cells (1, \,\, 2), (2, \,\, 1), (4, \,\, 1) and (5, \,\, 2), therefore Ivan will place a knight in this cell. Cell (4, \,\, 5) is initially attacked by only 3 knights in cells (2, \,\, 6), (5, \,\, 7) and (6, \,\, 6). But new knight in cell (3, \,\, 3) also attacks cell (4, \,\, 5), now it is attacked by 4 knights and Ivan will place another knight in this cell. There are no more free cells which are attacked by 4 or more knights, so the process stops. There are 9 knights in the end, which is not less than \lfloor \frac{7^{2}}{10} \rfloor = 4.
Input4
Output1 13 11 54 4
1 second
256 megabytes
['constructive algorithms', '*2600']
B. Multihedgehogtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSomeone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog.Let us define k-multihedgehog as follows: 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. For all k \ge 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog.InputFirst line of input contains 2 integers n, k (1 \le n \le 10^{5}, 1 \le k \le 10^{9}) — number of vertices and hedgehog parameter.Next n-1 lines contains two integers u v (1 \le u, \,\, v \le n; \,\, u \ne v) — indices of vertices connected by edge.It is guaranteed that given graph is a tree.OutputPrint "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise.ExamplesInput14 21 42 43 44 1310 511 512 514 55 136 78 613 69 6OutputYesInput3 11 32 3OutputNoNote2-multihedgehog from the first example looks like this:Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13].Tree from second example is not a hedgehog because degree of center should be at least 3.
Input14 21 42 43 44 1310 511 512 514 55 136 78 613 69 6
OutputYes
1 second
256 megabytes
['dfs and similar', 'graphs', 'shortest paths', '*1800']
A. Array Without Local Maximums time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIvan unexpectedly saw a present from one of his previous birthdays. It is array of n numbers from 1 to 200. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally:a_{1} \le a_{2},a_{n} \le a_{n-1} anda_{i} \le max(a_{i-1}, \,\, a_{i+1}) for all i from 2 to n-1.Ivan does not remember the array and asks to find the number of ways to restore it. Restored elements also should be integers from 1 to 200. Since the number of ways can be big, print it modulo 998244353.InputFirst line of input contains one integer n (2 \le n \le 10^{5}) — size of the array.Second line of input contains n integers a_{i} — elements of array. Either a_{i} = -1 or 1 \le a_{i} \le 200. a_{i} = -1 means that i-th element can't be read.OutputPrint number of ways to restore the array modulo 998244353.ExamplesInput31 -1 2Output1Input2-1 -1Output200NoteIn the first example, only possible value of a_{2} is 2.In the second example, a_{1} = a_{2} so there are 200 different values because all restored elements should be integers between 1 and 200.
Input31 -1 2
Output1
2 seconds
512 megabytes
['dp', '*1900']
F. Yet another 2D Walkingtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMaksim walks on a Cartesian plane. Initially, he stands at the point (0, 0) and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point (0, 0), he can go to any of the following points in one move: (1, 0); (0, 1); (-1, 0); (0, -1). There are also n distinct key points at this plane. The i-th point is p_i = (x_i, y_i). It is guaranteed that 0 \le x_i and 0 \le y_i and there is no key point (0, 0).Let the first level points be such points that max(x_i, y_i) = 1, the second level points be such points that max(x_i, y_i) = 2 and so on. Maksim wants to visit all the key points. But he shouldn't visit points of level i + 1 if he does not visit all the points of level i. He starts visiting the points from the minimum level of point from the given set.The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2| where |v| is the absolute value of v.Maksim wants to visit all the key points in such a way that the total distance he walks will be minimum possible. Your task is to find this distance.If you are Python programmer, consider using PyPy instead of Python when you submit your code.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of key points.Each of the next n lines contains two integers x_i, y_i (0 \le x_i, y_i \le 10^9) — x-coordinate of the key point p_i and y-coordinate of the key point p_i. It is guaranteed that all the points are distinct and the point (0, 0) is not in this set.OutputPrint one integer — the minimum possible total distance Maksim has to travel if he needs to visit all key points in a way described above.ExamplesInput82 21 42 33 13 41 14 31 2Output15Input52 11 02 03 20 3Output9NoteThe picture corresponding to the first example: There is one of the possible answers of length 15.The picture corresponding to the second example: There is one of the possible answers of length 9.
Input82 21 42 33 13 41 14 31 2
Output15
4 seconds
256 megabytes
['dp', '*2100']
E. Binary Numbers AND Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two huge binary integer numbers a and b of lengths n and m respectively. You will repeat the following process: if b > 0, then add to the answer the value a~ \&~ b and divide b by 2 rounding down (i.e. remove the last digit of b), and repeat the process again, otherwise stop the process.The value a~ \&~ b means bitwise AND of a and b. Your task is to calculate the answer modulo 998244353.Note that you should add the value a~ \&~ b to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if a = 1010_2~ (10_{10}) and b = 1000_2~ (8_{10}), then the value a~ \&~ b will be equal to 8, not to 1000.InputThe first line of the input contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the length of a and the length of b correspondingly.The second line of the input contains one huge integer a. It is guaranteed that this number consists of exactly n zeroes and ones and the first digit is always 1.The third line of the input contains one huge integer b. It is guaranteed that this number consists of exactly m zeroes and ones and the first digit is always 1.OutputPrint the answer to this problem in decimal notation modulo 998244353.ExamplesInput4 410101101Output12Input4 5100110101Output11NoteThe algorithm for the first example: add to the answer 1010_2~ \&~ 1101_2 = 1000_2 = 8_{10} and set b := 110; add to the answer 1010_2~ \&~ 110_2 = 10_2 = 2_{10} and set b := 11; add to the answer 1010_2~ \&~ 11_2 = 10_2 = 2_{10} and set b := 1; add to the answer 1010_2~ \&~ 1_2 = 0_2 = 0_{10} and set b := 0. So the answer is 8 + 2 + 2 + 0 = 12.The algorithm for the second example: add to the answer 1001_2~ \&~ 10101_2 = 1_2 = 1_{10} and set b := 1010; add to the answer 1001_2~ \&~ 1010_2 = 1000_2 = 8_{10} and set b := 101; add to the answer 1001_2~ \&~ 101_2 = 1_2 = 1_{10} and set b := 10; add to the answer 1001_2~ \&~ 10_2 = 0_2 = 0_{10} and set b := 1; add to the answer 1001_2~ \&~ 1_2 = 1_2 = 1_{10} and set b := 0. So the answer is 1 + 8 + 1 + 0 + 1 = 11.
Input4 410101101
Output12
1 second
256 megabytes
['data structures', 'implementation', 'math', '*1700']
D. Boxes Packingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMaksim has n objects and m boxes, each box has size exactly k. Objects are numbered from 1 to n in order from left to right, the size of the i-th object is a_i.Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above. If he has no empty boxes and there is at least one object not in some box then Maksim cannot pack the chosen set of objects.Maksim wants to know the maximum number of objects he can pack by the algorithm above. To reach this target, he will throw out the leftmost object from the set until the remaining set of objects can be packed in boxes he has. Your task is to say the maximum number of objects Maksim can pack in boxes he has.Each time when Maksim tries to pack the objects into the boxes, he will make empty all the boxes he has before do it (and the relative order of the remaining set of objects will not change).InputThe first line of the input contains three integers n, m, k (1 \le n, m \le 2 \cdot 10^5, 1 \le k \le 10^9) — the number of objects, the number of boxes and the size of each box.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le k), where a_i is the size of the i-th object.OutputPrint the maximum number of objects Maksim can pack using the algorithm described in the problem statement.ExamplesInput5 2 65 2 1 4 2Output4Input5 1 44 2 3 4 1Output1Input5 3 31 2 3 1 1Output5NoteIn the first example Maksim can pack only 4 objects. Firstly, he tries to pack all the 5 objects. Distribution of objects will be [5], [2, 1]. Maxim cannot pack the next object in the second box and he has no more empty boxes at all. Next he will throw out the first object and the objects distribution will be [2, 1], [4, 2]. So the answer is 4.In the second example it is obvious that Maksim cannot pack all the objects starting from first, second, third and fourth (in all these cases the distribution of objects is [4]), but he can pack the last object ([1]).In the third example Maksim can pack all the objects he has. The distribution will be [1, 2], [3], [1, 1].
Input5 2 65 2 1 4 2
Output4
1 second
256 megabytes
['binary search', 'implementation', '*1800']
C. Books Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have got a shelf and want to put some books on it.You are given q queries of three types: L id — put a book having index id on the shelf to the left from the leftmost existing book; R id — put a book having index id on the shelf to the right from the rightmost existing book; ? id — calculate the minimum number of books you need to pop from the left or from the right in such a way that the book with index id will be leftmost or rightmost. You can assume that the first book you will put can have any position (it does not matter) and queries of type 3 are always valid (it is guaranteed that the book in each such query is already placed). You can also assume that you don't put the same book on the shelf twice, so ids don't repeat in queries of first two types.Your problem is to answer all the queries of type 3 in order they appear in the input.Note that after answering the query of type 3 all the books remain on the shelf and the relative order of books does not change.If you are Python programmer, consider using PyPy instead of Python when you submit your code.InputThe first line of the input contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries.Then q lines follow. The i-th line contains the i-th query in format as in the problem statement. It is guaranteed that queries are always valid (for query type 3, it is guaranteed that the book in each such query is already placed, and for other types, it is guaranteed that the book was not placed before).It is guaranteed that there is at least one query of type 3 in the input.In each query the constraint 1 \le id \le 2 \cdot 10^5 is met.OutputPrint answers to queries of the type 3 in order they appear in the input.ExamplesInput8L 1R 2R 3? 2L 4? 1L 5? 1Output112Input10L 100R 100000R 123L 101? 123L 10R 115? 100R 110? 115Output021NoteLet's take a look at the first example and let's consider queries: The shelf will look like [1]; The shelf will look like [1, 2]; The shelf will look like [1, 2, 3]; The shelf looks like [1, \textbf{2}, 3] so the answer is 1; The shelf will look like [4, 1, 2, 3]; The shelf looks like [4, \textbf{1}, 2, 3] so the answer is 1; The shelf will look like [5, 4, 1, 2, 3]; The shelf looks like [5, 4, \textbf{1}, 2, 3] so the answer is 2. Let's take a look at the second example and let's consider queries: The shelf will look like [100]; The shelf will look like [100, 100000]; The shelf will look like [100, 100000, 123]; The shelf will look like [101, 100, 100000, 123]; The shelf looks like [101, 100, 100000, \textbf{123}] so the answer is 0; The shelf will look like [10, 101, 100, 100000, 123]; The shelf will look like [10, 101, 100, 100000, 123, 115]; The shelf looks like [10, 101, \textbf{100}, 100000, 123, 115] so the answer is 2; The shelf will look like [10, 101, 100, 100000, 123, 115, 110]; The shelf looks like [10, 101, 100, 100000, 123, \textbf{115}, 110] so the answer is 1.
Input8L 1R 2R 3? 2L 4? 1L 5? 1
Output112
2 seconds
256 megabytes
['implementation', '*1400']
B. Heaterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova's house is an array consisting of n elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The i-th element of the array is 1 if there is a heater in the position i, otherwise the i-th element of the array is 0.Each heater has a value r (r is the same for all heaters). This value means that the heater at the position pos can warm up all the elements in range [pos - r + 1; pos + r - 1].Vova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater. Vova's target is to warm up the whole house (all the elements of the array), i.e. if n = 6, r = 2 and heaters are at positions 2 and 5, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first 3 elements will be warmed up by the first heater and the last 3 elements will be warmed up by the second heater).Initially, all the heaters are off.But from the other hand, Vova didn't like to pay much for the electricity. So he wants to switch the minimum number of heaters on in such a way that each element of his house is warmed up by at least one heater.Your task is to find this number of heaters or say that it is impossible to warm up the whole house.InputThe first line of the input contains two integers n and r (1 \le n, r \le 1000) — the number of elements in the array and the value of heaters.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 1) — the Vova's house description.OutputPrint one integer — the minimum number of heaters needed to warm up the whole house or -1 if it is impossible to do it.ExamplesInput6 20 1 1 0 0 1Output3Input5 31 0 0 0 1Output2Input5 100 0 0 0 0Output-1Input10 30 0 1 1 0 1 0 0 0 1Output3NoteIn the first example the heater at the position 2 warms up elements [1; 3], the heater at the position 3 warms up elements [2, 4] and the heater at the position 6 warms up elements [5; 6] so the answer is 3.In the second example the heater at the position 1 warms up elements [1; 3] and the heater at the position 5 warms up elements [3; 5] so the answer is 2.In the third example there are no heaters so the answer is -1.In the fourth example the heater at the position 3 warms up elements [1; 5], the heater at the position 6 warms up elements [4; 8] and the heater at the position 10 warms up elements [8; 10] so the answer is 3.
Input6 20 1 1 0 0 1
Output3
1 second
256 megabytes
['greedy', 'two pointers', '*1500']
A. Vova and Traintime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova plans to go to the conference by train. Initially, the train is at the point 1 and the destination point of the path is the point L. The speed of the train is 1 length unit per minute (i.e. at the first minute the train is at the point 1, at the second minute — at the point 2 and so on).There are lanterns on the path. They are placed at the points with coordinates divisible by v (i.e. the first lantern is at the point v, the second is at the point 2v and so on).There is also exactly one standing train which occupies all the points from l to r inclusive.Vova can see the lantern at the point p if p is divisible by v and there is no standing train at this position (p \not\in [l; r]). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.Your problem is to say the number of lanterns Vova will see during the path. Vova plans to go to t different conferences, so you should answer t independent queries.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of queries.Then t lines follow. The i-th line contains four integers L_i, v_i, l_i, r_i (1 \le L, v \le 10^9, 1 \le l \le r \le L) — destination point of the i-th path, the period of the lantern appearance and the segment occupied by the standing train.OutputPrint t lines. The i-th line should contain one integer — the answer for the i-th query.ExampleInput410 2 3 7100 51 51 511234 1 100 1991000000000 1 1 1000000000Output3011340NoteFor the first example query, the answer is 3. There are lanterns at positions 2, 4, 6, 8 and 10, but Vova didn't see the lanterns at positions 4 and 6 because of the standing train.For the second example query, the answer is 0 because the only lantern is at the point 51 and there is also a standing train at this point.For the third example query, the answer is 1134 because there are 1234 lanterns, but Vova didn't see the lanterns from the position 100 to the position 199 inclusive.For the fourth example query, the answer is 0 because the standing train covers the whole path.
Input410 2 3 7100 51 51 511234 1 100 1991000000000 1 1 1000000000
Output3011340
1 second
256 megabytes
['math', '*1100']
G. Fibonacci Suffixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's denote (yet again) the sequence of Fibonacci strings:F(0) = 0, F(1) = 1, F(i) = F(i - 2) + F(i - 1), where the plus sign denotes the concatenation of two strings.Let's denote the lexicographically sorted sequence of suffixes of string F(i) as A(F(i)). For example, F(4) is 01101, and A(F(4)) is the following sequence: 01, 01101, 1, 101, 1101. Elements in this sequence are numbered from 1.Your task is to print m first characters of k-th element of A(F(n)). If there are less than m characters in this suffix, then output the whole suffix.InputThe only line of the input contains three numbers n, k and m (1 \le n, m \le 200, 1 \le k \le 10^{18}) denoting the index of the Fibonacci string you have to consider, the index of the element of A(F(n)) and the number of characters you have to output, respectively.It is guaranteed that k does not exceed the length of F(n).OutputOutput m first characters of k-th element of A(F(n)), or the whole element if its length is less than m.ExamplesInput4 5 3Output110Input4 3 3Output1
Input4 5 3
Output110
1 second
256 megabytes
['strings', '*2700']
F. Up and Down the Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree with n vertices; its root is vertex 1. Also there is a token, initially placed in the root. You can move the token to other vertices. Let's assume current vertex of token is v, then you make any of the following two possible moves: move down to any leaf in subtree of v; if vertex v is a leaf, then move up to the parent no more than k times. In other words, if h(v) is the depth of vertex v (the depth of the root is 0), then you can move to vertex to such that to is an ancestor of v and h(v) - k \le h(to). Consider that root is not a leaf (even if its degree is 1). Calculate the maximum number of different leaves you can visit during one sequence of moves.InputThe first line contains two integers n and k (1 \le k < n \le 10^6) — the number of vertices in the tree and the restriction on moving up, respectively.The second line contains n - 1 integers p_2, p_3, \dots, p_n, where p_i is the parent of vertex i.It is guaranteed that the input represents a valid tree, rooted at 1.OutputPrint one integer — the maximum possible number of different leaves you can visit.ExamplesInput7 11 1 3 3 4 4Output4Input8 21 1 2 3 4 5 5Output2NoteThe graph from the first example: One of the optimal ways is the next one: 1 \rightarrow 2 \rightarrow 1 \rightarrow 5 \rightarrow 3 \rightarrow 7 \rightarrow 4 \rightarrow 6.The graph from the second example: One of the optimal ways is the next one: 1 \rightarrow 7 \rightarrow 5 \rightarrow 8. Note that there is no way to move from 6 to 7 or 8 and vice versa.
Input7 11 1 3 3 4 4
Output4
3 seconds
256 megabytes
['dfs and similar', 'dp', 'trees', '*2500']
E. Side Transmutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider some set of distinct characters A and some string S, consisting of exactly n characters, where each character is present in A.You are given an array of m integers b (b_1 < b_2 < \dots < b_m). You are allowed to perform the following move on the string S: Choose some valid i and set k = b_i; Take the first k characters of S = Pr_k; Take the last k characters of S = Su_k; Substitute the first k characters of S with the reversed Su_k; Substitute the last k characters of S with the reversed Pr_k. For example, let's take a look at S = "abcdefghi" and k = 2. Pr_2 = "ab", Su_2 = "hi". Reversed Pr_2 = "ba", Su_2 = "ih". Thus, the resulting S is "ihcdefgba".The move can be performed arbitrary number of times (possibly zero). Any i can be selected multiple times over these moves.Let's call some strings S and T equal if and only if there exists such a sequence of moves to transmute string S to string T. For the above example strings "abcdefghi" and "ihcdefgba" are equal. Also note that this implies S = S.The task is simple. Count the number of distinct strings.The answer can be huge enough, so calculate it modulo 998244353.InputThe first line contains three integers n, m and |A| (2 \le n \le 10^9, 1 \le m \le min(\frac n 2, 2 \cdot 10^5), 1 \le |A| \le 10^9) — the length of the strings, the size of the array b and the size of the set A, respectively.The second line contains m integers b_1, b_2, \dots, b_m (1 \le b_i \le \frac n 2, b_1 < b_2 < \dots < b_m).OutputPrint a single integer — the number of distinct strings of length n with characters from set A modulo 998244353.ExamplesInput3 1 21Output6Input9 2 262 3Output150352234Input12 3 12 5 6Output1NoteHere are all the distinct strings for the first example. The chosen letters 'a' and 'b' are there just to show that the characters in A are different. "aaa" "aab" = "baa" "aba" "abb" = "bba" "bab" "bbb"
Input3 1 21
Output6
2 seconds
256 megabytes
['combinatorics', 'strings', '*2300']
D. Three Piecestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily 8 \times 8, but it still is N \times N. Each square has some number written on it, all the numbers are from 1 to N^2 and all the numbers are pairwise distinct. The j-th square in the i-th row has a number A_{ij} written on it.In your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number 1 (you can choose which one). Then you want to reach square 2 (possibly passing through some other squares in process), then square 3 and so on until you reach square N^2. In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. Each square can be visited arbitrary number of times.A knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on.You want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements.What is the path you should take to satisfy all conditions?InputThe first line contains a single integer N (3 \le N \le 10) — the size of the chessboard.Each of the next N lines contains N integers A_{i1}, A_{i2}, \dots, A_{iN} (1 \le A_{ij} \le N^2) — the numbers written on the squares of the i-th row of the board.It is guaranteed that all A_{ij} are pairwise distinct.OutputThe only line should contain two integers — the number of steps in the best answer and the number of replacement moves in it.ExampleInput31 9 38 6 74 2 5Output12 1NoteHere are the steps for the first example (the starting piece is a knight): Move to (3, 2) Move to (1, 3) Move to (3, 2) Replace the knight with a rook Move to (3, 1) Move to (3, 3) Move to (3, 2) Move to (2, 2) Move to (2, 3) Move to (2, 1) Move to (1, 1) Move to (1, 2)
Input31 9 38 6 74 2 5
Output12 1
2 seconds
256 megabytes
['dfs and similar', 'dp', 'shortest paths', '*2200']
C. Make It Equaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of h_i cubes, so it has height h_i.Let's define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make tower's height equal to H. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to k (k \ge n). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.InputThe first line contains two integers n and k (1 \le n \le 2 \cdot 10^5, n \le k \le 10^9) — the number of towers and the restriction on slices, respectively.The second line contains n space separated integers h_1, h_2, \dots, h_n (1 \le h_i \le 2 \cdot 10^5) — the initial heights of towers.OutputPrint one integer — the minimum number of good slices you have to do to make all towers have the same heigth.ExamplesInput5 53 1 2 2 4Output2Input4 52 3 4 5Output2NoteIn the first example it's optimal to make 2 slices. The first slice is on height 2 (its cost is 3), and the second one is on height 1 (its cost is 4).
Input5 53 1 2 2 4
Output2
2 seconds
256 megabytes
['greedy', '*1600']
B. Vasya and Isolated Verticestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has got an undirected graph consisting of n vertices and m edges. This graph doesn't contain any self-loops or multiple edges. Self-loop is an edge connecting a vertex to itself. Multiple edges are a pair of edges such that they connect the same pair of vertices. Since the graph is undirected, the pair of edges (1, 2) and (2, 1) is considered to be multiple edges. Isolated vertex of the graph is a vertex such that there is no edge connecting this vertex to any other vertex.Vasya wants to know the minimum and maximum possible number of isolated vertices in an undirected graph consisting of n vertices and m edges. InputThe only line contains two integers n and m~(1 \le n \le 10^5, 0 \le m \le \frac{n (n - 1)}{2}).It is guaranteed that there exists a graph without any self-loops or multiple edges with such number of vertices and edges.OutputIn the only line print two numbers min and max — the minimum and maximum number of isolated vertices, respectively.ExamplesInput4 2Output0 1Input3 1Output1 1NoteIn the first example it is possible to construct a graph with 0 isolated vertices: for example, it should contain edges (1, 2) and (3, 4). To get one isolated vertex, we may construct a graph with edges (1, 2) and (1, 3). In the second example the graph will always contain exactly one isolated vertex.
Input4 2
Output0 1
1 second
256 megabytes
['constructive algorithms', 'graphs', '*1300']
A. Vasya and Chocolatetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a special offer in Vasya's favourite supermarket: if the customer buys a chocolate bars, he or she may take b additional bars for free. This special offer can be used any number of times.Vasya currently has s roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs c roubles. Help Vasya to calculate the maximum possible number of chocolate bars he can get!InputThe first line contains one integer t (1 \le t \le 100) — the number of testcases.Each of the next t lines contains four integers s, a, b, c~(1 \le s, a, b, c \le 10^9) — the number of roubles Vasya has, the number of chocolate bars you have to buy to use the special offer, the number of bars you get for free, and the cost of one bar, respectively.OutputPrint t lines. i-th line should contain the maximum possible number of chocolate bars Vasya can get in i-th test.ExampleInput210 3 1 11000000000 1 1000000000 1Output131000000001000000000NoteIn the first test of the example Vasya can buy 9 bars, get 3 for free, buy another bar, and so he will get 13 bars.In the second test Vasya buys 1000000000 bars and gets 1000000000000000000 for free. So he has 1000000001000000000 bars.
Input210 3 1 11000000000 1 1000000000 1
Output131000000001000000000
1 second
256 megabytes
['implementation', 'math', '*800']
B. Equations of Mathematical Magictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputColossal! — exclaimed Hawk-nose. — A programmer! That's exactly what we are looking for.Arkadi and Boris Strugatsky. Monday starts on SaturdayReading the book "Equations of Mathematical Magic" Roman Oira-Oira and Cristobal Junta found an interesting equation: a - (a \oplus x) - x = 0 for some given a, where \oplus stands for a bitwise exclusive or (XOR) of two integers (this operation is denoted as ^ or xor in many modern programming languages). Oira-Oira quickly found some x, which is the solution of the equation, but Cristobal Junta decided that Oira-Oira's result is not interesting enough, so he asked his colleague how many non-negative solutions of this equation exist. This task turned out to be too difficult for Oira-Oira, so he asks you to help.InputEach test contains several possible values of a and your task is to find the number of equation's solution for each of them. The first line contains an integer t (1 \le t \le 1000) — the number of these values.The following t lines contain the values of parameter a, each value is an integer from 0 to 2^{30} - 1 inclusive.OutputFor each value of a print exactly one integer — the number of non-negative solutions of the equation for the given value of the parameter. Print answers in the same order as values of a appear in the input.One can show that the number of solutions is always finite.ExampleInput3021073741823Output121073741824NoteLet's define the bitwise exclusive OR (XOR) operation. Given two integers x and y, consider their binary representations (possibly with leading zeroes): x_k \dots x_2 x_1 x_0 and y_k \dots y_2 y_1 y_0. Here, x_i is the i-th bit of the number x and y_i is the i-th bit of the number y. Let r = x \oplus y be the result of the XOR operation of x and y. Then r is defined as r_k \dots r_2 r_1 r_0 where: r_i = \left\{ \begin{aligned} 1, ~ \text{if} ~ x_i \ne y_i \\ 0, ~ \text{if} ~ x_i = y_i \end{aligned} \right. For the first value of the parameter, only x = 0 is a solution of the equation.For the second value of the parameter, solutions are x = 0 and x = 2.
Input3021073741823
Output121073741824
1 second
256 megabytes
['math', '*1200']
A. Make a triangle!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha has three sticks of length a, b and c centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks.What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a triangle of positive area. Sticks should be used as triangle's sides (one stick for one side) and their endpoints should be located at triangle's vertices.InputThe only line contains tree integers a, b and c (1 \leq a, b, c \leq 100) — the lengths of sticks Masha possesses.OutputPrint a single integer — the minimum number of minutes that Masha needs to spend in order to be able to make the triangle of positive area from her sticks.ExamplesInput3 4 5Output0Input2 5 3Output1Input100 10 10Output81NoteIn the first example, Masha can make a triangle from the sticks without increasing the length of any of them.In the second example, Masha can't make a triangle of positive area from the sticks she has at the beginning, but she can spend one minute to increase the length 2 centimeter stick by one and after that form a triangle with sides 3, 3 and 5 centimeters.In the third example, Masha can take 33 minutes to increase one of the 10 centimeters sticks by 33 centimeters, and after that take 48 minutes to increase another 10 centimeters stick by 48 centimeters. This way she can form a triangle with lengths 43, 58 and 100 centimeters in 81 minutes. One can show that it is impossible to get a valid triangle faster.
Input3 4 5
Output0
2 seconds
256 megabytes
['brute force', 'geometry', 'math', '*800']
F. String Journeytime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe call a sequence of strings t1, ..., tk a journey of length k, if for each i > 1 ti is a substring of ti - 1 and length of ti is strictly less than length of ti - 1. For example, {ab, b} is a journey, but {ab, c} and {a, a} are not.Define a journey on string s as journey t1, ..., tk, such that all its parts can be nested inside s in such a way that there exists a sequence of strings u1, ..., uk + 1 (each of these strings can be empty) and s = u1 t1 u2 t2... uk tk uk + 1. As an example, {ab, b} is a journey on string abb, but not on bab because the journey strings ti should appear from the left to the right.The length of a journey on a string is the number of strings in it. Determine the maximum possible length of a journey on the given string s.InputThe first line contains a single integer n (1 ≤ n ≤ 500 000) — the length of string s.The second line contains the string s itself, consisting of n lowercase Latin letters.OutputPrint one number — the maximum possible length of string journey on s.ExamplesInput7abcdbccOutput3Input4bbcbOutput2NoteIn the first sample, the string journey of maximum length is {abcd, bc, c}.In the second sample, one of the suitable journeys is {bb, b}.
Input7abcdbcc
Output3
5 seconds
512 megabytes
['data structures', 'dp', 'string suffix structures', '*3300']
E. Lasers and Mirrorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOleg came to see the maze of mirrors. The maze is a n by n room in which each cell is either empty or contains a mirror connecting opposite corners of this cell. Mirrors in this maze reflect light in a perfect way, which causes the interesting visual effects and contributes to the loss of orientation in the maze.Oleg is a person of curious nature, so he decided to install n lasers facing internal of the maze on the south wall of the maze. On the north wall of the maze, Oleg installed n receivers, also facing internal of the maze. Let's number lasers and receivers from west to east with distinct integers from 1 to n. Each laser sends a beam of some specific kind and receiver with number a_i should receive the beam sent from laser number i. Since two lasers' beams can't come to the same receiver, these numbers form a permutation — each of the receiver numbers occurs exactly once.You came to the maze together with Oleg. Help him to place the mirrors in the initially empty maze so that the maximum number of lasers' beams will come to the receivers they should. There are no mirrors outside the maze, so if the laser beam leaves the maze, it will not be able to go back.InputThe first line contains a single integer n (1 \le n \le 1000) — the size of the maze.The second line contains a permutation of n integers a_i (1 \le a_i \le n), where a_i defines the number of the receiver, to which the beam from i-th laser should come.OutputIn the first line print the maximum possible number of laser beams, which can come to the receivers they should.In the next n lines of length n print the arrangement of mirrors, causing such number of laser beams to come where they should. If the corresponding cell is empty, print ".", otherwise print "/" or "\", depending on the orientation of the mirror.In your output north should be above, south should be below, and west and east should be on left and on the right respectively.It is allowed for laser beams to come not to the receivers they correspond to, but they are not counted in the answer.If there are multiple arrangements of mirrors leading to the optimal answer — print any of them.ExampleInput44 1 3 2Output3.\..\\../../...\NoteThe picture illustrates the arrangements of the mirrors in the first example.
Input44 1 3 2
Output3.\..\\../../...\
1 second
256 megabytes
['constructive algorithms', 'math', '*3000']
D. Candies for Childrentime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt the children's festival, children were dancing in a circle. When music stopped playing, the children were still standing in a circle. Then Lena remembered, that her parents gave her a candy box with exactly k candies "Wilky May". Lena is not a greedy person, so she decided to present all her candies to her friends in the circle. Lena knows, that some of her friends have a sweet tooth and others do not. Sweet tooth takes out of the box two candies, if the box has at least two candies, and otherwise takes one. The rest of Lena's friends always take exactly one candy from the box.Before starting to give candies, Lena step out of the circle, after that there were exactly n people remaining there. Lena numbered her friends in a clockwise order with positive integers starting with 1 in such a way that index 1 was assigned to her best friend Roma.Initially, Lena gave the box to the friend with number l, after that each friend (starting from friend number l) took candies from the box and passed the box to the next friend in clockwise order. The process ended with the friend number r taking the last candy (or two, who knows) and the empty box. Please note that it is possible that some of Lena's friends took candy from the box several times, that is, the box could have gone several full circles before becoming empty.Lena does not know which of her friends have a sweet tooth, but she is interested in the maximum possible number of friends that can have a sweet tooth. If the situation could not happen, and Lena have been proved wrong in her observations, please tell her about this.InputThe only line contains four integers n, l, r and k (1 \le n, k \le 10^{11}, 1 \le l, r \le n) — the number of children in the circle, the number of friend, who was given a box with candies, the number of friend, who has taken last candy and the initial number of candies in the box respectively.OutputPrint exactly one integer — the maximum possible number of sweet tooth among the friends of Lena or "-1" (quotes for clarity), if Lena is wrong.ExamplesInput4 1 4 12Output2Input5 3 4 10Output3Input10 5 5 1Output10Input5 4 5 6Output-1NoteIn the first example, any two friends can be sweet tooths, this way each person will receive the box with candies twice and the last person to take sweets will be the fourth friend.In the second example, sweet tooths can be any three friends, except for the friend on the third position.In the third example, only one friend will take candy, but he can still be a sweet tooth, but just not being able to take two candies. All other friends in the circle can be sweet tooths as well, they just will not be able to take a candy even once.In the fourth example, Lena is wrong and this situation couldn't happen.
Input4 1 4 12
Output2
1 second
256 megabytes
['brute force', 'math', '*2600']
C. Dwarves, Hats and Extrasensory Abilitiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.In good old times dwarves tried to develop extrasensory abilities: Exactly n dwarves entered completely dark cave. Each dwarf received a hat — white or black. While in cave, none of the dwarves was able to see either his own hat or hats of other Dwarves. Dwarves went out of the cave to the meadow and sat at an arbitrary place one after the other. When a dwarf leaves the cave, he sees the colors of all hats of all dwarves that are seating on the meadow (i.e. left the cave before him). However, he is not able to see the color of his own hat and none of the dwarves can give him this information. The task for dwarves was to got diverged into two parts — one with dwarves with white hats and one with black hats. After many centuries, dwarves finally managed to select the right place on the meadow without error. Will you be able to repeat their success?You are asked to successively name n different integer points on the plane. After naming each new point you will be given its color — black or white. Your task is to ensure that the named points can be split by a line in such a way that all points of one color lie on the same side from the line and points of different colors lie on different sides. Moreover, no points can belong to the line. Also, you need to report any such line at the end of the process.In this problem, the interactor is adaptive — the colors of the points in the tests are not fixed beforehand and the jury program can select them arbitrarily, in particular, depending on your program output.InteractionThe first line of the standard input stream contains an integer n (1 ≤ n ≤ 30) — the number of points your program should name.Then n times your program must print two integer coordinates x and y (0 ≤ x ≤ 109, 0 ≤ y ≤ 109). All points you print must be distinct.In response to each coordinate pair your program will receive the string "black", if the point is black, or "white", if the point is white.When all n points are processed, you need to print four integers x1, y1, x2 and y2 (0 ≤ x1, y1 ≤ 109, 0 ≤ x2, y2 ≤ 109) — coordinates of points (x1, y1) and (x2, y2), which form a line, which separates n points into black and white. Points (x1, y1) and (x2, y2) should not coincide.HacksTo hack solution use the following format. The first line must contain word "hack", the second line should contain the number n and the last line should contain the sequence of 0 and 1 — colors of points, which will be reported to the solution. Unlike the jury tests, colors of points in hacks are always fixed in advance. Of course, the hacked solution wouldn't be able to get the information about the colors in advance.For example, the hack corresponding to sample test will look like this: hack50 0 1 1 0ExampleInput5blackblackwhitewhiteblackOutput0 03 12 34 40 21 3 4 1NoteIn the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no "extra" line breaks should appear.The following picture illustrates the first test.
Input5blackblackwhitewhiteblack
Output0 03 12 34 40 21 3 4 1
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'geometry', 'interactive', '*1900']
B. Labyrinthtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?InputThe first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively.The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell.The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively.The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle.It is guaranteed, that the starting cell contains no obstacles.OutputPrint exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.ExamplesInput4 53 21 2......***....***....Output10Input4 42 20 1......*.........Output7NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
Input4 53 21 2......***....***....
Output10
2 seconds
512 megabytes
['graphs', 'shortest paths', '*1800']
A. Oh Those Palindromestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, "abc", "ab", and "c" are substrings of the string "abc", while "ac" and "d" are not.Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string "aaa" is 6 because all its substrings are palindromes, and the palindromic count of the string "abc" is 3 because only its substrings of length 1 are palindromes.You are given a string s. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.InputThe first line contains an integer n (1 \le n \le 100\,000) — the length of string s.The second line contains string s that consists of exactly n lowercase characters of Latin alphabet.OutputPrint string t, which consists of the same set of characters (and each characters appears exactly the same number of times) as string s. Moreover, t should have the maximum possible value of palindromic count among all such strings strings.If there are multiple such strings, print any of them.ExamplesInput5oololOutputololoInput16gagadbcgghhchbdfOutputabccbaghghghgdfdNoteIn the first example, string "ololo" has 9 palindromic substrings: "o", "l", "o", "l", "o", "olo", "lol", "olo", "ololo". Note, that even though some substrings coincide, they are counted as many times as they appear in the resulting string.In the second example, the palindromic count of string "abccbaghghghgdfd" is 29.
Input5oolol
Outputololo
2 seconds
256 megabytes
['constructive algorithms', 'strings', '*1300']
F. Upgrading Citiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in the kingdom X, numbered from 1 through n. People travel between cities by some one-way roads. As a passenger, JATC finds it weird that from any city u, he can't start a trip in it and then return back to it using the roads of the kingdom. That is, the kingdom can be viewed as an acyclic graph.Being annoyed by the traveling system, JATC decides to meet the king and ask him to do something. In response, the king says that he will upgrade some cities to make it easier to travel. Because of the budget, the king will only upgrade those cities that are important or semi-important. A city u is called important if for every city v \neq u, there is either a path from u to v or a path from v to u. A city u is called semi-important if it is not important and we can destroy exactly one city v \neq u so that u becomes important.The king will start to act as soon as he finds out all those cities. Please help him to speed up the process.InputThe first line of the input contains two integers n and m (2 \le n \le 300\,000, 1 \le m \le 300\,000) — the number of cities and the number of one-way roads.Next m lines describe the road system of the kingdom. Each of them contains two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \neq v_i), denoting one-way road from u_i to v_i.It is guaranteed, that the kingdoms' roads make an acyclic graph, which doesn't contain multiple edges and self-loops.OutputPrint a single integer — the number of cities that the king has to upgrade.ExamplesInput7 71 22 33 44 72 55 46 4Output4Input6 71 22 33 41 55 32 66 4Output4NoteIn the first example: Starting at the city 1 we can reach all the other cities, except for the city 6. Also, from the city 6 we cannot reach the city 1. Therefore, if we destroy the city 6 then the city 1 will become important. So 1 is a semi-important city. For city 2, the set of cities that cannot reach 2 and cannot be reached by 2 is \{6\}. Therefore, destroying city 6 will make the city 2 important. So city 2 is also semi-important. For city 3, the set is \{5, 6\}. As you can see, destroying either city 5 or 6 will not make the city 3 important. Therefore, it is neither important nor semi-important. For city 4, the set is empty. So 4 is an important city. The set for city 5 is \{3, 6\} and the set for city 6 is \{3, 5\}. Similarly to city 3, both of them are not important nor semi-important. The city 7 is important since we can reach it from all other cities. So we have two important cities (4 and 7) and two semi-important cities (1 and 2).In the second example, the important cities are 1 and 4. The semi-important cities are 2 and 3.
Input7 71 22 33 44 72 55 46 4
Output4
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*2900']
E. Companytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe company X has n employees numbered from 1 through n. Each employee u has a direct boss p_u (1 \le p_u \le n), except for the employee 1 who has no boss. It is guaranteed, that values p_i form a tree. Employee u is said to be in charge of employee v if u is the direct boss of v or there is an employee w such that w is in charge of v and u is the direct boss of w. Also, any employee is considered to be in charge of himself.In addition, for each employee u we define it's level lv(u) as follow: lv(1)=0 lv(u)=lv(p_u)+1 for u \neq 1 In the near future, there are q possible plans for the company to operate. The i-th plan consists of two integers l_i and r_i, meaning that all the employees in the range [l_i, r_i], and only they, are involved in this plan. To operate the plan smoothly, there must be a project manager who is an employee in charge of all the involved employees. To be precise, if an employee u is chosen as the project manager for the i-th plan then for every employee v \in [l_i, r_i], u must be in charge of v. Note, that u is not necessary in the range [l_i, r_i]. Also, u is always chosen in such a way that lv(u) is as large as possible (the higher the level is, the lower the salary that the company has to pay the employee).Before any plan is operated, the company has JATC take a look at their plans. After a glance, he tells the company that for every plan, it's possible to reduce the number of the involved employees exactly by one without affecting the plan. Being greedy, the company asks JATC which employee they should kick out of the plan so that the level of the project manager required is as large as possible. JATC has already figured out the answer and challenges you to do the same.InputThe first line contains two integers n and q (2 \le n \le 100\,000, 1 \le q \le 100\,000) — the number of employees and the number of plans, respectively.The second line contains n-1 integers p_2, p_3, \dots, p_n (1 \le p_i \le n) meaning p_i is the direct boss of employee i.It is guaranteed, that values p_i form a directed tree with the root of 1.Each of the following q lines contains two integers l_i and r_i (1 \le l_i<r_i \le n) — the range of the employees, involved in the corresponding plan.OutputPrint q lines, each containing two integers — the number of the employee which should be kicked from the corresponding plan and the maximum possible level of the project manager in that case.If there are more than one way to choose that employee, print any of them.ExampleInput11 51 1 3 3 3 4 2 7 7 64 64 81 119 118 11Output4 18 11 011 38 1NoteIn the example: In the first query, we can choose whether 4 or 5 or 6 and the project manager will be 3.In the second query, if we choose any employee other than the employee 8, the project manager will be 1. If we choose 8, the project manager will be 3. Since lv(3)=1 > lv(1)=0, choosing 8 is the best strategy.In the third query, no matter how we choose the employee, the project manager will always be 1.In the fourth query, if we choose 9 or 10 then the project manager will be 3. If we choose 11 then the project manager will be 7. Since lv(7)=3>lv(3)=1, we choose 11 as the answer.
Input11 51 1 3 3 3 4 2 7 7 64 64 81 119 118 11
Output4 18 11 011 38 1
2 seconds
256 megabytes
['binary search', 'data structures', 'dfs and similar', 'greedy', 'trees', '*2300']
D. Fun with Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n greater or equal to 2. For every pair of integers a and b (2 \le |a|, |b| \le n), you can transform a into b if and only if there exists an integer x such that 1 < |x| and (a \cdot x = b or b \cdot x = a), where |x| denotes the absolute value of x.After such a transformation, your score increases by |x| points and you are not allowed to transform a into b nor b into a anymore.Initially, you have a score of 0. You can start at any integer and transform it as many times as you like. What is the maximum score you can achieve?InputA single line contains a single integer n (2 \le n \le 100\,000) — the given integer described above.OutputPrint an only integer — the maximum score that can be achieved with the transformations. If it is not possible to perform even a single transformation for all possible starting integers, print 0.ExamplesInput4Output8Input6Output28Input2Output0NoteIn the first example, the transformations are 2 \rightarrow 4 \rightarrow (-2) \rightarrow (-4) \rightarrow 2.In the third example, it is impossible to perform even a single transformation.
Input4
Output8
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'implementation', 'math', '*1800']
C. Banh-mitime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i \in \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\_, \_, 2]. After eating the last part, JATC's enjoyment will become 4.However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.InputThe first line contains two integers n and q (1 \le n, q \le 100\,000).The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.Each of the following q lines contains two integers l_i and r_i (1 \le l_i \le r_i \le n) — the segment of the corresponding query.OutputPrint q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.ExamplesInput4 210111 43 4Output143Input3 21111 23 3Output31NoteIn the first example: For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer.
Input4 210111 43 4
Output143
1 second
256 megabytes
['greedy', 'implementation', 'math', '*1600']
B. Mathtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer n, you can perform the following operations zero or more times: mul x: multiplies n by x (where x is an arbitrary positive integer). sqrt: replaces n with \sqrt{n} (to apply this operation, \sqrt{n} must be an integer). You can perform these operations as many times as you like. What is the minimum value of n, that can be achieved and what is the minimum number of operations, to achieve that minimum value?Apparently, no one in the class knows the answer to this problem, maybe you can help them?InputThe only line of the input contains a single integer n (1 \le n \le 10^6) — the initial number.OutputPrint two integers: the minimum integer n that can be achieved using the described operations and the minimum number of operations required.ExamplesInput20Output10 2Input5184Output6 4NoteIn the first example, you can apply the operation mul 5 to get 100 and then sqrt to get 10.In the second example, you can first apply sqrt to get 72, then mul 18 to get 1296 and finally two more sqrt and you get 6.Note, that even if the initial value of n is less or equal 10^6, it can still become greater than 10^6 after applying one or more operations.
Input20
Output10 2
1 second
256 megabytes
['greedy', 'math', 'number theory', '*1500']
A. A Pranktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array a_1, a_2, ..., a_n of integers, such that 1 \le a_1 < a_2 < \ldots < a_n \le 10^3, and then went to the bathroom.JATC decided to prank his friend by erasing some consecutive elements in the array. Since he doesn't want for the prank to go too far, he will only erase in a way, such that Giraffe can still restore the array using the information from the remaining elements. Because Giraffe has created the array, he's also aware that it's an increasing array and all the elements are integers in the range [1, 10^3].JATC wonders what is the greatest number of elements he can erase?InputThe first line of the input contains a single integer n (1 \le n \le 100) — the number of elements in the array.The second line of the input contains n integers a_i (1 \le a_1<a_2<\dots<a_n \le 10^3) — the array written by Giraffe.OutputPrint a single integer — the maximum number of consecutive elements in the array that JATC can erase.If it is impossible to erase even a single element, print 0.ExamplesInput61 3 4 5 6 9Output2Input3998 999 1000Output2Input51 2 3 4 5Output4NoteIn the first example, JATC can erase the third and fourth elements, leaving the array [1, 3, \_, \_, 6, 9]. As you can see, there is only one way to fill in the blanks.In the second example, JATC can erase the second and the third elements. The array will become [998, \_, \_]. Because all the elements are less than or equal to 1000, the array is still can be restored. Note, that he can't erase the first 2 elements.In the third example, JATC can erase the first 4 elements. Since all the elements are greater than or equal to 1, Giraffe can still restore the array. Note, that he can't erase the last 4 elements.
Input61 3 4 5 6 9
Output2
1 second
256 megabytes
['greedy', 'implementation', '*1300']
F. Lost Roottime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe graph is called tree if it is connected and has no cycles. Suppose the tree is rooted at some vertex. Then tree is called to be perfect k-ary tree if each vertex is either a leaf (has no children) or has exactly k children. Also, in perfect k-ary tree all leafs must have same depth.For example, the picture below illustrates perfect binary tree with 15 vertices:There is a perfect k-ary tree with n nodes. The nodes are labeled with distinct integers from 1 to n, however you don't know how nodes are labelled. Still, you want to find the label of the root of the tree.You are allowed to make at most 60 \cdot n queries of the following type: "? a b c", the query returns "Yes" if node with label b lies on the path from a to c and "No" otherwise. Both a and c are considered to be lying on the path from a to c.When you are ready to report the root of the tree, print "! s", where s is the label of the root of the tree. It is possible to report the root only once and this query is not counted towards limit of 60 \cdot n queries.InteractionThe first line of the standard input stream contains two integers n and k (3 \le n \le 1500, 2 \le k < n) — the number of nodes in the tree and the value of k. It is guaranteed that n is such that the tree forms a perfect k-ary tree.You can ask at most 60 \cdot n queries. To ask a query, print a line of form "? a b c", where 1 \le a, b, c \le n. After that you should read a single line containing "Yes" or "No" depending on the answer of the query.The tree is fixed for each test and it doesn't depend on your queries.When you are ready to print the answer, print a line of the form "! s", where s is the label of the root vertex and then terminate your program.After printing each query do not forget to print end of line and flush the output. Otherwise you may get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; See documentation for other languages.In case your program will make more than 60 \cdot n queries, but in other aspects would follow the interaction protocol and terminate coorectly, it will get verdict «Wrong Answer».HacksTo hack the solution use the following test format:The first line should contain integers n and k (3 \le n \le 1500, 2 \le k \le 1500) — the number of vertices and the k parameter of the tree.Of course, the value of n must correspond to the size of the valid k-ary tree of some depth.The second line should contain a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the labels of the tree in the natural order, all labels must be distinct.Let's call the following ordering of the tree vertices to be natural: first the root of the tree goes, then go all vertices on depth of one edge from root, ordered from left to right, then go all vertices on depth of two edges from root, ordered from left to right, and so on until the maximum depth.This way, the a_1 is the answer for the hack.ExampleInput3 2NoYesOutput? 1 3 2? 1 2 3! 2NoteThe tree in the example is as follows:The input and output for example illustrate possible interaction on that test (empty lines are inserted only for clarity).The hack corresponding to the example would look like:3 22 3 1
Input3 2NoYes
Output? 1 3 2? 1 2 3! 2
3 seconds
256 megabytes
['interactive', 'probabilities', '*2400']
E. Politicstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in the country. Two candidates are fighting for the post of the President. The elections are set in the future, and both candidates have already planned how they are going to connect the cities with roads. Both plans will connect all cities using n - 1 roads only. That is, each plan can be viewed as a tree. Both of the candidates had also specified their choice of the capital among n cities (x for the first candidate and y for the second candidate), which may or may not be same.Each city has a potential of building a port (one city can have at most one port). Building a port in i-th city brings a_i amount of money. However, each candidate has his specific demands. The demands are of the form: k x, which means that the candidate wants to build exactly x ports in the subtree of the k-th city of his tree (the tree is rooted at the capital of his choice). Find out the maximum revenue that can be gained while fulfilling all demands of both candidates, or print -1 if it is not possible to do.It is additionally guaranteed, that each candidate has specified the port demands for the capital of his choice.InputThe first line contains integers n, x and y (1 \le n \le 500, 1 \le x, y \le n) — the number of cities, the capital of the first candidate and the capital of the second candidate respectively.Next line contains integers a_1, a_2, \ldots, a_n (1 \le a_i \le 100\,000) — the revenue gained if the port is constructed in the corresponding city.Each of the next n - 1 lines contains integers u_i and v_i (1 \le u_i, v_i \le n, u_i \ne v_i), denoting edges between cities in the tree of the first candidate.Each of the next n - 1 lines contains integers u'_i and v'_i (1 \le u'_i, v'_i \le n, u'_i \ne v'_i), denoting edges between cities in the tree of the second candidate.Next line contains an integer q_1 (1 \le q_1 \le n), denoting the number of demands of the first candidate.Each of the next q_1 lines contains two integers k and x (1 \le k \le n, 1 \le x \le n) — the city number and the number of ports in its subtree.Next line contains an integer q_2 (1 \le q_2 \le n), denoting the number of demands of the second candidate.Each of the next q_2 lines contain two integers k and x (1 \le k \le n, 1 \le x \le n) — the city number and the number of ports in its subtree.It is guaranteed, that given edges correspond to valid trees, each candidate has given demand about each city at most once and that each candidate has specified the port demands for the capital of his choice. That is, the city x is always given in demands of the first candidate and city y is always given in the demands of the second candidate.OutputPrint exactly one integer — the maximum possible revenue that can be gained, while satisfying demands of both candidates, or -1 if it is not possible to satisfy all of the demands.ExamplesInput4 1 21 2 3 41 21 33 41 22 31 421 34 112 3Output9Input5 1 13 99 99 100 21 21 33 43 51 31 22 42 521 23 121 22 1Output198Input4 1 21 2 3 41 21 33 42 12 44 311 424 12 4Output-1NoteIn the first example, it is optimal to build ports in cities 2, 3 and 4, which fulfills all demands of both candidates and gives revenue equal to 2 + 3 + 4 = 9.In the second example, it is optimal to build ports in cities 2 and 3, which fulfills all demands of both candidates and gives revenue equal to 99 + 99 = 198. In the third example, it is not possible to build ports in such way, that all demands of both candidates are specified, hence the answer is -1.
Input4 1 21 2 3 41 21 33 41 22 31 421 34 112 3
Output9
4 seconds
256 megabytes
['flows', 'graphs', '*2600']
D. TV Showstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The i-th of the shows is going from l_i-th to r_i-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments [l_i, r_i] and [l_j, r_j] intersect, then shows i and j can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for x rupees, and charges y (y < x) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes [a; b] you will need to pay x + y \cdot (b - a). You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo 10^9 + 7.InputThe first line contains integers n, x and y (1 \le n \le 10^5, 1 \le y < x \le 10^9) — the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute.Each of the next n lines contains two integers l_i and r_i (1 \le l_i \le r_i \le 10^9) denoting the start and the end minute of the i-th TV show.OutputPrint exactly one integer — the minimum cost to view all the shows taken modulo 10^9 + 7.ExamplesInput5 4 31 24 102 410 115 9Output60Input6 3 28 206 224 1520 2817 2520 27Output142Input2 1000000000 21 22 3Output999999997NoteIn the first example, the optimal strategy would be to rent 3 TVs to watch: Show [1, 2] on the first TV, Show [4, 10] on the second TV, Shows [2, 4], [5, 9], [10, 11] on the third TV. This way the cost for the first TV is 4 + 3 \cdot (2 - 1) = 7, for the second is 4 + 3 \cdot (10 - 4) = 22 and for the third is 4 + 3 \cdot (11 - 2) = 31, which gives 60 int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo 10^9 + 7.
Input5 4 31 24 102 410 115 9
Output60
2 seconds
256 megabytes
['data structures', 'greedy', 'implementation', 'sortings', '*2000']
C. Multiplicitytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer array a_1, a_2, \ldots, a_n.The array b is called to be a subsequence of a if it is possible to remove some elements from a to get b.Array b_1, b_2, \ldots, b_k is called to be good if it is not empty and for every i (1 \le i \le k) b_i is divisible by i.Find the number of good subsequences in a modulo 10^9 + 7. Two subsequences are considered different if index sets of numbers included in them are different. That is, the values ​of the elements ​do not matter in the comparison of subsequences. In particular, the array a has exactly 2^n - 1 different subsequences (excluding an empty subsequence).InputThe first line contains an integer n (1 \le n \le 100\,000) — the length of the array a.The next line contains integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^6).OutputPrint exactly one integer — the number of good subsequences taken modulo 10^9 + 7.ExamplesInput21 2Output3Input52 2 1 22 14Output13NoteIn the first example, all three non-empty possible subsequences are good: \{1\}, \{1, 2\}, \{2\}In the second example, the possible good subsequences are: \{2\}, \{2, 2\}, \{2, 22\}, \{2, 14\}, \{2\}, \{2, 22\}, \{2, 14\}, \{1\}, \{1, 22\}, \{1, 14\}, \{22\}, \{22, 14\}, \{14\}.Note, that some subsequences are listed more than once, since they occur in the original array multiple times.
Input21 2
Output3
3 seconds
256 megabytes
['data structures', 'dp', 'implementation', 'math', 'number theory', '*1700']
B. Views Mattertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou came to the exhibition and one exhibit has drawn your attention. It consists of n stacks of blocks, where the i-th stack consists of a_i blocks resting on the surface.The height of the exhibit is equal to m. Consequently, the number of blocks in each stack is less than or equal to m.There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks. Find the maximum number of blocks you can remove such that the views for both the cameras would not change.Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is no gravity in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either.InputThe first line contains two integers n and m (1 \le n \le 100\,000, 1 \le m \le 10^9) — the number of stacks and the height of the exhibit.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le m) — the number of blocks in each stack from left to right.OutputPrint exactly one integer — the maximum number of blocks that can be removed.ExamplesInput5 63 3 3 3 3Output10Input3 51 2 4Output3Input5 52 3 1 4 4Output9Input1 1000548Output0Input3 33 1 1Output1NoteThe following pictures illustrate the first example and its possible solution.Blue cells indicate removed blocks. There are 10 blue cells, so the answer is 10.
Input5 63 3 3 3 3
Output10
2 seconds
256 megabytes
['greedy', 'implementation', 'sortings', '*1400']
A. Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have unlimited number of coins with values 1, 2, \ldots, n. You want to select some set of coins having the total value of S. It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S?InputThe only line of the input contains two integers n and S (1 \le n \le 100\,000, 1 \le S \le 10^9)OutputPrint exactly one integer — the minimum number of coins required to obtain sum S.ExamplesInput5 11Output3Input6 16Output3NoteIn the first example, some of the possible ways to get sum 11 with 3 coins are: (3, 4, 4) (2, 4, 5) (1, 5, 5) (3, 3, 5) It is impossible to get sum 11 with less than 3 coins.In the second example, some of the possible ways to get sum 16 with 3 coins are: (5, 5, 6) (4, 6, 6) It is impossible to get sum 16 with less than 3 coins.
Input5 11
Output3
2 seconds
256 megabytes
['greedy', 'implementation', 'math', '*800']
G. Balls and Pocketstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is a strip with an infinite number of cells. Cells are numbered starting with 0. Initially the cell i contains a ball with the number i.There are n pockets located at cells a_1, \ldots, a_n. Each cell contains at most one pocket.Filtering is the following sequence of operations: All pockets at cells a_1, \ldots, a_n open simultaneously, which makes balls currently located at those cells disappear. After the balls disappear, the pockets close again. For each cell i from 0 to \infty, if the cell i contains a ball, we move that ball to the free cell j with the lowest number. If there is no free cell j < i, the ball stays at the cell i.Note that after each filtering operation each cell will still contain exactly one ball.For example, let the cells 1, 3 and 4 contain pockets. The initial configuration of balls is shown below (underscores display the cells with pockets): 0 1 2 3 4 5 6 7 8 9 ... After opening and closing the pockets, balls 1, 3 and 4 disappear: 0   2     5 6 7 8 9 ... After moving all the balls to the left, the configuration looks like this: 0 2 5 6 7 8 9 10 11 12 ... Another filtering repetition results in the following: 0 5 8 9 10 11 12 13 14 15 ... You have to answer m questions. The i-th of these questions is "what is the number of the ball located at the cell x_i after k_i repetitions of the filtering operation?"InputThe first line contains two integers n and m — the number of pockets and questions respectively (1 \leq n, m \leq 10^5).The following line contains n integers a_1, \ldots, a_n — the numbers of cells containing pockets (0 \leq a_1 < \ldots < a_n \leq 10^9).The following m lines describe questions. The i-th of these lines contains two integers x_i and k_i (0 \leq x_i, k_i \leq 10^9).OutputPrint m numbers — answers to the questions, in the same order as given in the input.ExampleInput3 151 3 40 01 02 03 04 00 11 12 13 14 10 21 22 23 24 2Output0123402567058910
Input3 151 3 40 01 02 03 04 00 11 12 13 14 10 21 22 23 24 2
Output0123402567058910
2 seconds
512 megabytes
['data structures', '*3400']
F. Shrinking Treetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider a tree T (that is, a connected graph without cycles) with n vertices labelled 1 through n. We start the following process with T: while T has more than one vertex, do the following: choose a random edge of T equiprobably; shrink the chosen edge: if the edge was connecting vertices v and u, erase both v and u and create a new vertex adjacent to all vertices previously adjacent to either v or u. The new vertex is labelled either v or u equiprobably.At the end of the process, T consists of a single vertex labelled with one of the numbers 1, \ldots, n. For each of the numbers, what is the probability of this number becoming the label of the final vertex?InputThe first line contains a single integer n (1 \leq n \leq 50).The following n - 1 lines describe the tree edges. Each of these lines contains two integers u_i, v_i — labels of vertices connected by the respective edge (1 \leq u_i, v_i \leq n, u_i \neq v_i). It is guaranteed that the given graph is a tree.OutputPrint n floating numbers — the desired probabilities for labels 1, \ldots, n respectively. All numbers should be correct up to 10^{-6} relative or absolute precision.ExamplesInput41 21 31 4Output0.12500000000.29166666670.29166666670.2916666667Input71 21 32 42 53 63 7Output0.08506944440.06640625000.06640625000.19552951390.19552951390.19552951390.1955295139NoteIn the first sample, the resulting vertex has label 1 if and only if for all three edges the label 1 survives, hence the probability is 1/2^3 = 1/8. All other labels have equal probability due to symmetry, hence each of them has probability (1 - 1/8) / 3 = 7/24.
Input41 21 31 4
Output0.12500000000.29166666670.29166666670.2916666667
2 seconds
512 megabytes
['combinatorics', 'dp', '*2900']
E. Sergey and Subwaytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at night). However, his assistants have found a solution and they now draw an imaginary city on a paper sheet and suggest the mayor can propose its improvements.Right now he has a map of some imaginary city with n subway stations. Some stations are directly connected with tunnels in such a way that the whole map is a tree (assistants were short on time and enthusiasm). It means that there exists exactly one simple path between each pair of station. We call a path simple if it uses each tunnel no more than once.One of Sergey Semyonovich's favorite quality objectives is the sum of all pairwise distances between every pair of stations. The distance between two stations is the minimum possible number of tunnels on a path between them.Sergey Semyonovich decided to add new tunnels to the subway map. In particular, he connected any two stations u and v that were not connected with a direct tunnel but share a common neighbor, i.e. there exists such a station w that the original map has a tunnel between u and w and a tunnel between w and v. You are given a task to compute the sum of pairwise distances between all pairs of stations in the new map.InputThe first line of the input contains a single integer n (2 \leq n \leq 200\,000) — the number of subway stations in the imaginary city drawn by mayor's assistants. Each of the following n - 1 lines contains two integers u_i and v_i (1 \leq u_i, v_i \leq n, u_i \ne v_i), meaning the station with these indices are connected with a direct tunnel.It is guaranteed that these n stations and n - 1 tunnels form a tree.OutputPrint one integer that is equal to the sum of distances between all pairs of stations after Sergey Semyonovich draws new tunnels between all pairs of stations that share a common neighbor in the original map.ExamplesInput41 21 31 4Output6Input41 22 33 4Output7NoteIn the first sample, in the new map all pairs of stations share a direct connection, so the sum of distances is 6.In the second sample, the new map has a direct tunnel between all pairs of stations except for the pair (1, 4). For these two stations the distance is 2.
Input41 21 31 4
Output6
2 seconds
512 megabytes
['dfs and similar', 'dp', 'trees', '*2000']
D. Social Circlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou invited n guests to dinner! You plan to arrange one or more circles of chairs. Each chair is going to be either occupied by one guest, or be empty. You can make any number of circles. Your guests happen to be a little bit shy, so the i-th guest wants to have a least l_i free chairs to the left of his chair, and at least r_i free chairs to the right. The "left" and "right" directions are chosen assuming all guests are going to be seated towards the center of the circle. Note that when a guest is the only one in his circle, the l_i chairs to his left and r_i chairs to his right may overlap.What is smallest total number of chairs you have to use?InputFirst line contains one integer n  — number of guests, (1 \leqslant n \leqslant 10^5). Next n lines contain n pairs of space-separated integers l_i and r_i (0 \leqslant l_i, r_i \leqslant 10^9).OutputOutput a single integer — the smallest number of chairs you have to use.ExamplesInput31 11 11 1Output6Input41 22 13 55 3Output15Input15 6Output7NoteIn the second sample the only optimal answer is to use two circles: a circle with 5 chairs accomodating guests 1 and 2, and another one with 10 chairs accomodationg guests 3 and 4.In the third sample, you have only one circle with one person. The guest should have at least five free chairs to his left, and at least six free chairs to his right to the next person, which is in this case the guest herself. So, overall number of chairs should be at least 6+1=7.
Input31 11 11 1
Output6
2 seconds
512 megabytes
['greedy', 'math', '*1900']
C. Maximum Subrectangletime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b of positive integers, with length n and m respectively. Let c be an n \times m matrix, where c_{i,j} = a_i \cdot b_j. You need to find a subrectangle of the matrix c such that the sum of its elements is at most x, and its area (the total number of elements) is the largest possible.Formally, you need to find the largest number s such that it is possible to choose integers x_1, x_2, y_1, y_2 subject to 1 \leq x_1 \leq x_2 \leq n, 1 \leq y_1 \leq y_2 \leq m, (x_2 - x_1 + 1) \times (y_2 - y_1 + 1) = s, and \sum_{i=x_1}^{x_2}{\sum_{j=y_1}^{y_2}{c_{i,j}}} \leq x.InputThe first line contains two integers n and m (1 \leq n, m \leq 2000).The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 2000).The third line contains m integers b_1, b_2, \ldots, b_m (1 \leq b_i \leq 2000).The fourth line contains a single integer x (1 \leq x \leq 2 \cdot 10^{9}).OutputIf it is possible to choose four integers x_1, x_2, y_1, y_2 such that 1 \leq x_1 \leq x_2 \leq n, 1 \leq y_1 \leq y_2 \leq m, and \sum_{i=x_1}^{x_2}{\sum_{j=y_1}^{y_2}{c_{i,j}}} \leq x, output the largest value of (x_2 - x_1 + 1) \times (y_2 - y_1 + 1) among all such quadruplets, otherwise output 0.ExamplesInput3 31 2 31 2 39Output4Input5 15 4 2 4 525Output1NoteMatrix from the first sample and the chosen subrectangle (of blue color): Matrix from the second sample and the chosen subrectangle (of blue color):
Input3 31 2 31 2 39
Output4
2 seconds
512 megabytes
['binary search', 'implementation', 'two pointers', '*1600']
B. Maximum Sum of Digitstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n.Let S(x) be sum of digits in base 10 representation of x, for example, S(123) = 1 + 2 + 3 = 6, S(0) = 0.Your task is to find two integers a, b, such that 0 \leq a, b \leq n, a + b = n and S(a) + S(b) is the largest possible among all such pairs.InputThe only line of input contains an integer n (1 \leq n \leq 10^{12}).OutputPrint largest S(a) + S(b) among all pairs of integers a, b, such that 0 \leq a, b \leq n and a + b = n.ExamplesInput35Output17Input10000000000Output91NoteIn the first example, you can choose, for example, a = 17 and b = 18, so that S(17) + S(18) = 1 + 7 + 1 + 8 = 17. It can be shown that it is impossible to get a larger answer.In the second test example, you can choose, for example, a = 5000000001 and b = 4999999999, with S(5000000001) + S(4999999999) = 91. It can be shown that it is impossible to get a larger answer.
Input35
Output17
2 seconds
512 megabytes
['greedy', '*1100']
A. Phone Numberstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit.For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not.You have n cards with digits, and you want to use them to make as many phone numbers as possible. Each card must be used in at most one phone number, and you don't have to use all cards. The phone numbers do not necessarily have to be distinct.InputThe first line contains an integer n — the number of cards with digits that you have (1 \leq n \leq 100).The second line contains a string of n digits (characters "0", "1", ..., "9") s_1, s_2, \ldots, s_n. The string will not contain any other characters, such as leading or trailing spaces.OutputIf at least one phone number can be made from these cards, output the maximum number of phone numbers that can be made. Otherwise, output 0.ExamplesInput1100000000008Output1Input220011223344556677889988Output2Input1131415926535Output0NoteIn the first example, one phone number, "8000000000", can be made from these cards.In the second example, you can make two phone numbers from the cards, for example, "80123456789" and "80123456789".In the third example you can't make any phone number from the given cards.
Input1100000000008
Output1
2 seconds
512 megabytes
['brute force', '*800']
E. Split the Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belong to exactly one path.A vertical path is a sequence of vertices v_1, v_2, \ldots, v_k where v_i (i \ge 2) is the parent of v_{i - 1}.InputThe first line contains three integers n, L, S (1 \le n \le 10^5, 1 \le L \le 10^5, 1 \le S \le 10^{18}) — the number of vertices, the maximum number of vertices in one path and the maximum sum in one path.The second line contains n integers w_1, w_2, \ldots, w_n (1 \le w_i \le 10^9) — the numbers in the vertices of the tree.The third line contains n - 1 integers p_2, \ldots, p_n (1 \le p_i < i), where p_i is the parent of the i-th vertex in the tree.OutputOutput one number  — the minimum number of vertical paths. If it is impossible to split the tree, output -1.ExamplesInput3 1 31 2 31 1Output3Input3 3 61 2 31 1Output2Input1 1 1000010001Output-1NoteIn the first sample the tree is split into \{1\},\ \{2\},\ \{3\}.In the second sample the tree is split into \{1,\ 2\},\ \{3\} or \{1,\ 3\},\ \{2\}.In the third sample it is impossible to split the tree.
Input3 1 31 2 31 1
Output3
2 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'greedy', 'trees', '*2400']
D. Nature Reservetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a forest that we model as a plane and live n rare animals. Animal number i has its lair in the point (x_{i}, y_{i}). In order to protect them, a decision to build a nature reserve has been made.The reserve must have a form of a circle containing all lairs. There is also a straight river flowing through the forest. All animals drink from this river, therefore it must have at least one common point with the reserve. On the other hand, ships constantly sail along the river, so the reserve must not have more than one common point with the river.For convenience, scientists have made a transformation of coordinates so that the river is defined by y = 0. Check whether it is possible to build a reserve, and if possible, find the minimum possible radius of such a reserve.InputThe first line contains one integer n (1 \le n \le 10^5) — the number of animals. Each of the next n lines contains two integers x_{i}, y_{i} (-10^7 \le x_{i}, y_{i} \le 10^7) — the coordinates of the i-th animal's lair. It is guaranteed that y_{i} \neq 0. No two lairs coincide.OutputIf the reserve cannot be built, print -1. Otherwise print the minimum radius. Your answer will be accepted if absolute or relative error does not exceed 10^{-6}.Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}.ExamplesInput10 1Output0.5Input30 10 20 -3Output-1Input20 11 1Output0.625NoteIn the first sample it is optimal to build the reserve with the radius equal to 0.5 and the center in (0,\ 0.5).In the second sample it is impossible to build a reserve.In the third sample it is optimal to build the reserve with the radius equal to \frac{5}{8} and the center in (\frac{1}{2},\ \frac{5}{8}).
Input10 1
Output0.5
2 seconds
256 megabytes
['binary search', 'geometry', 'ternary search', '*2200']
C. Sequence Transformationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call the following process a transformation of a sequence of length n.If the sequence is empty, the process ends. Otherwise, append the greatest common divisor (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.You are given an integer sequence 1, 2, \dots, n. Find the lexicographically maximum result of its transformation.A sequence a_1, a_2, \ldots, a_n is lexicographically larger than a sequence b_1, b_2, \ldots, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.InputThe first and only line of input contains one integer n (1\le n\le 10^6).OutputOutput n integers  — the lexicographically maximum result of the transformation.ExamplesInput3Output1 1 3 Input2Output1 2 Input1Output1 NoteIn the first sample the answer may be achieved this way: Append GCD(1, 2, 3) = 1, remove 2. Append GCD(1, 3) = 1, remove 1. Append GCD(3) = 3, remove 3. We get the sequence [1, 1, 3] as the result.
Input3
Output1 1 3
2 seconds
256 megabytes
['constructive algorithms', 'math', '*1600']
B. Forgerytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputStudent Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?For simplicity, the signature is represented as an n\times m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3\times3 square without its central cell if it is completely contained inside the grid, as shown below. xxxx.xxxx Determine whether is it possible to forge the signature on an empty n\times m grid.InputThe first line of input contains two integers n and m (3 \le n, m \le 1000).Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.OutputIf Andrey can forge the signature, output "YES". Otherwise output "NO".You can print each letter in any case (upper or lower).ExamplesInput3 3####.####OutputYESInput3 3#########OutputNOInput4 3############OutputYESInput5 7........#####..#.#.#..#####........OutputYESNoteIn the first sample Andrey can paint the border of the square with the center in (2, 2).In the second sample the signature is impossible to forge.In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2): we have a clear paper: ............ use the pen with center at (2, 2). ####.####... use the pen with center at (3, 2). ############ In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5).
Input3 3####.####
OutputYES
2 seconds
256 megabytes
['implementation', '*1300']
A. Cashiertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has recently got a job as a cashier at a local store. His day at work is L minutes long. Vasya has already memorized n regular customers, the i-th of which comes after t_{i} minutes after the beginning of the day, and his service consumes l_{i} minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for a minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day?InputThe first line contains three integers n, L and a (0 \le n \le 10^{5}, 1 \le L \le 10^{9}, 1 \le a \le L).The i-th of the next n lines contains two integers t_{i} and l_{i} (0 \le t_{i} \le L - 1, 1 \le l_{i} \le L). It is guaranteed that t_{i} + l_{i} \le t_{i + 1} and t_{n} + l_{n} \le L.OutputOutput one integer  — the maximum number of breaks.ExamplesInput2 11 30 11 1Output3Input0 5 2Output2Input1 3 21 2Output0NoteIn the first sample Vasya can take 3 breaks starting after 2, 5 and 8 minutes after the beginning of the day.In the second sample Vasya can take 2 breaks starting after 0 and 2 minutes after the beginning of the day.In the third sample Vasya can't take any breaks.
Input2 11 30 11 1
Output3
2 seconds
256 megabytes
['implementation', '*1000']
C. Tanya and Colored Candiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n candy boxes in front of Tania. The boxes are arranged in a row from left to right, numbered from 1 to n. The i-th box contains r_i candies, candies have the color c_i (the color can take one of three values ​​— red, green, or blue). All candies inside a single box have the same color (and it is equal to c_i).Initially, Tanya is next to the box number s. Tanya can move to the neighbor box (that is, with a number that differs by one) or eat candies in the current box. Tanya eats candies instantly, but the movement takes one second.If Tanya eats candies from the box, then the box itself remains in place, but there is no more candies in it. In other words, Tanya always eats all the candies from the box and candies in the boxes are not refilled.It is known that Tanya cannot eat candies of the same color one after another (that is, the colors of candies in two consecutive boxes from which she eats candies are always different). In addition, Tanya's appetite is constantly growing, so in each next box from which she eats candies, there should be strictly more candies than in the previous one.Note that for the first box from which Tanya will eat candies, there are no restrictions on the color and number of candies.Tanya wants to eat at least k candies. What is the minimum number of seconds she will need? Remember that she eats candies instantly, and time is spent only on movements.InputThe first line contains three integers n, s and k (1 \le n \le 50, 1 \le s \le n, 1 \le k \le 2000) — number of the boxes, initial position of Tanya and lower bound on number of candies to eat. The following line contains n integers r_i (1 \le r_i \le 50) — numbers of candies in the boxes. The third line contains sequence of n letters 'R', 'G' and 'B', meaning the colors of candies in the correspondent boxes ('R' for red, 'G' for green, 'B' for blue). Recall that each box contains candies of only one color. The third line contains no spaces.OutputPrint minimal number of seconds to eat at least k candies. If solution doesn't exist, print "-1".ExamplesInput5 3 101 2 3 4 5RGBRROutput4Input2 1 155 6RGOutput-1NoteThe sequence of actions of Tanya for the first example: move from the box 3 to the box 2; eat candies from the box 2; move from the box 2 to the box 3; eat candy from the box 3; move from the box 3 to the box 4; move from the box 4 to the box 5; eat candies from the box 5. Since Tanya eats candy instantly, the required time is four seconds.
Input5 3 101 2 3 4 5RGBRR
Output4
2 seconds
256 megabytes
['*special problem', 'dp', '*2000']
B. DDoStime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe get more and more news about DDoS-attacks of popular websites.Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 \cdot t, where t — the number of seconds in this time segment. Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, \dots, r_n, where r_i — the number of requests in the i-th second after boot. Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].InputThe first line contains n (1 \le n \le 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, \dots, r_n (0 \le r_i \le 5000), r_i — number of requests in the i-th second.OutputPrint the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.ExamplesInput5100 200 1 1 1Output3Input51 2 3 4 5Output0Input2101 99Output1
Input5100 200 1 1 1
Output3
2 seconds
256 megabytes
['*special problem', 'brute force', '*1400']
A. Bmail Computer Networktime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values p_i — the index of the router to which the i-th router was connected after being purchased (p_i < i).There are n routers in Boogle in total now. Print the sequence of routers on the path from the first to the n-th router.InputThe first line contains integer number n (2 \le n \le 200000) — the number of the routers. The following line contains n-1 integers p_2, p_3, \dots, p_n (1 \le p_i < i), where p_i is equal to index of the router to which the i-th was connected after purchase.OutputPrint the path from the 1-st to the n-th router. It starts with 1 and ends with n. All the elements in the path should be distinct.ExamplesInput81 1 2 2 3 2 5Output1 2 5 8 Input61 2 3 4 5Output1 2 3 4 5 6 Input71 1 2 3 4 3Output1 3 7
Input81 1 2 2 3 2 5
Output1 2 5 8
4 seconds
256 megabytes
['*special problem', 'dfs and similar', 'trees', '*900']
H. Detect Robotstime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou successfully found poor Arkady near the exit of the station you've perfectly predicted. You sent him home on a taxi and suddenly came up with a question.There are n crossroads in your city and several bidirectional roads connecting some of them. A taxi ride is a path from some crossroads to another one without passing the same crossroads twice. You have a collection of rides made by one driver and now you wonder if this driver can be a robot or they are definitely a human.You think that the driver can be a robot if for every two crossroads a and b the driver always chooses the same path whenever he drives from a to b. Note that a and b here do not have to be the endpoints of a ride and that the path from b to a can be different. On the contrary, if the driver ever has driven two different paths from a to b, they are definitely a human.Given the system of roads and the description of all rides available to you, determine if the driver can be a robot or not.InputEach test contains one or more test cases. The first line contains a single integer t (1 \le t \le 3 \cdot 10^5) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 3 \cdot 10^5) — the number of crossroads in the city.The next line contains a single integer q (1 \le q \le 3 \cdot 10^5) — the number of rides available to you.Each of the following q lines starts with a single integer k (2 \le k \le n) — the number of crossroads visited by the driver on this ride. It is followed by k integers c_1, c_2, ..., c_k (1 \le c_i \le n) — the crossroads in the order the driver visited them. It is guaranteed that all crossroads in one ride are distinct.It is guaranteed that the sum of values k among all rides of all test cases does not exceed 3 \cdot 10^5.It is guaranteed that the sum of values n and the sum of values q doesn't exceed 3 \cdot 10^5 among all test cases.OutputOutput a single line for each test case.If the driver can be a robot, output "Robot" in a single line. Otherwise, output "Human".You can print each letter in any case (upper or lower).ExamplesInput 1 5 2 4 1 2 3 5 3 1 4 3 Output Human Input 1 4 4 3 1 2 3 3 2 3 4 3 3 4 1 3 4 1 2 Output Robot NoteIn the first example it is clear that the driver used two different ways to get from crossroads 1 to crossroads 3. It must be a human.In the second example the driver always drives the cycle 1 \to 2 \to 3 \to 4 \to 1 until he reaches destination.
1 5 2 4 1 2 3 5 3 1 4 3
Human
1 second
1024 megabytes
['data structures', 'strings', '*3200']
G. Take Metrotime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHaving problems with tram routes in the morning, Arkady decided to return home by metro. Fortunately for Arkady, there is only one metro line in the city.Unfortunately for Arkady, the line is circular. It means that the stations are enumerated from 1 to n and there is a tunnel between any pair of consecutive stations as well as between the station 1 and the station n. Trains that go in clockwise direction visit the stations in order 1 \to 2 \to 3 \to \ldots \to n \to 1 while the trains that go in the counter-clockwise direction visit the stations in the reverse order.The stations that have numbers from 1 to m have interior mostly in red colors while the stations that have numbers from m + 1 to n have blue interior. Arkady entered the metro at station s and decided to use the following algorithm to choose his way home. Initially he has a positive integer t in his mind. If the current station has red interior, he takes a clockwise-directed train, otherwise he takes a counter-clockwise-directed train. He rides exactly t stations on the train and leaves the train. He decreases t by one. If t is still positive, he returns to step 2. Otherwise he exits the metro. You have already realized that this algorithm most probably won't bring Arkady home. Find the station he will exit the metro at so that you can continue helping him.InputThe first line contains two integers n and m (3 \le n \le 10^5, 1 \le m < n) — the total number of stations and the number of stations that have red interior.The second line contains two integers s and t (1 \le s \le n, 1 \le t \le 10^{12}) — the starting station and the initial value of t.OutputOutput the only integer — the station where Arkady will exit the metro.ExamplesInput 10 4 3 1 Output 4 Input 10 4 3 5 Output 4 Input 10543 437 5492 1947349 Output 438 NoteConsider the first example. There are 10 stations and the first 4 of them are red. Arkady starts at station 3 with value t = 1, so just rides 1 station in clockwise direction and ends up on the station 4.In the second example the metro is same as in the first example, but Arkady starts at station 3 with value t = 5. It is a red station so he rides 5 stations in clockwise direction and leaves the train at station 8. It is a blue station, so he rides 4 stations in counter-clockwise direction and leaves at station 4. It is a red station, so he rides 3 stations in clockwise direction and leaves at station 7. It is a blue station, so he rides 2 stations in counter-clockwise direction and leaves at station 5. It is a blue station, so he rides 1 station in counter-clockwise direction and leaves at station 4. Now t = 0, so Arkady exits metro at the station 4.
10 4 3 1
4
2 seconds
1024 megabytes
['brute force', 'data structures', 'graphs', '*2900']
F. Write The Contesttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp, Arkady's friend, prepares to the programming competition and decides to write a contest. The contest consists of n problems and lasts for T minutes. Each of the problems is defined by two positive integers a_i and p_i — its difficulty and the score awarded by its solution.Polycarp's experience suggests that his skill level is defined with positive real value s, and initially s=1.0. To solve the i-th problem Polycarp needs a_i/s minutes.Polycarp loves to watch series, and before solving each of the problems he will definitely watch one episode. After Polycarp watches an episode, his skill decreases by 10\%, that is skill level s decreases to 0.9s. Each episode takes exactly 10 minutes to watch. When Polycarp decides to solve some problem, he firstly has to watch one episode, and only then he starts solving the problem without breaks for a_i/s minutes, where s is his current skill level. In calculation of a_i/s no rounding is performed, only division of integer value a_i by real value s happens.Also, Polycarp can train for some time. If he trains for t minutes, he increases his skill by C \cdot t, where C is some given positive real constant. Polycarp can train only before solving any problem (and before watching series). Duration of the training can be arbitrary real value.Polycarp is interested: what is the largest score he can get in the contest? It is allowed to solve problems in any order, while training is only allowed before solving the first problem.InputThe first line contains one integer tc (1 \le tc \le 20) — the number of test cases. Then tc test cases follow.The first line of each test contains one integer n (1 \le n \le 100) — the number of problems in the contest.The second line of the test contains two real values C, T (0 < C < 10, 0 \le T \le 2 \cdot 10^5), where C defines the efficiency of the training and T is the duration of the contest in minutes. Value C, T are given exactly with three digits after the decimal point.Each of the next n lines of the test contain characteristics of the corresponding problem: two integers a_i, p_i (1 \le a_i \le 10^4, 1 \le p_i \le 10) — the difficulty and the score of the problem.It is guaranteed that the value of T is such that changing it by the 0.001 in any direction will not change the test answer.Please note that in hacks you can only use tc = 1.OutputPrint tc integers — the maximum possible score in each test case.ExamplesInput241.000 31.00012 320 630 15 131.000 30.0001 1010 1020 8Output720NoteIn the first example, Polycarp can get score of 7 as follows: Firstly he trains for 4 minutes, increasing s to the value of 5; Then he decides to solve 4-th problem: he watches one episode in 10 minutes, his skill level decreases to s=5*0.9=4.5 and then he solves the problem in 5/s=5/4.5, which is roughly 1.111 minutes; Finally, he decides to solve 2-nd problem: he watches one episode in 10 minutes, his skill level decreases to s=4.5*0.9=4.05 and then he solves the problem in 20/s=20/4.05, which is roughly 4.938 minutes. This way, Polycarp uses roughly 4+10+1.111+10+4.938=30.049 minutes, to get score of 7 points. It is not possible to achieve larger score in 31 minutes.In the second example, Polycarp can get 20 points as follows: Firstly he trains for 4 minutes, increasing s to the value of 5; Then he decides to solve 1-st problem: he watches one episode in 10 minutes, his skill decreases to s=5*0.9=4.5 and then he solves problem in 1/s=1/4.5, which is roughly 0.222 minutes. Finally, he decides to solve 2-nd problem: he watches one episode in 10 minutes, his skill decreases to s=4.5*0.9=4.05 and then he solves the problem in 10/s=10/4.05, which is roughly 2.469 minutes. This way, Polycarp gets score of 20 in 4+10+0.222+10+2.469=26.691 minutes. It is not possible to achieve larger score in 30 minutes.
Input241.000 31.00012 320 630 15 131.000 30.0001 1010 1020 8
Output720
2 seconds
256 megabytes
['binary search', 'dp', 'math', '*2500']
E. Check Transcriptiontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal s towards a faraway galaxy. Recently they've received a response t which they believe to be a response from aliens! The scientists now want to check if the signal t is similar to s.The original signal s was a sequence of zeros and ones (everyone knows that binary code is the universe-wide language). The returned signal t, however, does not look as easy as s, but the scientists don't give up! They represented t as a sequence of English letters and say that t is similar to s if you can replace all zeros in s with some string r_0 and all ones in s with some other string r_1 and obtain t. The strings r_0 and r_1 must be different and non-empty.Please help Arkady's friend and find the number of possible replacements for zeros and ones (the number of pairs of strings r_0 and r_1) that transform s to t.InputThe first line contains a string s (2 \le |s| \le 10^5) consisting of zeros and ones — the original signal.The second line contains a string t (1 \le |t| \le 10^6) consisting of lowercase English letters only — the received signal.It is guaranteed, that the string s contains at least one '0' and at least one '1'.OutputPrint a single integer — the number of pairs of strings r_0 and r_1 that transform s to t.In case there are no such pairs, print 0.ExamplesInput 01 aaaaaa Output 4 Input 001 kokokokotlin Output 2 NoteIn the first example, the possible pairs (r_0, r_1) are as follows: "a", "aaaaa" "aa", "aaaa" "aaaa", "aa" "aaaaa", "a" The pair "aaa", "aaa" is not allowed, since r_0 and r_1 must be different.In the second example, the following pairs are possible: "ko", "kokotlin" "koko", "tlin"
01 aaaaaa
4
3 seconds
256 megabytes
['brute force', 'data structures', 'hashing', 'strings', '*2100']
D. Decorate Apple Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from 1 to n, the junction 1 is called the root.A subtree of a junction v is a set of junctions u such that the path from u to the root must pass through v. Note that v itself is included in a subtree of v.A leaf is such a junction that its subtree contains exactly one junction.The New Year is coming, so Arkady wants to decorate the tree. He will put a light bulb of some color on each leaf junction and then count the number happy junctions. A happy junction is such a junction t that all light bulbs in the subtree of t have different colors.Arkady is interested in the following question: for each k from 1 to n, what is the minimum number of different colors needed to make the number of happy junctions be greater than or equal to k?InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of junctions in the tree.The second line contains n - 1 integers p_2, p_3, ..., p_n (1 \le p_i < i), where p_i means there is a branch between junctions i and p_i. It is guaranteed that this set of branches forms a tree.OutputOutput n integers. The i-th of them should be the minimum number of colors needed to make the number of happy junctions be at least i.ExamplesInput 3 1 1 Output 1 1 2 Input 5 1 1 3 3 Output 1 1 1 2 3 NoteIn the first example for k = 1 and k = 2 we can use only one color: the junctions 2 and 3 will be happy. For k = 3 you have to put the bulbs of different colors to make all the junctions happy.In the second example for k = 4 you can, for example, put the bulbs of color 1 in junctions 2 and 4, and a bulb of color 2 into junction 5. The happy junctions are the ones with indices 2, 3, 4 and 5 then.
3 1 1
1 1 2
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'dp', 'graphs', 'greedy', 'sortings', 'trees', '*1600']
C. Pick Heroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDon't you tell me what you think that I can beIf you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each player has to pick a distinct hero in the beginning of the game.There are 2 teams each having n players and 2n heroes to distribute between the teams. The teams take turns picking heroes: at first, the first team chooses a hero in its team, after that the second team chooses a hero and so on. Note that after a hero is chosen it becomes unavailable to both teams.The friends estimate the power of the i-th of the heroes as p_i. Each team wants to maximize the total power of its heroes. However, there is one exception: there are m pairs of heroes that are especially strong against each other, so when any team chooses a hero from such a pair, the other team must choose the other one on its turn. Each hero is in at most one such pair.This is an interactive problem. You are to write a program that will optimally choose the heroes for one team, while the jury's program will play for the other team. Note that the jury's program may behave inefficiently, in this case you have to take the opportunity and still maximize the total power of your team. Formally, if you ever have chance to reach the total power of q or greater regardless of jury's program choices, you must get q or greater to pass a test.InputThe first line contains two integers n and m (1 \le n \le 10^3, 0 \le m \le n) — the number of players in one team and the number of special pairs of heroes.The second line contains 2n integers p_1, p_2, \ldots, p_{2n} (1 \le p_i \le 10^3) — the powers of the heroes.Each of the next m lines contains two integer a and b (1 \le a, b \le 2n, a \ne b) — a pair of heroes that are especially strong against each other. It is guaranteed that each hero appears at most once in this list.The next line contains a single integer t (1 \le t \le 2) — the team you are to play for. If t = 1, the first turn is yours, otherwise you have the second turn.HacksIn order to hack, use the format described above with one additional line. In this line output 2n distinct integers from 1 to 2n — the priority order for the jury's team. The jury's team will on each turn select the first possible hero from this list. Here possible means that it is not yet taken and does not contradict the rules about special pair of heroes.InteractionWhen it is your turn, print a single integer x (1 \le x \le 2n) — the index of the hero chosen by you. Note that you can't choose a hero previously chosen by either you of the other player, and you must follow the rules about special pairs of heroes.When it is the other team's turn, read a line containing a single integer x (1 \le x \le 2n) — the index of the hero chosen by the other team. It is guaranteed that this index is not chosen before and that the other team also follows the rules about special pairs of heroes.After the last turn you should terminate without printing anything.After printing your choice do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Jury's answer -1 instead of a valid choice means that you made an invalid turn. Exit immediately after receiving -1 and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.ExamplesInput 3 1 1 2 3 4 5 6 2 6 1 2 4 1 Output 6 5 3 Input 3 1 1 2 3 4 5 6 1 5 2 6 1 3 Output 5 4 2 NoteIn the first example the first turn is yours. In example, you choose 6, the other team is forced to reply with 2. You choose 5, the other team chooses 4. Finally, you choose 3 and the other team choose 1.In the second example you have the second turn. The other team chooses 6, you choose 5, forcing the other team to choose 1. Now you choose 4, the other team chooses 3 and you choose 2.
3 1 1 2 3 4 5 6 2 6 1 2 4 1
6 5 3
1 second
256 megabytes
['greedy', 'implementation', 'interactive', 'sortings', '*1700']
B. Divide Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady and his friends love playing checkers on an n \times n field. The rows and the columns of the field are enumerated from 1 to n.The friends have recently won a championship, so Arkady wants to please them with some candies. Remembering an old parable (but not its moral), Arkady wants to give to his friends one set of candies per each cell of the field: the set of candies for cell (i, j) will have exactly (i^2 + j^2) candies of unique type.There are m friends who deserve the present. How many of these n \times n sets of candies can be split equally into m parts without cutting a candy into pieces? Note that each set has to be split independently since the types of candies in different sets are different.InputThe only line contains two integers n and m (1 \le n \le 10^9, 1 \le m \le 1000) — the size of the field and the number of parts to split the sets into.OutputPrint a single integer — the number of sets that can be split equally.ExamplesInput 3 3 Output 1 Input 6 5 Output 13 Input 1000000000 1 Output 1000000000000000000 NoteIn the first example, only the set for cell (3, 3) can be split equally (3^2 + 3^2 = 18, which is divisible by m=3).In the second example, the sets for the following cells can be divided equally: (1, 2) and (2, 1), since 1^2 + 2^2 = 5, which is divisible by 5; (1, 3) and (3, 1); (2, 4) and (4, 2); (2, 6) and (6, 2); (3, 4) and (4, 3); (3, 6) and (6, 3); (5, 5). In the third example, sets in all cells can be divided equally, since m = 1.
3 3
1
1 second
256 megabytes
['math', 'number theory', '*1600']
A. Determine Linetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?InputThe first line contains a single integer n (2 \le n \le 100) — the number of stops Arkady saw.The next n lines describe the stops. Each of them starts with a single integer r (1 \le r \le 100) — the number of tram lines that stop there. r distinct integers follow, each one between 1 and 100, inclusive, — the line numbers. They can be in arbitrary order.It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.OutputPrint all tram lines that Arkady could be in, in arbitrary order.ExamplesInput 3 3 1 4 6 2 1 4 5 10 5 6 4 1 Output 1 4 Input 5 1 1 10 10 9 8 7 100 5 4 3 99 1 5 1 2 3 4 5 5 4 1 3 2 5 4 10 1 5 3 Output 1 NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines 1, 4, 6. The second time he saw a stop with lines 1, 4. The third time he saw a stop with lines 10, 5, 6, 4 and 1. He can be in a tram of one of two lines: 1 or 4.
3 3 1 4 6 2 1 4 5 10 5 6 4 1
1 4
1 second
256 megabytes
['implementation', '*800']
G. Jellyfish Nightmaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob has put on some weight recently. In order to lose weight a bit, Bob has decided to swim regularly in the pool. However, the day before he went to the pool for the first time he had a weird dream. In this dream Bob was swimming along one of the pool's lanes, but also there were some jellyfish swimming around him. It's worth mentioning that jellyfish have always been one of Bob's deepest childhood fears.Let us assume the following physical model for Bob's dream. The pool's lane is an area of the plane between lines x=0 and x=w. Bob is not allowed to swim outside of the lane, but he may touch its bounding lines if he wants. The jellyfish are very small, but in Bob's dream they are extremely swift. Each jellyfish has its area of activity around it. Those areas are circles of various radii, with the jellyfish sitting in their centers. The areas of activity of two jellyfish may overlap and one area of activity may even be fully contained within another one. Bob has a shape of a convex polygon. Unfortunately, Bob's excess weight has made him very clumsy, and as a result he can't rotate his body while swimming. So he swims in a parallel translation pattern. However at any given moment of time he can choose any direction of his movement. Whenever Bob swims into a jellyfish's activity area, it will immediately notice him and sting him very painfully. We assume that Bob has swum into the activity area if at some moment of time the intersection of his body with the jellyfish's activity area had a positive area (for example, if they only touch, the jellyfish does not notice Bob). Once a jellyfish stung Bob, it happily swims away and no longer poses any threat to Bob. Bob wants to swim the lane to its end and get stung the least possible number of times. He will start swimming on the line y=-h, and finish on the line y=h where h = 10^{10}.InputThe first line contains two integers n and w (3 \le n \le 200, 1 \le w \le 30000) — the number of vertices in the polygon that constitutes the Bob's shape and the width of the swimming pool lane.Each of the next n lines contains two integers x_i and y_i (0 \le x_i \le w, 0 \le y_i \le 30000) — the coordinates of corresponding vertex of the polygon. The vertices in the polygon are given in counterclockwise order. It is guaranteed that the given polygon is strictly convex.The next line contains an only integer m (0 \le m \le 200) — the number of the jellyfish in the pool.Each of the next m lines contains three integers (x_i, y_i, r_i (0 \le x_i \le w, 0 \le y_i \le 30000, 1 \le r_i \le 30000) — coordinates of the i-th jellyfish in the pool and the radius of her activity. It is guaranteed, that no two jellyfish are located in the same point.OutputOutput a single integer — the least possible number of jellyfish that will sting Bob.ExamplesInput4 40 02 02 20 231 1 13 5 11 9 1Output0Input4 60 03 03 30 331 0 14 2 23 6 1Output2Input4 20 01 01 10 121 1 11 3 1Output2NoteVisualization of the possible solutions to the first and the second sample test cases are below:
Input4 40 02 02 20 231 1 13 5 11 9 1
Output0
2 seconds
256 megabytes
['*3500']
F. Tree and XORtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a connected undirected graph without cycles (that is, a tree) of n vertices, moreover, there is a non-negative integer written on every edge.Consider all pairs of vertices (v, u) (that is, there are exactly n^2 such pairs) and for each pair calculate the bitwise exclusive or (xor) of all integers on edges of the simple path between v and u. If the path consists of one vertex only, then xor of all integers on edges of this path is equal to 0.Suppose we sorted the resulting n^2 values in non-decreasing order. You need to find the k-th of them.The definition of xor is as follows.Given two integers x and y, consider their binary representations (possibly with leading zeros): x_k \dots x_2 x_1 x_0 and y_k \dots y_2 y_1 y_0 (where k is any number so that all bits of x and y can be represented). Here, x_i is the i-th bit of the number x and y_i is the i-th bit of the number y. Let r = x \oplus y be the result of the xor operation of x and y. Then r is defined as r_k \dots r_2 r_1 r_0 where: r_i = \left\{ \begin{aligned} 1, ~ \text{if} ~ x_i \ne y_i \\ 0, ~ \text{if} ~ x_i = y_i \end{aligned} \right. InputThe first line contains two integers n and k (2 \le n \le 10^6, 1 \le k \le n^2) — the number of vertices in the tree and the number of path in the list with non-decreasing order.Each of the following n - 1 lines contains two integers p_i and w_i (1 \le p_i \le i, 0 \le w_i < 2^{62}) — the ancestor of vertex i + 1 and the weight of the corresponding edge.OutputPrint one integer: k-th smallest xor of a path in the tree.ExamplesInput2 11 3Output0Input3 61 21 3Output2NoteThe tree in the second sample test looks like this:For such a tree in total 9 paths exist: 1 \to 1 of value 0 2 \to 2 of value 0 3 \to 3 of value 0 2 \to 3 (goes through 1) of value 1 = 2 \oplus 3 3 \to 2 (goes through 1) of value 1 = 2 \oplus 3 1 \to 2 of value 2 2 \to 1 of value 2 1 \to 3 of value 3 3 \to 1 of value 3
Input2 11 3
Output0
4 seconds
256 megabytes
['strings', 'trees', '*2900']
E. Segments on the Linetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are a given a list of integers a_1, a_2, \ldots, a_n and s of its segments [l_j; r_j] (where 1 \le l_j \le r_j \le n).You need to select exactly m segments in such a way that the k-th order statistic of the multiset of a_i, where i is contained in at least one segment, is the smallest possible. If it's impossible to select a set of m segments in such a way that the multiset contains at least k elements, print -1.The k-th order statistic of a multiset is the value of the k-th element after sorting the multiset in non-descending order.InputThe first line contains four integers n, s, m and k (1 \le m \le s \le 1500, 1 \le k \le n \le 1500) — the size of the list, the number of segments, the number of segments to choose and the statistic number.The second line contains n integers a_i (1 \le a_i \le 10^9) — the values of the numbers in the list.Each of the next s lines contains two integers l_i and r_i (1 \le l_i \le r_i \le n) — the endpoints of the segments.It is possible that some segments coincide.OutputPrint exactly one integer — the smallest possible k-th order statistic, or -1 if it's impossible to choose segments in a way that the multiset contains at least k elements.ExamplesInput4 3 2 23 1 3 21 22 34 4Output2Input5 2 1 11 2 3 4 52 41 5Output1Input5 3 3 55 5 2 1 11 22 33 4Output-1NoteIn the first example, one possible solution is to choose the first and the third segment. Together they will cover three elements of the list (all, except for the third one). This way the 2-nd order statistic for the covered elements is 2.
Input4 3 2 23 1 3 21 22 34 4
Output2
2 seconds
256 megabytes
['binary search', 'dp', '*2500']
D. Refactoringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice has written a program and now tries to improve its readability. One of the ways to improve readability is to give sensible names to the variables, so now Alice wants to rename some variables in her program. In her IDE there is a command called "massive refactoring", which can replace names of many variable in just one run. To use it, Alice needs to select two strings s and t and after that for each variable the following algorithm is performed: if the variable's name contains s as a substring, then the first (and only first) occurrence of s is replaced with t. If the name doesn't contain s, then this variable's name stays the same.The list of variables is known and for each variable both the initial name and the name Alice wants this variable change to are known. Moreover, for each variable the lengths of the initial name and the target name are equal (otherwise the alignment of the code could become broken). You need to perform renaming of all variables in exactly one run of the massive refactoring command or determine that it is impossible.InputThe first line contains the only integer n (1 \le n \le 3000) — the number of variables in Alice's program.The following n lines contain the initial names of variables w_1, w_2, \ldots, w_n, one per line. After that, n more lines go, the i-th of them contains the target name w'_i for the i-th variable. It is guaranteed that 1 \le |w_i| = |w'_i| \le 3000.It is guaranteed that there is at least one variable having its target name different from the initial name. Both initial and target names consist of lowercase English letters only. For each variable the length of its initial name is equal to the length of its target name.OutputIf it is impossible to rename all variables with one call of "massive refactoring", print "NO" (quotes for clarity).Otherwise, on the first line print "YES" (quotes for clarity) and on the following lines print s and t (1 \le |s|, |t| \le 5000), which should be used for replacement. Strings s and t should consist only of lowercase letters of English alphabet.If there are multiple ways to perform a "massive refactoring", you can use any of them.ExamplesInput1topforcescodecoderOutputYEStopforcescodecoderInput3babcaccdcbdbcdccdcOutputYESadInput2youshalnotpassOutputNO
Input1topforcescodecoder
OutputYEStopforcescodecoder
1 second
256 megabytes
['greedy', 'implementation', 'strings', '*2400']
C. Lucky Daystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob and Alice are often participating in various programming competitions. Like many competitive programmers, Alice and Bob have good and bad days. They noticed, that their lucky and unlucky days are repeating with some period. For example, for Alice days [l_a; r_a] are lucky, then there are some unlucky days: [r_a + 1; l_a + t_a - 1], and then there are lucky days again: [l_a + t_a; r_a + t_a] and so on. In other words, the day is lucky for Alice if it lies in the segment [l_a + k t_a; r_a + k t_a] for some non-negative integer k.The Bob's lucky day have similar structure, however the parameters of his sequence are different: l_b, r_b, t_b. So a day is a lucky for Bob if it lies in a segment [l_b + k t_b; r_b + k t_b], for some non-negative integer k.Alice and Bob want to participate in team competitions together and so they want to find out what is the largest possible number of consecutive days, which are lucky for both Alice and Bob.InputThe first line contains three integers l_a, r_a, t_a (0 \le l_a \le r_a \le t_a - 1, 2 \le t_a \le 10^9) and describes Alice's lucky days.The second line contains three integers l_b, r_b, t_b (0 \le l_b \le r_b \le t_b - 1, 2 \le t_b \le 10^9) and describes Bob's lucky days.It is guaranteed that both Alice and Bob have some unlucky days.OutputPrint one integer: the maximum number of days in the row that are lucky for both Alice and Bob.ExamplesInput0 2 51 3 5Output2Input0 1 32 3 6Output1NoteThe graphs below correspond to the two sample tests and show the lucky and unlucky days of Alice and Bob as well as the possible solutions for these tests.
Input0 2 51 3 5
Output2
1 second
256 megabytes
['math', 'number theory', '*1900']
B. Alice and Hairdressertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most l centimeters after haircut, where l is her favorite number. Suppose, that the Alice's head is a straight line on which n hairlines grow. Let's number them from 1 to n. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length l, given that all hairlines on that segment had length strictly greater than l. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second.Alice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types: 0 — Alice asks how much time the haircut would take if she would go to the hairdresser now. 1 p d — p-th hairline grows by d centimeters. Note, that in the request 0 Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length.InputThe first line contains three integers n, m and l (1 \le n, m \le 100\,000, 1 \le l \le 10^9) — the number of hairlines, the number of requests and the favorite number of Alice.The second line contains n integers a_i (1 \le a_i \le 10^9) — the initial lengths of all hairlines of Alice.Each of the following m lines contains a request in the format described in the statement.The request description starts with an integer t_i. If t_i = 0, then you need to find the time the haircut would take. Otherwise, t_i = 1 and in this moment one hairline grows. The rest of the line than contains two more integers: p_i and d_i (1 \le p_i \le n, 1 \le d_i \le 10^9) — the number of the hairline and the length it grows by.OutputFor each query of type 0 print the time the haircut would take.ExampleInput4 7 31 2 3 401 2 301 1 301 3 10Output1221NoteConsider the first example: Initially lengths of hairlines are equal to 1, 2, 3, 4 and only 4-th hairline is longer l=3, and hairdresser can cut it in 1 second. Then Alice's second hairline grows, the lengths of hairlines are now equal to 1, 5, 3, 4 Now haircut takes two seonds: two swings are required: for the 4-th hairline and for the 2-nd. Then Alice's first hairline grows, the lengths of hairlines are now equal to 4, 5, 3, 4 The haircut still takes two seconds: with one swing hairdresser can cut 4-th hairline and with one more swing cut the segment from 1-st to 2-nd hairline. Then Alice's third hairline grows, the lengths of hairlines are now equal to 4, 5, 4, 4 Now haircut takes only one second: with one swing it is possible to cut the segment from 1-st hairline to the 4-th.
Input4 7 31 2 3 401 2 301 1 301 3 10
Output1221
1 second
256 megabytes
['dsu', 'implementation', '*1300']
A. Metrotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.In the city in which Alice and Bob live, the first metro line is being built. This metro line contains n stations numbered from 1 to n. Bob lives near the station with number 1, while Alice lives near the station with number s. The metro line has two tracks. Trains on the first track go from the station 1 to the station n and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.Some stations are not yet open at all and some are only partially open — for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.InputThe first line contains two integers n and s (2 \le s \le n \le 1000) — the number of stations in the metro and the number of the station where Alice's home is located. Bob lives at station 1.Next lines describe information about closed and open stations.The second line contains n integers a_1, a_2, \ldots, a_n (a_i = 0 or a_i = 1). If a_i = 1, then the i-th station is open on the first track (that is, in the direction of increasing station numbers). Otherwise the station is closed on the first track.The third line contains n integers b_1, b_2, \ldots, b_n (b_i = 0 or b_i = 1). If b_i = 1, then the i-th station is open on the second track (that is, in the direction of decreasing station numbers). Otherwise the station is closed on the second track.OutputPrint "YES" (quotes for clarity) if Bob will be able to commute to the Alice's home by metro and "NO" (quotes for clarity) otherwise.You can print each letter in any case (upper or lower).ExamplesInput5 31 1 1 1 11 1 1 1 1OutputYESInput5 41 0 0 0 10 1 1 1 1OutputYESInput5 20 1 1 1 11 1 1 1 1OutputNONoteIn the first example, all stations are opened, so Bob can simply travel to the station with number 3.In the second example, Bob should travel to the station 5 first, switch to the second track and travel to the station 4 then.In the third example, Bob simply can't enter the train going in the direction of Alice's home.
Input5 31 1 1 1 11 1 1 1 1
OutputYES
1 second
256 megabytes
['graphs', '*900']
H. Epic Convolutiontime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a_0, a_1, \ldots, a_{n - 1} and b_0, b_1, \ldots, b_{m-1}, and an integer c.Compute the following sum:\sum_{i=0}^{n-1} \sum_{j=0}^{m-1} a_i b_j c^{i^2\,j^3}Since it's value can be really large, print it modulo 490019.InputFirst line contains three integers n, m and c (1 \le n, m \le 100\,000, 1 \le c < 490019).Next line contains exactly n integers a_i and defines the array a (0 \le a_i \le 1000).Last line contains exactly m integers b_i and defines the array b (0 \le b_i \le 1000).OutputPrint one integer — value of the sum modulo 490019.ExamplesInput2 2 30 10 1Output3Input3 4 11 1 11 1 1 1Output12Input2 3 31 23 4 5Output65652NoteIn the first example, the only non-zero summand corresponds to i = 1, j = 1 and is equal to 1 \cdot 1 \cdot 3^1 = 3.In the second example, all summands are equal to 1.
Input2 2 30 10 1
Output3
4 seconds
256 megabytes
['chinese remainder theorem', 'fft', 'math', 'number theory', '*3500']
G. New Road Networktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe king of some country N decided to completely rebuild the road network. There are n people living in the country, they are enumerated from 1 to n. It is possible to construct a road between the house of any citizen a to the house of any other citizen b. There should not be more than one road between any pair of citizens. The road network must be connected, i.e. it should be possible to reach every citizen starting from anyone using roads. To save funds, it was decided to build exactly n-1 road, so the road network should be a tree.However, it is not that easy as it sounds, that's why the king addressed you for help. There are m secret communities in the country, each of them unites a non-empty subset of citizens. The king does not want to conflict with any of the communities, so he wants to build the network such that the houses of members of each society form a connected subtree in network. A set of vertices forms a connected subtree if and only if the graph remains connected when we delete all the other vertices and all edges but ones that connect the vertices from the set.Help the king to determine if it is possible to build the desired road network, and if it is, build it.InputEach test consists of one or more test cases.The first line contains a single integer t (1 \leq t \leq 2000) — the number of test cases.The following lines describe the test cases, each in the following format.The first line contains two integers n and m (1 \leq n, m \leq 2000) — the number of citizens and the number of secret communities. The next m lines contain the description of the communities. The i-th of these lines contains a string s_i of length n, consisting of characters '0' and '1'. The citizen with number j is a member of the i-th community if and only if s_{{i}{j}}=1. It is guaranteed that the string s_i contains at least one character '1' for each 1 \leq i \leq m.It is guaranteed that the sum of n for all test cases does not exceed 2000 and the sum of m for all test cases does not exceed 2000.OutputPrint the answer for all test cases in the order they are given in the input, each in the following format.If there is no way to build the desired road network, print "NO" (without quotes).Otherwise in the first line print "YES" (without quotes).In the next n-1 lines print the description of the road network: each line should contain two integers a and b (1 \leq a, b \leq n, a \neq b) that denote you build a road between houses of citizens a and b. The roads should form a connected tree, and each community should form a connected subtree.ExampleInput24 30011111001113 3011101110OutputYES1 32 33 4NONoteIn the first example you can build the following network: It is easy to see that for each community all the houses of its members form a connected subtree. For example, the 2-nd community unites the citizens 1, 2, 3. They form a connected subtree, because if we delete everything except the houses 1, 2, 3 and the roads between them, two roads will remain: between 1 and 3 and between 2 and 3, forming a connected graph.There is no network in the second example suitable for the king.
Input24 30011111001113 3011101110
OutputYES1 32 33 4NO
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', '*3300']
F. Electric Schemetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPasha is a young technician, nevertheless, he has already got a huge goal: to assemble a PC. The first task he has to become familiar with is to assemble an electric scheme.The scheme Pasha assembled yesterday consists of several wires. Each wire is a segment that connects two points on a plane with integer coordinates within the segment [1, 10^9].There are wires of two colors in the scheme: red wires: these wires are horizontal segments, i.e. if such a wire connects two points (x_1, y_1) and (x_2, y_2), then y_1 = y_2; blue wires: these wires are vertical segments, i.e. if such a wire connects two points (x_1, y_1) and (x_2, y_2), then x_1 = x_2. Note that if a wire connects a point to itself, it may be blue, and it can be red. Also, in Pasha's scheme no two wires of the same color intersect, i.e. there are no two wires of same color that have common points.The imperfection of Pasha's scheme was that the wires were not isolated, so in the points where two wires of different colors intersect, Pasha saw sparks. Pasha wrote down all the points where he saw sparks and obtained a set of n distinct points. After that he disassembled the scheme.Next morning Pasha looked at the set of n points where he had seen sparks and wondered how many wires had he used. Unfortunately, he does not remember that, so he wonders now what is the smallest number of wires he might have used in the scheme. Help him to determine this number and place the wires in such a way that in the resulting scheme the sparks occur in the same places.InputThe first line contains a single integer n (1 \leq n \leq 1000) — the number of points where Pasha saw sparks.Each of the next n lines contain two integers x and y (1 \leq x, y \leq 10^9) — the coordinates of a point with sparks. It is guaranteed that all points are distinct.OutputPrint the description of the scheme in the following format.In the first line print h — the number of horizontal red wires (0 \leq h). In each of the next h lines print 4 integers x_1, y_1, x_2, y_2 — the coordinates of two points (x_1, y_1) and (x_2, y_2) that are connected with this red wire. The segmenst must be horizontal, i.e. y_1 = y_2 must hold. Also, the constraint 1 \leq x_1, y_1, x_2, y_2 \leq 10^9 must hold.After that print v — the number of vertical blue wires (0 \leq v). In each of the next v lines print 4 integers x_1, y_1, x_2, y_2 — the coordinates of two points (x_1, y_1) and (x_2, y_2) that are connected with this blue wire. The segmenst must be vertical, i.e. x_1 = x_2 shomustuld hold. Also, the constraint 1 \leq x_1, y_1, x_2, y_2 \leq 10^9 must hold.No two segments of the same color should have common points. The set of points where sparks appear should be the same as given in the input.The number of segments (h + v) should be minimum possible. It's easy to see that the answer always exists. If there are multiple possible answers, print any.ExamplesInput42 22 44 24 4Output25 2 1 21 4 5 422 1 2 54 5 4 1Input42 13 22 31 2Output42 1 2 13 2 3 21 2 1 22 3 2 331 2 1 23 2 3 22 3 2 1NoteIn the first example Pasha could have assembled the following scheme: In this scheme there are 2 wires of each color: red ones connecting (5, 2) with (1, 2) and (1, 4) with (5, 4), blue ones connecting (2, 1) with (2, 5) and (4, 5) with (4, 1). Note that the sparks appear in the points that are described in the input, they are shown in yellow on the picture. For example, Pasha will see the spark in the point (2, 4) because the second red wire and the first blue wire intersect there. It is possible to show that we can't have less than 4 wires to produce a scheme with same sparks positions.
Input42 22 44 24 4
Output25 2 1 21 4 5 422 1 2 54 5 4 1
1 second
256 megabytes
['flows', 'graph matchings', '*2700']
E. Chips Puzzletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEgor came up with a new chips puzzle and suggests you to play.The puzzle has the form of a table with n rows and m columns, each cell can contain several black or white chips placed in a row. Thus, the state of the cell can be described by a string consisting of characters '0' (a white chip) and '1' (a black chip), possibly empty, and the whole puzzle can be described as a table, where each cell is a string of zeros and ones. The task is to get from one state of the puzzle some other state.To do this, you can use the following operation. select 2 different cells (x_1, y_1) and (x_2, y_2): the cells must be in the same row or in the same column of the table, and the string in the cell (x_1, y_1) must be non-empty; in one operation you can move the last character of the string at the cell (x_1, y_1) to the beginning of the string at the cell (x_2, y_2). Egor came up with two states of the table for you: the initial state and the final one. It is guaranteed that the number of zeros and ones in the tables are the same. Your goal is with several operations get the final state from the initial state. Of course, Egor does not want the number of operations to be very large. Let's denote as s the number of characters in each of the tables (which are the same). Then you should use no more than 4 \cdot s operations.InputThe first line contains two integers n and m (2 \leq n, m \leq 300) — the number of rows and columns of the table, respectively.The following n lines describe the initial state of the table in the following format: each line contains m non-empty strings consisting of zeros and ones. In the i-th of these lines, the j-th string is the string written at the cell (i, j). The rows are enumerated from 1 to n, the columns are numerated from 1 to m.The following n lines describe the final state of the table in the same format.Let's denote the total length of strings in the initial state as s. It is guaranteed that s \leq 100\, 000. It is also guaranteed that the numbers of zeros and ones coincide in the initial and final states.OutputOn the first line print q — the number of operations used. You should find such a solution that 0 \leq q \leq 4 \cdot s. In each the next q lines print 4 integers x_1, y_1, x_2, y_2. On the i-th line you should print the description of the i-th operation. These integers should satisfy the conditions 1 \leq x_1, x_2 \leq n, 1 \leq y_1, y_2 \leq m, (x_1, y_1) \neq (x_2, y_2), x_1 = x_2 or y_1 = y_2. The string in the cell (x_1, y_1) should be non-empty. This sequence of operations should transform the initial state of the table to the final one.We can show that a solution exists. If there is more than one solution, find any of them.ExamplesInput2 200 1001 1110 0110 01Output42 1 1 11 1 1 21 2 2 22 2 2 1Input2 30 0 0011 1 00 0 1011 0 0Output42 2 1 21 2 2 21 2 1 31 3 1 2NoteConsider the first example. The current state of the table:00 1001 11The first operation. The cell (2, 1) contains the string 01. Applying the operation to cells (2, 1) and (1, 1), we move the 1 from the end of the string 01 to the beginning of the string 00 and get the string 100. The current state of the table:100 100 11The second operation. The cell (1, 1) contains the string 100. Applying the operation to cells (1, 1) and (1, 2), we move the 0 from the end of the string 100 to the beginning of the string 10 and get the string 010. The current state of the table:10 0100 11The third operation. The cell (1, 2) contains the string 010. Applying the operation to cells (1, 2) and (2, 2), we move the 0 from the end of the string 010 to the beginning of the string 11 and get the string 011. The current state of the table:10 010 011The fourth operation. The cell (2, 2) contains the string 011. Applying the operation to cells (2, 2) and (2, 1), we move the 1 from the end of the string 011 to the beginning of the string 0 and get the string 10. The current state of the table:10 0110 01 It's easy to see that we have reached the final state of the table.
Input2 200 1001 1110 0110 01
Output42 1 1 11 1 1 21 2 2 22 2 2 1
1 second
256 megabytes
['constructive algorithms', 'implementation', 'math', '*2400']
D. Changing Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt a break Vanya came to the class and saw an array of n k-bit integers a_1, a_2, \ldots, a_n on the board. An integer x is called a k-bit integer if 0 \leq x \leq 2^k - 1. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array i (1 \leq i \leq n) and replace the number a_i with the number \overline{a_i}. We define \overline{x} for a k-bit integer x as the k-bit integer such that all its k bits differ from the corresponding bits of x. Vanya does not like the number 0. Therefore, he likes such segments [l, r] (1 \leq l \leq r \leq n) such that a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0, where \oplus denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.InputThe first line of the input contains two integers n and k (1 \leq n \leq 200\,000, 1 \leq k \leq 30).The next line contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 2^k - 1), separated by spaces — the array of k-bit integers.OutputPrint one integer — the maximum possible number of segments with XOR not equal to 0 that can be obtained by making several (possibly 0) operations described in the statement.ExamplesInput3 21 3 0Output5Input6 31 4 4 7 3 4Output19NoteIn the first example if Vasya does not perform any operations, he gets an array that has 5 segments that Vanya likes. If he performs the operation with i = 2, he gets an array [1, 0, 0], because \overline{3} = 0 when k = 2. This array has 3 segments that Vanya likes. Also, to get an array with 5 segments that Vanya likes, he can perform two operations with i = 3 and with i = 2. He then gets an array [1, 0, 3]. It can be proven that he can't obtain 6 or more segments that he likes.In the second example, to get 19 segments that Vanya likes, he can perform 4 operations with i = 3, i = 4, i = 5, i = 6 and get an array [1, 4, 3, 0, 4, 3].
Input3 21 3 0
Output5
1 second
256 megabytes
['greedy', 'implementation', '*1900']
C. Candies Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n children numbered from 1 to n in a kindergarten. Kindergarten teacher gave a_i (1 \leq a_i \leq n) candies to the i-th child. Children were seated in a row in order from 1 to n from left to right and started eating candies. While the i-th child was eating candies, he calculated two numbers l_i and r_i — the number of children seating to the left of him that got more candies than he and the number of children seating to the right of him that got more candies than he, respectively.Formally, l_i is the number of indices j (1 \leq j < i), such that a_i < a_j and r_i is the number of indices j (i < j \leq n), such that a_i < a_j.Each child told to the kindergarten teacher the numbers l_i and r_i that he calculated. Unfortunately, she forgot how many candies she has given to each child. So, she asks you for help: given the arrays l and r determine whether she could have given the candies to the children such that all children correctly calculated their values l_i and r_i, or some of them have definitely made a mistake. If it was possible, find any way how she could have done it.InputOn the first line there is a single integer n (1 \leq n \leq 1000) — the number of children in the kindergarten.On the next line there are n integers l_1, l_2, \ldots, l_n (0 \leq l_i \leq n), separated by spaces.On the next line, there are n integer numbers r_1, r_2, \ldots, r_n (0 \leq r_i \leq n), separated by spaces.OutputIf there is no way to distribute the candies to the children so that all of them calculated their numbers correctly, print «NO» (without quotes).Otherwise, print «YES» (without quotes) on the first line. On the next line, print n integers a_1, a_2, \ldots, a_n, separated by spaces — the numbers of candies the children 1, 2, \ldots, n received, respectively. Note that some of these numbers can be equal, but all numbers should satisfy the condition 1 \leq a_i \leq n. The number of children seating to the left of the i-th child that got more candies than he should be equal to l_i and the number of children seating to the right of the i-th child that got more candies than he should be equal to r_i. If there is more than one solution, find any of them.ExamplesInput50 0 1 1 22 0 1 0 0OutputYES1 3 1 2 1Input40 0 2 01 1 1 1OutputNOInput30 0 00 0 0OutputYES1 1 1NoteIn the first example, if the teacher distributed 1, 3, 1, 2, 1 candies to 1-st, 2-nd, 3-rd, 4-th, 5-th child, respectively, then all the values calculated by the children are correct. For example, the 5-th child was given 1 candy, to the left of him 2 children were given 1 candy, 1 child was given 2 candies and 1 child — 3 candies, so there are 2 children to the left of him that were given more candies than him.In the second example it is impossible to distribute the candies, because the 4-th child made a mistake in calculating the value of r_4, because there are no children to the right of him, so r_4 should be equal to 0.In the last example all children may have got the same number of candies, that's why all the numbers are 0. Note that each child should receive at least one candy.
Input50 0 1 1 22 0 1 0 0
OutputYES1 3 1 2 1
1 second
256 megabytes
['constructive algorithms', 'implementation', '*1500']
B. Appending Mextime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInitially Ildar has an empty array. He performs n steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset [0, 2, 3] is 1, while the mex of the multiset [1, 2, 1] is 0.More formally, on the step m, when Ildar already has an array a_1, a_2, \ldots, a_{m-1}, he chooses some subset of indices 1 \leq i_1 < i_2 < \ldots < i_k < m (possibly, empty), where 0 \leq k < m, and appends the mex(a_{i_1}, a_{i_2}, \ldots a_{i_k}) to the end of the array.After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array a_1, a_2, \ldots, a_n the minimum step t such that he has definitely made a mistake on at least one of the steps 1, 2, \ldots, t, or determine that he could have obtained this array without mistakes.InputThe first line contains a single integer n (1 \leq n \leq 100\,000) — the number of steps Ildar made.The second line contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 10^9) — the array Ildar obtained.OutputIf Ildar could have chosen the subsets on each step in such a way that the resulting array is a_1, a_2, \ldots, a_n, print -1.Otherwise print a single integer t — the smallest index of a step such that a mistake was made on at least one step among steps 1, 2, \ldots, t.ExamplesInput40 1 2 1Output-1Input31 0 1Output1Input40 1 2 239Output4NoteIn the first example it is possible that Ildar made no mistakes. Here is the process he could have followed. 1-st step. The initial array is empty. He can choose an empty subset and obtain 0, because the mex of an empty set is 0. Appending this value to the end he gets the array [0]. 2-nd step. The current array is [0]. He can choose a subset [0] and obtain an integer 1, because mex(0) = 1. Appending this value to the end he gets the array [0,1]. 3-rd step. The current array is [0,1]. He can choose a subset [0,1] and obtain an integer 2, because mex(0,1) = 2. Appending this value to the end he gets the array [0,1,2]. 4-th step. The current array is [0,1,2]. He can choose a subset [0] and obtain an integer 1, because mex(0) = 1. Appending this value to the end he gets the array [0,1,2,1]. Thus, he can get the array without mistakes, so the answer is -1.In the second example he has definitely made a mistake on the very first step, because he could not have obtained anything different from 0.In the third example he could have obtained [0, 1, 2] without mistakes, but 239 is definitely wrong.
Input40 1 2 1
Output-1
1 second
256 megabytes
['implementation', '*1000']
A. Elevator or Stairs?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor x, Egor on the floor y (not on the same floor with Masha).The house has a staircase and an elevator. If Masha uses the stairs, it takes t_1 seconds for her to walk between adjacent floors (in each direction). The elevator passes between adjacent floors (in each way) in t_2 seconds. The elevator moves with doors closed. The elevator spends t_3 seconds to open or close the doors. We can assume that time is not spent on any action except moving between adjacent floors and waiting for the doors to open or close. If Masha uses the elevator, it immediately goes directly to the desired floor.Coming out of the apartment on her floor, Masha noticed that the elevator is now on the floor z and has closed doors. Now she has to choose whether to use the stairs or use the elevator. If the time that Masha needs to get to the Egor's floor by the stairs is strictly less than the time it will take her using the elevator, then she will use the stairs, otherwise she will choose the elevator.Help Mary to understand whether to use the elevator or the stairs.InputThe only line contains six integers x, y, z, t_1, t_2, t_3 (1 \leq x, y, z, t_1, t_2, t_3 \leq 1000) — the floor Masha is at, the floor Masha wants to get to, the floor the elevator is located on, the time it takes Masha to pass between two floors by stairs, the time it takes the elevator to pass between two floors and the time it takes for the elevator to close or open the doors.It is guaranteed that x \ne y.OutputIf the time it will take to use the elevator is not greater than the time it will take to use the stairs, print «YES» (without quotes), otherwise print «NO> (without quotes).You can print each letter in any case (upper or lower).ExamplesInput5 1 4 4 2 1OutputYESInput1 6 6 2 1 1OutputNOInput4 1 7 4 1 2OutputYESNoteIn the first example:If Masha goes by the stairs, the time she spends is 4 \cdot 4 = 16, because she has to go 4 times between adjacent floors and each time she spends 4 seconds. If she chooses the elevator, she will have to wait 2 seconds while the elevator leaves the 4-th floor and goes to the 5-th. After that the doors will be opening for another 1 second. Then Masha will enter the elevator, and she will have to wait for 1 second for the doors closing. Next, the elevator will spend 4 \cdot 2 = 8 seconds going from the 5-th floor to the 1-st, because the elevator has to pass 4 times between adjacent floors and spends 2 seconds each time. And finally, it will take another 1 second before the doors are open and Masha can come out. Thus, all the way by elevator will take 2 + 1 + 1 + 8 + 1 = 13 seconds, which is less than 16 seconds, so Masha has to choose the elevator.In the second example, it is more profitable for Masha to use the stairs, because it will take 13 seconds to use the elevator, that is more than the 10 seconds it will takes to go by foot.In the third example, the time it takes to use the elevator is equal to the time it takes to walk up by the stairs, and is equal to 12 seconds. That means Masha will take the elevator.
Input5 1 4 4 2 1
OutputYES
1 second
256 megabytes
['implementation', '*800']
E. Euler tourtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEuler is a little, cute squirrel. When the autumn comes, he collects some reserves for winter. The interesting fact is that Euler likes to collect acorns in a specific way. A tree can be described as n acorns connected by n - 1 branches, such that there is exactly one way between each pair of acorns. Let's enumerate the acorns from 1 to n.The squirrel chooses one acorn (not necessary with number 1) as a start, and visits them in a way called "Euler tour" (see notes), collecting each acorn when he visits it for the last time.Today morning Kate was observing Euler. She took a sheet of paper and wrote down consecutive indices of acorns on his path. Unfortunately, during her way to home it started raining and some of numbers became illegible. Now the girl is very sad, because she has to present the observations to her teacher."Maybe if I guess the lacking numbers, I'll be able to do it!" she thought. Help her and restore any valid Euler tour of some tree or tell that she must have made a mistake.InputThe first line contains a single integer n (1 \leq n \leq 5 \cdot 10^5), denoting the number of acorns in the tree.The second line contains 2n - 1 integers a_1, a_2, \ldots, a_{2n-1} (0 \leq a_i \leq n) — the Euler tour of the tree that Kate wrote down. 0 means an illegible number, which has to be guessed.OutputIf there is no Euler tour satisfying the given description, output "no" in the first line.Otherwise, on the first line output "yes", and then in the second line print the Euler tour which satisfy the given description.Any valid Euler tour will be accepted, since the teacher doesn't know how exactly the initial tree looks.ExamplesInput21 0 0Outputyes1 2 1Input41 0 3 2 0 0 0Outputyes1 4 3 2 3 4 1Input50 1 2 3 4 1 0 0 0OutputnoNoteAn Euler tour of a tree with n acorns is a sequence of 2n - 1 indices of acorns. such that each acorn occurs at least once, the first and the last acorns are same and each two consecutive acorns are directly connected with a branch.
Input21 0 0
Outputyes1 2 1
2 seconds
256 megabytes
['constructive algorithms', 'trees', '*3500']
G. Distinctificationtime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSuppose you are given a sequence S of k pairs of integers (a_1, b_1), (a_2, b_2), \dots, (a_k, b_k).You can perform the following operations on it: Choose some position i and increase a_i by 1. That can be performed only if there exists at least one such position j that i \ne j and a_i = a_j. The cost of this operation is b_i; Choose some position i and decrease a_i by 1. That can be performed only if there exists at least one such position j that a_i = a_j + 1. The cost of this operation is -b_i. Each operation can be performed arbitrary number of times (possibly zero).Let f(S) be minimum possible x such that there exists a sequence of operations with total cost x, after which all a_i from S are pairwise distinct. Now for the task itself ...You are given a sequence P consisting of n pairs of integers (a_1, b_1), (a_2, b_2), \dots, (a_n, b_n). All b_i are pairwise distinct. Let P_i be the sequence consisting of the first i pairs of P. Your task is to calculate the values of f(P_1), f(P_2), \dots, f(P_n).InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of pairs in sequence P.Next n lines contain the elements of P: i-th of the next n lines contains two integers a_i and b_i (1 \le a_i \le 2 \cdot 10^5, 1 \le b_i \le n). It is guaranteed that all values of b_i are pairwise distinct.OutputPrint n integers — the i-th number should be equal to f(P_i).ExamplesInput51 13 35 54 22 4Output000-5-16Input42 42 32 21 1Output0371
Input51 13 35 54 22 4
Output000-5-16
6 seconds
512 megabytes
['data structures', 'dsu', 'greedy', '*2900']
F. The Shortest Statementtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a weighed undirected connected graph, consisting of n vertices and m edges.You should answer q queries, the i-th query is to find the shortest distance between vertices u_i and v_i.InputThe first line contains two integers n and m~(1 \le n, m \le 10^5, m - n \le 20) — the number of vertices and edges in the graph.Next m lines contain the edges: the i-th edge is a triple of integers v_i, u_i, d_i~(1 \le u_i, v_i \le n, 1 \le d_i \le 10^9, u_i \neq v_i). This triple means that there is an edge between vertices u_i and v_i of weight d_i. It is guaranteed that graph contains no self-loops and multiple edges.The next line contains a single integer q~(1 \le q \le 10^5) — the number of queries.Each of the next q lines contains two integers u_i and v_i~(1 \le u_i, v_i \le n) — descriptions of the queries.Pay attention to the restriction m - n ~ \le ~ 20.OutputPrint q lines.The i-th line should contain the answer to the i-th query — the shortest distance between vertices u_i and v_i.ExamplesInput3 31 2 32 3 13 1 531 21 32 3Output341Input8 131 2 42 3 63 4 14 5 125 6 36 7 87 8 71 4 11 8 32 6 92 7 14 6 36 8 281 51 72 32 83 73 46 87 8Output75677127
Input3 31 2 32 3 13 1 531 21 32 3
Output341
4 seconds
256 megabytes
['graphs', 'shortest paths', 'trees', '*2400']
E. Vasya and Big Integerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya owns three big integers — a, l, r. Let's define a partition of x such a sequence of strings s_1, s_2, \dots, s_k that s_1 + s_2 + \dots + s_k = x, where + is a concatanation of strings. s_i is the i-th element of the partition. For example, number 12345 has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of a beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number a, which has each of s_i satisfy the condition l \le s_i \le r. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number a such that they match all the given requirements. The result can be rather big, so print it modulo 998244353.InputThe first line contains a single integer a~(1 \le a \le 10^{1000000}).The second line contains a single integer l~(0 \le l \le 10^{1000000}).The third line contains a single integer r~(0 \le r \le 10^{1000000}).It is guaranteed that l \le r.It is also guaranteed that numbers a, l, r contain no leading zeros.OutputPrint a single integer — the amount of partitions of number a such that they match all the given requirements modulo 998244353.ExamplesInput135115Output2Input1000009Output1NoteIn the first test case, there are two good partitions 13+5 and 1+3+5.In the second test case, there is one good partition 1+0+0+0+0.
Input135115
Output2
1 second
256 megabytes
['binary search', 'data structures', 'dp', 'hashing', 'strings', '*2600']
D. Bicoloringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a grid, consisting of 2 rows and n columns. Each cell of this grid should be colored either black or white.Two cells are considered neighbours if they have a common border and share the same color. Two cells A and B belong to the same component if they are neighbours, or if there is a neighbour of A that belongs to the same component with B.Let's call some bicoloring beautiful if it has exactly k components.Count the number of beautiful bicolorings. The number can be big enough, so print the answer modulo 998244353.InputThe only line contains two integers n and k (1 \le n \le 1000, 1 \le k \le 2n) — the number of columns in a grid and the number of components required.OutputPrint a single integer — the number of beautiful bicolorings modulo 998244353.ExamplesInput3 4Output12Input4 1Output2Input1 2Output2NoteOne of possible bicolorings in sample 1:
Input3 4
Output12
2 seconds
256 megabytes
['bitmasks', 'dp', '*1700']
C. Vasya and Multisetstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a multiset s consisting of n integer numbers. Vasya calls some number x nice if it appears in the multiset exactly once. For example, multiset \{1, 1, 2, 3, 3, 3, 4\} contains nice numbers 2 and 4.Vasya wants to split multiset s into two multisets a and b (one of which may be empty) in such a way that the quantity of nice numbers in multiset a would be the same as the quantity of nice numbers in multiset b (the quantity of numbers to appear exactly once in multiset a and the quantity of numbers to appear exactly once in multiset b).InputThe first line contains a single integer n~(2 \le n \le 100).The second line contains n integers s_1, s_2, \dots s_n~(1 \le s_i \le 100) — the multiset s.OutputIf there exists no split of s to satisfy the given requirements, then print "NO" in the first line.Otherwise print "YES" in the first line.The second line should contain a string, consisting of n characters. i-th character should be equal to 'A' if the i-th element of multiset s goes to multiset a and 'B' if if the i-th element of multiset s goes to multiset b. Elements are numbered from 1 to n in the order they are given in the input.If there exist multiple solutions, then print any of them.ExamplesInput43 5 7 1OutputYESBABAInput33 5 1OutputNO
Input43 5 7 1
OutputYESBABA
1 second
256 megabytes
['brute force', 'dp', 'greedy', 'implementation', 'math', '*1500']
B. Relatively Prime Pairstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of all integers from l to r inclusive, l < r, (r - l + 1) \le 3 \cdot 10^5 and (r - l) is always odd.You want to split these numbers into exactly \frac{r - l + 1}{2} pairs in such a way that for each pair (i, j) the greatest common divisor of i and j is equal to 1. Each number should appear in exactly one of the pairs.Print the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them.InputThe only line contains two integers l and r (1 \le l < r \le 10^{18}, r - l + 1 \le 3 \cdot 10^5, (r - l) is odd).OutputIf any solution exists, print "YES" in the first line. Each of the next \frac{r - l + 1}{2} lines should contain some pair of integers. GCD of numbers in each pair should be equal to 1. All (r - l + 1) numbers should be pairwise distinct and should have values from l to r inclusive.If there are multiple solutions, print any of them.If there exists no solution, print "NO".ExampleInput1 8OutputYES2 74 13 86 5
Input1 8
OutputYES2 74 13 86 5
2 seconds
256 megabytes
['greedy', 'math', 'number theory', '*1000']
A. Vasya And Passwordtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya came up with a password to register for EatForces — a string s. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits.But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin letter and at least one lowercase Latin letter. For example, the passwords "abaCABA12", "Z7q" and "3R24m" are valid, and the passwords "qwerty", "qwerty12345" and "Password" are not. A substring of string s is a string x = s_l s_{l + 1} \dots s_{l + len - 1} (1 \le l \le |s|, 0 \le len \le |s| - l + 1). len is the length of the substring. Note that the empty string is also considered a substring of s, it has the length 0.Vasya's password, however, may come too weak for the security settings of EatForces. He likes his password, so he wants to replace some its substring with another string of the same length in order to satisfy the above conditions. This operation should be performed exactly once, and the chosen string should have the minimal possible length.Note that the length of s should not change after the replacement of the substring, and the string itself should contain only lowercase and uppercase Latin letters and digits.InputThe first line contains a single integer T (1 \le T \le 100) — the number of testcases.Each of the next T lines contains the initial password s~(3 \le |s| \le 100), consisting of lowercase and uppercase Latin letters and digits.Only T = 1 is allowed for hacks.OutputFor each testcase print a renewed password, which corresponds to given conditions. The length of the replaced substring is calculated as following: write down all the changed positions. If there are none, then the length is 0. Otherwise the length is the difference between the first and the last changed position plus one. For example, the length of the changed substring between the passwords "abcdef" \rightarrow "a7cdEf" is 4, because the changed positions are 2 and 5, thus (5 - 2) + 1 = 4.It is guaranteed that such a password always exists.If there are several suitable passwords — output any of them.ExampleInput2abcDCEhtQw27OutputabcD4EhtQw27NoteIn the first example Vasya's password lacks a digit, he replaces substring "C" with "4" and gets password "abcD4E". That means, he changed the substring of length 1.In the second example Vasya's password is ok from the beginning, and nothing has to be changed. That is the same as replacing the empty substring with another empty substring (length 0).
Input2abcDCEhtQw27
OutputabcD4EhtQw27
1 second
256 megabytes
['greedy', 'implementation', 'strings', '*1200']
B. Cover Pointstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere 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.InputFirst 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).OutputPrint the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.ExamplesInput31 11 22 1Output3Input41 11 22 12 2Output4NoteIllustration for the first example: Illustration for the second example:
Input31 11 22 1
Output3
1 second
256 megabytes
['geometry', 'math', '*900']
A. Little C Loves 3 Itime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle C loves number «3» very much. He loves all things about it.Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution.InputA single line containing one integer n (3 \leq n \leq 10^9) — the integer Little C has.OutputPrint 3 positive integers a,b,c in a single line, such that a+b+c=n and none of them is a multiple of 3.It can be proved that there is at least one solution. If there are multiple solutions, print any of them.ExamplesInput3Output1 1 1Input233Output77 77 79
Input3
Output1 1 1
1 second
256 megabytes
['math', '*800']
I. Say Hellotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo friends are travelling through Bubble galaxy. They say "Hello!" via signals to each other if their distance is smaller or equal than d_1 and it's the first time they speak to each other or at some point in time after their last talk their distance was greater than d_2. We need to calculate how many times friends said "Hello!" to each other. For N moments, you'll have an array of points for each friend representing their positions at that moment. A person can stay in the same position between two moments in time, but if a person made a move we assume this movement as movement with constant speed in constant direction.InputThe first line contains one integer number N (2 \leq N \leq 100\,000) representing number of moments in which we captured positions for two friends.The second line contains two integer numbers d_1 and d_2 \ (0 < d_1 < d_2 < 1000). The next N lines contains four integer numbers A_x,A_y,B_x,B_y (0 \leq A_x, A_y, B_x, B_y \leq 1000) representing coordinates of friends A and B in each captured moment.OutputOutput contains one integer number that represents how many times friends will say "Hello!" to each other.ExampleInput42 50 0 0 105 5 5 65 0 10 514 7 10 5Output2Note Explanation: Friends should send signals 2 times to each other, first time around point A2 and B2 and second time during A's travel from point A3 to A4 while B stays in point B3=B4.
Input42 50 0 0 105 5 5 65 0 10 514 7 10 5
Output2
2 seconds
256 megabytes
['geometry', '*2300']
F. Splitting moneytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most x satoshi (1 bitcoin = 10^8 satoshi). She can create new public address wallets for free and is willing to pay f fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal.InputFirst line contains number N (1 \leq N \leq 200\,000) representing total number of public addresses Alice has.Next line contains N integer numbers a_i (1 \leq a_i \leq 10^9) separated by a single space, representing how many satoshi Alice has in her public addresses.Last line contains two numbers x, f (1 \leq f < x \leq 10^9) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. OutputOutput one integer number representing total fee in satoshi Alice will need to pay to achieve her goal.ExampleInput313 7 66 2Output4NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4.
Input313 7 66 2
Output4
1 second
256 megabytes
['implementation', '*1400']
C. Space Formulatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFormula 1 officials decided to introduce new competition. Cars are replaced by space ships and number of points awarded can differ per race.Given the current ranking in the competition and points distribution for the next race, your task is to calculate the best possible ranking for a given astronaut after the next race. It's guaranteed that given astronaut will have unique number of points before the race.InputThe first line contains two integer numbers N (1 \leq N \leq 200000) representing number of F1 astronauts, and current position of astronaut D (1 \leq D \leq N) you want to calculate best ranking for (no other competitor will have the same number of points before the race).The second line contains N integer numbers S_k (0 \leq S_k \leq 10^8, k=1...N), separated by a single space, representing current ranking of astronauts. Points are sorted in non-increasing order.The third line contains N integer numbers P_k (0 \leq P_k \leq 10^8, k=1...N), separated by a single space, representing point awards for the next race. Points are sorted in non-increasing order, so winner of the race gets the maximum number of points.OutputOutput contains one integer number — the best possible ranking for astronaut after the race. If multiple astronauts have the same score after the race, they all share the best ranking.ExampleInput4 350 30 20 1015 10 7 3Output2NoteIf the third ranked astronaut wins the race, he will have 35 points. He cannot take the leading position, but he can overtake the second position if the second ranked astronaut finishes the race at the last position.
Input4 350 30 20 1015 10 7 3
Output2
1 second
256 megabytes
['greedy', '*1400']
J. Moonwalk challengetime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSince astronauts from BubbleCup XI mission finished their mission on the Moon and are big fans of famous singer, they decided to spend some fun time before returning to the Earth and hence created a so called "Moonwalk challenge" game.Teams of astronauts are given the map of craters on the Moon and direct bidirectional paths from some craters to others that are safe for "Moonwalking". Each of those direct paths is colored in one color and there is unique path between each two craters. Goal of the game is to find two craters such that given array of colors appears most times as continuous subarray on the path between those two craters (overlapping appearances should be counted).To help your favorite team win, you should make a program that, given the map, answers the queries of the following type: For two craters and array of colors answer how many times given array appears as continuous subarray on the path from the first crater to the second.Colors are represented as lowercase English alphabet letters.InputIn the first line, integer N (2 \leq N \leq 10^5) — number of craters on the Moon. Craters are numerated with numbers 1 to N.In next N-1 lines, three values u, v, L (1 \leq u, v \leq N, L \in \{a, ..., z\}) — denoting that there is a direct path with color L between craters u and v.Next line contains integer Q (1 \leq Q \leq 10^5) — number of queries.Next Q lines contain three values u, v (1 \leq u, v \leq N) and S (|S| \leq 100), where u and v are the two cratersfor which you should find how many times array of colors S (represented as string) appears on the path from u to v. OutputFor each query output one number that represents number of occurrences of array S on the path from u to v.ExampleInput62 3 g3 4 n5 3 o6 1 n1 2 d71 6 n6 4 dg6 4 n2 5 og1 2 d6 5 go2 3 gOutput1120111
Input62 3 g3 4 n5 3 o6 1 n1 2 d71 6 n6 4 dg6 4 n2 5 og1 2 d6 5 go2 3 g
Output1120111
6 seconds
256 megabytes
['data structures', 'strings', 'trees', '*2600']
I. Palindrome Pairstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).InputThe first line contains a positive integer N (1 \le N \le 100\,000), representing the length of the input array.Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than 1\,000\,000.OutputOutput one number, representing how many palindrome pairs there are in the array.ExamplesInput3aabbcdOutput1Input6aababcacdffeedaaaadeOutput6NoteThe first example: aa + bb \to abba. The second example: aab + abcac = aababcac \to aabccbaa aab + aa = aabaa abcac + aa = abcacaa \to aacbcaa dffe + ed = dffeed \to fdeedf dffe + aade = dffeaade \to adfaafde ed + aade = edaade \to aeddea
Input3aabbcd
Output1
2 seconds
256 megabytes
['hashing', 'strings', '*1600']
H. Self-explorationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing bored of exploring the Moon over and over again Wall-B decided to explore something he is made of — binary numbers. He took a binary number and decided to count how many times different substrings of length two appeared. He stored those values in c_{00}, c_{01}, c_{10} and c_{11}, representing how many times substrings 00, 01, 10 and 11 appear in the number respectively. For example: 10111100 \rightarrow c_{00} = 1, \ c_{01} = 1,\ c_{10} = 2,\ c_{11} = 3 10000 \rightarrow c_{00} = 3,\ c_{01} = 0,\ c_{10} = 1,\ c_{11} = 0 10101001 \rightarrow c_{00} = 1,\ c_{01} = 3,\ c_{10} = 3,\ c_{11} = 0 1 \rightarrow c_{00} = 0,\ c_{01} = 0,\ c_{10} = 0,\ c_{11} = 0Wall-B noticed that there can be multiple binary numbers satisfying the same c_{00}, c_{01}, c_{10} and c_{11} constraints. Because of that he wanted to count how many binary numbers satisfy the constraints c_{xy} given the interval [A, B]. Unfortunately, his processing power wasn't strong enough to handle large intervals he was curious about. Can you help him? Since this number can be large print it modulo 10^9 + 7.InputFirst two lines contain two positive binary numbers A and B (1 \leq A \leq B < 2^{100\,000}), representing the start and the end of the interval respectively. Binary numbers A and B have no leading zeroes.Next four lines contain decimal numbers c_{00}, c_{01}, c_{10} and c_{11} (0 \leq c_{00}, c_{01}, c_{10}, c_{11} \leq 100\,000) representing the count of two-digit substrings 00, 01, 10 and 11 respectively. OutputOutput one integer number representing how many binary numbers in the interval [A, B] satisfy the constraints mod 10^9 + 7.ExamplesInput1010010011Output1Input10100011234Output0NoteExample 1: The binary numbers in the interval [10,1001] are 10,11,100,101,110,111,1000,1001. Only number 110 satisfies the constraints: c_{00} = 0, c_{01} = 0, c_{10} = 1, c_{11} = 1.Example 2: No number in the interval satisfies the constraints
Input1010010011
Output1
1 second
256 megabytes
['math', '*2400']
G. AI robotstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the last mission, MDCS has successfully shipped N AI robots to Mars. Before they start exploring, system initialization is required so they are arranged in a line. Every robot can be described with three numbers: position (x_i), radius of sight (r_i) and IQ (q_i).Since they are intelligent robots, some of them will talk if they see each other. Radius of sight is inclusive, so robot can see other all robots in range [x_i - r_i, x_i + r_i]. But they don't walk to talk with anybody, but only with robots who have similar IQ. By similar IQ we mean that their absolute difference isn't more than K. Help us and calculate how many pairs of robots are going to talk with each other, so we can timely update their software and avoid any potential quarrel.InputThe first line contains two integers, numbers N (1 \leq N \leq 10^5) and K (0 \leq K \leq 20).Next N lines contain three numbers each x_i, r_i, q_i (0 \leq x_i,r_i,q_i \leq 10^9) — position, radius of sight and IQ of every robot respectively.OutputOutput contains only one number — solution to the problem.ExampleInput3 23 6 17 3 1010 5 8Output1NoteThe first robot can see the second, but not vice versa. The first robot can't even see the third. The second and the third robot can see each other and their IQs don't differ more than 2 so only one conversation will happen.
Input3 23 6 17 3 1010 5 8
Output1
2 seconds
256 megabytes
['data structures', '*2200']
F. Shady Ladytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAni and Borna are playing a short game on a two-variable polynomial. It's a special kind of a polynomial: the monomials are fixed, but all of its coefficients are fill-in-the-blanks dashes, e.g. \_ xy + \_ x^4 y^7 + \_ x^8 y^3 + \ldots Borna will fill in the blanks with positive integers. He wants the polynomial to be bounded from below, i.e. his goal is to make sure there exists a real number M such that the value of the polynomial at any point is greater than M. Ani is mischievous, and wants the polynomial to be unbounded. Along with stealing Borna's heart, she can also steal parts of polynomials. Ani is only a petty kind of thief, though: she can only steal at most one monomial from the polynomial before Borna fills in the blanks. If Ani and Borna play their only moves optimally, who wins?InputThe first line contains a positive integer N (2 \leq N \leq 200\, 000), denoting the number of the terms in the starting special polynomial.Each of the following N lines contains a description of a monomial: the k-th line contains two **space**-separated integers a_k and b_k (0 \leq a_k, b_k \leq 10^9) which mean the starting polynomial has the term \_ x^{a_k} y^{b_k}. It is guaranteed that for k \neq l, either a_k \neq a_l or b_k \neq b_l.OutputIf Borna can always choose the coefficients such that the resulting polynomial is bounded from below, regardless of what monomial Ani steals, output "Borna". Else, output "Ani". You shouldn't output the quotation marks.ExamplesInput31 12 00 2OutputAniInput40 00 10 20 8OutputBornaNoteIn the first sample, the initial polynomial is \_xy+ \_x^2 + \_y^2. If Ani steals the \_y^2 term, Borna is left with \_xy+\_x^2. Whatever positive integers are written on the blanks, y \rightarrow -\infty and x := 1 makes the whole expression go to negative infinity.In the second sample, the initial polynomial is \_1 + \_x + \_x^2 + \_x^8. One can check that no matter what term Ani steals, Borna can always win.
Input31 12 00 2
OutputAni
1 second
256 megabytes
['geometry', 'math', '*3400']
E. Ancient civilizationstime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the surface of a newly discovered planet, which we model by a plane, explorers found remains of two different civilizations in various locations. They would like to learn more about those civilizations and to explore the area they need to build roads between some of locations. But as always, there are some restrictions: Every two locations of the same civilization are connected by a unique path of roads No two locations from different civilizations may have road between them (explorers don't want to accidentally mix civilizations they are currently exploring) Roads must be straight line segments Since intersections are expensive to build, they don't want any two roads to intersect (that is, only common point for any two roads may be at some of locations) Obviously all locations are different points in the plane, but explorers found out one more interesting information that may help you – no three locations lie on the same line!Help explorers and find a solution for their problem, or report it is impossible.InputIn the first line, integer n (1 \leq n \leq 10^3) - the number of locations discovered.In next n lines, three integers x, y, c (0 \leq x, y \leq 10^4, c \in \{0, 1\}) - coordinates of the location and number of civilization it belongs to.OutputIn first line print number of roads that should be built.In the following lines print all pairs of locations (their 0-based indices) that should be connected with a road.If it is not possible to build roads such that all restrictions are met, print "Impossible". You should not print the quotation marks.ExampleInput50 0 11 0 00 1 01 1 13 2 0Output31 44 23 0
Input50 0 11 0 00 1 01 1 13 2 0
Output31 44 23 0
0.5 seconds
256 megabytes
['constructive algorithms', 'geometry', '*3200']
D. Interstellar battletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the intergalactic empire Bubbledom there are N planets, of which some pairs are directly connected by two-way wormholes. There are N-1 wormholes. The wormholes are of extreme religious importance in Bubbledom, a set of planets in Bubbledom consider themselves one intergalactic kingdom if and only if any two planets in the set can reach each other by traversing the wormholes. You are given that Bubbledom is one kingdom. In other words, the network of planets and wormholes is a tree.However, Bubbledom is facing a powerful enemy also possessing teleportation technology. The enemy attacks every night, and the government of Bubbledom retakes all the planets during the day. In a single attack, the enemy attacks every planet of Bubbledom at once, but some planets are more resilient than others. Planets are number 0,1,…,N-1 and the planet i will fall with probability p_i. Before every night (including the very first one), the government reinforces or weakens the defenses of a single planet.The government of Bubbledom is interested in the following question: what is the expected number of intergalactic kingdoms Bubbledom will be split into, after a single enemy attack (before they get a chance to rebuild)? In other words, you need to print the expected number of connected components after every attack.InputThe first line contains one integer number N (1 \le N \le 10^5) denoting the number of planets in Bubbledom (numbered from 0 to N-1). The next line contains N different real numbers in the interval [0,1], specified with 2 digits after the decimal point, denoting the probabilities that the corresponding planet will fall.The next N-1 lines contain all the wormholes in Bubbledom, where a wormhole is specified by the two planets it connects.The next line contains a positive integer Q (1 \le Q \le 10^5), denoting the number of enemy attacks.The next Q lines each contain a non-negative integer and a real number from interval [0,1], denoting the planet the government of Bubbledom decided to reinforce or weaken, along with the new probability that the planet will fall.OutputOutput contains Q numbers, each of which represents the expected number of kingdoms that are left after each enemy attack. Your answers will be considered correct if their absolute or relative error does not exceed 10^{-4}. ExampleInput50.50 0.29 0.49 0.95 0.832 30 33 42 134 0.661 0.690 0.36Output1.680401.484401.61740
Input50.50 0.29 0.49 0.95 0.832 30 33 42 134 0.661 0.690 0.36
Output1.680401.484401.61740
1 second
256 megabytes
['math', 'probabilities', 'trees', '*2200']