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
F. One Node is Gonetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an integer n. Let's define following tree generation as McDic's generation: Make a complete and full binary tree of 2^{n} - 1 vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes. Select a non-root vertex v from that binary tree. Remove v from tree and make new edges between v's parent and v's direct children. If v has no children, then no new edges will be made. You have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree.InputThe first line contains integer n (2 \le n \le 17).The i-th of the next 2^{n} - 3 lines contains two integers a_{i} and b_{i} (1 \le a_{i} \lt b_{i} \le 2^{n} - 2) — meaning there is an edge between a_{i} and b_{i}. It is guaranteed that the given edges form a tree.OutputPrint two lines.In the first line, print a single integer — the number of answers. If given tree cannot be made by McDic's generation, then print 0.In the second line, print all possible answers in ascending order, separated by spaces. If the given tree cannot be made by McDic's generation, then don't print anything.ExamplesInput 4 1 2 1 3 2 4 2 5 3 6 3 13 3 14 4 7 4 8 5 9 5 10 6 11 6 12 Output 1 3 Input 2 1 2 Output 2 1 2 Input 3 1 2 2 3 3 4 4 5 5 6 Output 0 NoteIn the first example, 3 is the only possible answer. In the second example, there are 2 possible answers. In the third example, the tree can't be generated by McDic's generation.
4 1 2 1 3 2 4 2 5 3 6 3 13 3 14 4 7 4 8 5 9 5 10 6 11 6 12
1 3
1 second
256 megabytes
['constructive algorithms', 'implementation', 'trees', '*2500']
E. Another Filling the Gridtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n \times n square grid and an integer k. Put an integer in each cell while satisfying the conditions below. All numbers in the grid should be between 1 and k inclusive. Minimum number of the i-th row is 1 (1 \le i \le n). Minimum number of the j-th column is 1 (1 \le j \le n). Find the number of ways to put integers in the grid. Since the answer can be very large, find the answer modulo (10^{9} + 7). These are the examples of valid and invalid grid when n=k=2. InputThe only line contains two integers n and k (1 \le n \le 250, 1 \le k \le 10^{9}).OutputPrint the answer modulo (10^{9} + 7).ExamplesInput 2 2 Output 7 Input 123 456789 Output 689974806 NoteIn the first example, following 7 cases are possible. In the second example, make sure you print the answer modulo (10^{9} + 7).
2 2
7
1 second
256 megabytes
['combinatorics', 'dp', 'math', '*2300']
D. Complete Tripartitetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.Let's make a definition.Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied: There are no edges with both endpoints in vertex set v_1. There are no edges with both endpoints in vertex set v_2. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y. Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below; All vertex sets should not be empty. Each vertex should be assigned to only one vertex set. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true. Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.InputThe first line contains two integers n and m (3 \le n \le 10^{5}, 0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})) — the number of vertices and edges in the graph.The i-th of the next m lines contains two integers a_{i} and b_{i} (1 \le a_{i} \lt b_{i} \le n) — it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.OutputIf the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.If there are multiple answers, print any.ExamplesInput 6 11 1 2 1 3 1 4 1 5 1 6 2 4 2 5 2 6 3 4 3 5 3 6 Output 1 2 2 3 3 3 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 NoteIn the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well. In the second example, it's impossible to make such vertex sets.
6 11 1 2 1 3 1 4 1 5 1 6 2 4 2 5 2 6 3 4 3 5 3 6
1 2 2 3 3 3
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'graphs', 'hashing', 'implementation', '*1900']
C. Primes and Multiplicationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's introduce some definitions that will be needed later.Let prime(x) be the set of prime divisors of x. For example, prime(140) = \{ 2, 5, 7 \}, prime(169) = \{ 13 \}.Let g(x, p) be the maximum possible integer p^k where k is an integer such that x is divisible by p^k. For example: g(45, 3) = 9 (45 is divisible by 3^2=9 but not divisible by 3^3=27), g(63, 7) = 7 (63 is divisible by 7^1=7 but not divisible by 7^2=49). Let f(x, y) be the product of g(y, p) for all p in prime(x). For example: f(30, 70) = g(70, 2) \cdot g(70, 3) \cdot g(70, 5) = 2^1 \cdot 3^0 \cdot 5^1 = 10, f(525, 63) = g(63, 3) \cdot g(63, 5) \cdot g(63, 7) = 3^2 \cdot 5^0 \cdot 7^1 = 63. You have integers x and n. Calculate f(x, 1) \cdot f(x, 2) \cdot \ldots \cdot f(x, n) \bmod{(10^{9} + 7)}.InputThe only line contains integers x and n (2 \le x \le 10^{9}, 1 \le n \le 10^{18}) — the numbers used in formula.OutputPrint the answer.ExamplesInput 10 2 Output 2 Input 20190929 1605 Output 363165664 Input 947 987654321987654321 Output 593574252 NoteIn the first example, f(10, 1) = g(1, 2) \cdot g(1, 5) = 1, f(10, 2) = g(2, 2) \cdot g(2, 5) = 2.In the second example, actual value of formula is approximately 1.597 \cdot 10^{171}. Make sure you print the answer modulo (10^{9} + 7).In the third example, be careful about overflow issue.
10 2
2
1 second
256 megabytes
['math', 'number theory', '*1700']
B. Filling the Gridtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose there is a h \times w grid consisting of empty or full cells. Let's make some definitions: r_{i} is the number of consecutive full cells connected to the left side in the i-th row (1 \le i \le h). In particular, r_i=0 if the leftmost cell of the i-th row is empty. c_{j} is the number of consecutive full cells connected to the top end in the j-th column (1 \le j \le w). In particular, c_j=0 if the topmost cell of the j-th column is empty. In other words, the i-th row starts exactly with r_i full cells. Similarly, the j-th column starts exactly with c_j full cells. These are the r and c values of some 3 \times 4 grid. Black cells are full and white cells are empty. You have values of r and c. Initially, all cells are empty. Find the number of ways to fill grid cells to satisfy values of r and c. Since the answer can be very large, find the answer modulo 1000000007\,(10^{9} + 7). In other words, find the remainder after division of the answer by 1000000007\,(10^{9} + 7).InputThe first line contains two integers h and w (1 \le h, w \le 10^{3}) — the height and width of the grid.The second line contains h integers r_{1}, r_{2}, \ldots, r_{h} (0 \le r_{i} \le w) — the values of r.The third line contains w integers c_{1}, c_{2}, \ldots, c_{w} (0 \le c_{j} \le h) — the values of c.OutputPrint the answer modulo 1000000007\,(10^{9} + 7).ExamplesInput 3 4 0 3 1 0 2 3 0 Output 2 Input 1 1 0 1 Output 0 Input 19 16 16 16 16 16 15 15 0 5 0 4 9 9 1 4 4 0 8 16 12 6 12 19 15 8 6 19 19 14 6 9 16 10 11 15 4 Output 797922655 NoteIn the first example, this is the other possible case. In the second example, it's impossible to make a grid to satisfy such r, c values.In the third example, make sure to print answer modulo (10^9 + 7).
3 4 0 3 1 0 2 3 0
2
1 second
256 megabytes
['implementation', 'math', '*1400']
A. Distinct Digitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have two integers l and r. Find an integer x which satisfies the conditions below: l \le x \le r. All digits of x are different. If there are multiple answers, print any of them.InputThe first line contains two integers l and r (1 \le l \le r \le 10^{5}).OutputIf an answer exists, print any of them. Otherwise, print -1.ExamplesInput 121 130 Output 123 Input 98766 100000 Output -1 NoteIn the first example, 123 is one of the possible answers. However, 121 can't be the answer, because there are multiple 1s on different digits.In the second example, there is no valid answer.
121 130
123
1 second
256 megabytes
['brute force', 'implementation', '*800']
G. Not Sametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer array a_1, a_2, \dots, a_n, where a_i represents the number of blocks at the i-th position. It is guaranteed that 1 \le a_i \le n. In one operation you can choose a subset of indices of the given array and remove one block in each of these indices. You can't remove a block from a position without blocks.All subsets that you choose should be different (unique).You need to remove all blocks in the array using at most n+1 operations. It can be proved that the answer always exists.InputThe first line contains a single integer n (1 \le n \le 10^3) — length of the given array.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — numbers of blocks at positions 1, 2, \dots, n.OutputIn the first line print an integer op (0 \le op \le n+1).In each of the following op lines, print a binary string s of length n. If s_i='0', it means that the position i is not in the chosen subset. Otherwise, s_i should be equal to '1' and the position i is in the chosen subset.All binary strings should be distinct (unique) and a_i should be equal to the sum of s_i among all chosen binary strings.If there are multiple possible answers, you can print any.It can be proved that an answer always exists.ExamplesInput 5 5 5 5 5 5 Output 6 11111 01111 10111 11011 11101 11110 Input 5 5 1 1 1 1 Output 5 11000 10000 10100 10010 10001 Input 5 4 1 5 3 4 Output 5 11111 10111 10101 00111 10100 NoteIn the first example, the number of blocks decrease like that:\lbrace 5,5,5,5,5 \rbrace \to \lbrace 4,4,4,4,4 \rbrace \to \lbrace 4,3,3,3,3 \rbrace \to \lbrace 3,3,2,2,2 \rbrace \to \lbrace 2,2,2,1,1 \rbrace \to \lbrace 1,1,1,1,0 \rbrace \to \lbrace 0,0,0,0,0 \rbrace. And we can note that each operation differs from others.
5 5 5 5 5 5
6 11111 01111 10111 11011 11101 11110
2 seconds
256 megabytes
['constructive algorithms', '*2600']
F2. Wrong Answer on test 233 (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour program fails again. This time it gets "Wrong answer on test 233".This is the harder version of the problem. In this version, 1 \le n \le 2\cdot10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.The problem is to finish n one-choice-questions. Each of the questions contains k options, and only one of them is correct. The answer to the i-th question is h_{i}, and if your answer of the question i is h_{i}, you earn 1 point, otherwise, you earn 0 points for this question. The values h_1, h_2, \dots, h_n are known to you in this problem.However, you have a mistake in your program. It moves the answer clockwise! Consider all the n answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.Formally, the mistake moves the answer for the question i to the question i \bmod n + 1. So it moves the answer for the question 1 to question 2, the answer for the question 2 to the question 3, ..., the answer for the question n to the question 1.We call all the n answers together an answer suit. There are k^n possible answer suits in total.You're wondering, how many answer suits satisfy the following condition: after moving clockwise by 1, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo 998\,244\,353.For example, if n = 5, and your answer suit is a=[1,2,3,4,5], it will submitted as a'=[5,1,2,3,4] because of a mistake. If the correct answer suit is h=[5,2,2,3,4], the answer suit a earns 1 point and the answer suite a' earns 4 points. Since 4 > 1, the answer suit a=[1,2,3,4,5] should be counted.InputThe first line contains two integers n, k (1 \le n \le 2\cdot10^5, 1 \le k \le 10^9) — the number of questions and the number of possible answers to each question.The following line contains n integers h_1, h_2, \dots, h_n, (1 \le h_{i} \le k) — answers to the questions.OutputOutput one integer: the number of answers suits satisfying the given condition, modulo 998\,244\,353.ExamplesInput 3 3 1 3 1 Output 9 Input 5 5 1 1 4 2 2 Output 1000 Input 6 2 1 1 2 2 1 1 Output 16 NoteFor the first example, valid answer suits are [2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [3,2,3].
3 3 1 3 1
9
1 second
256 megabytes
['combinatorics', 'math', '*2400']
F1. Wrong Answer on test 233 (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour program fails again. This time it gets "Wrong answer on test 233".This is the easier version of the problem. In this version 1 \le n \le 2000. You can hack this problem only if you solve and lock both problems.The problem is about a test containing n one-choice-questions. Each of the questions contains k options, and only one of them is correct. The answer to the i-th question is h_{i}, and if your answer of the question i is h_{i}, you earn 1 point, otherwise, you earn 0 points for this question. The values h_1, h_2, \dots, h_n are known to you in this problem.However, you have a mistake in your program. It moves the answer clockwise! Consider all the n answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.Formally, the mistake moves the answer for the question i to the question i \bmod n + 1. So it moves the answer for the question 1 to question 2, the answer for the question 2 to the question 3, ..., the answer for the question n to the question 1.We call all the n answers together an answer suit. There are k^n possible answer suits in total.You're wondering, how many answer suits satisfy the following condition: after moving clockwise by 1, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo 998\,244\,353.For example, if n = 5, and your answer suit is a=[1,2,3,4,5], it will submitted as a'=[5,1,2,3,4] because of a mistake. If the correct answer suit is h=[5,2,2,3,4], the answer suit a earns 1 point and the answer suite a' earns 4 points. Since 4 > 1, the answer suit a=[1,2,3,4,5] should be counted.InputThe first line contains two integers n, k (1 \le n \le 2000, 1 \le k \le 10^9) — the number of questions and the number of possible answers to each question.The following line contains n integers h_1, h_2, \dots, h_n, (1 \le h_{i} \le k) — answers to the questions.OutputOutput one integer: the number of answers suits satisfying the given condition, modulo 998\,244\,353.ExamplesInput 3 3 1 3 1 Output 9 Input 5 5 1 1 4 2 2 Output 1000 NoteFor the first example, valid answer suits are [2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [3,2,3].
3 3 1 3 1
9
1 second
256 megabytes
['dp', '*2200']
E. Arson In Berland Foresttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a n \times m rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as 0) some trees were set on fire. At the beginning of minute 0, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of 8 neighboring trees. At the beginning of minute T, the fire was extinguished.The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of T (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of T (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.Note that you'd like to maximize value T but the set of trees can be arbitrary.InputThe first line contains two integer n and m (1 \le n, m \le 10^6, 1 \le n \cdot m \le 10^6) — the sizes of the map.Next n lines contain the map. The i-th line corresponds to the i-th row of the map and contains m-character string. The j-th character of the i-th string is "X" if the corresponding tree is burnt and "." otherwise.It's guaranteed that the map contains at least one "X".OutputIn the first line print the single integer T — the maximum time the Forest was on fire. In the next n lines print the certificate: the map (n \times m rectangle) where the trees that were set on fire are marked as "X" and all other trees are marked as ".".ExamplesInput 3 6 XXXXXX XXXXXX XXXXXX Output 1 ...... .X.XX. ...... Input 10 10 .XXXXXX... .XXXXXX... .XXXXXX... .XXXXXX... .XXXXXXXX. ...XXXXXX. ...XXXXXX. ...XXXXXX. ...XXXXXX. .......... Output 2 .......... .......... ...XX..... .......... .......... .......... .....XX... .......... .......... .......... Input 4 5 X.... ..XXX ..XXX ..XXX Output 0 X.... ..XXX ..XXX ..XXX
3 6 XXXXXX XXXXXX XXXXXX
1 ...... .X.XX. ......
2 seconds
512 megabytes
['binary search', 'graphs', 'graphs', 'shortest paths', '*2200']
D2. Optimal Subsequences (Hard Version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the harder version of the problem. In this version, 1 \le n, m \le 2\cdot10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers a=[a_1,a_2,\dots,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 \le k \le n) is given, then the subsequence is called optimal if: it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, \dots, b_k] is lexicographically smaller than the sequence c=[c_1, c_2, \dots, c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 \le t \le k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: [10, 20, 20] lexicographically less than [10, 21, 1], [7, 99, 99] is lexicographically less than [10, 21, 1], [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,\dots,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 \le k \le n, 1 \le pos_j \le k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.InputThe first line contains an integer n (1 \le n \le 2\cdot10^5) — the length of the sequence a.The second line contains elements of the sequence a: integer numbers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).The third line contains an integer m (1 \le m \le 2\cdot10^5) — the number of requests.The following m lines contain pairs of integers k_j and pos_j (1 \le k \le n, 1 \le pos_j \le k_j) — the requests.OutputPrint m integers r_1, r_2, \dots, r_m (1 \le r_j \le 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j.ExamplesInput 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 NoteIn the first example, for a=[10,20,10] the optimal subsequences are: for k=1: [20], for k=2: [10,20], for k=3: [10,20,10].
3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3
20 10 20 10 20 10
3 seconds
256 megabytes
['data structures', 'greedy', '*1800']
D1. Optimal Subsequences (Easy Version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easier version of the problem. In this version 1 \le n, m \le 100. You can hack this problem only if you solve and lock both problems.You are given a sequence of integers a=[a_1,a_2,\dots,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 \le k \le n) is given, then the subsequence is called optimal if: it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, \dots, b_k] is lexicographically smaller than the sequence c=[c_1, c_2, \dots, c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 \le t \le k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: [10, 20, 20] lexicographically less than [10, 21, 1], [7, 99, 99] is lexicographically less than [10, 21, 1], [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,\dots,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 \le k \le n, 1 \le pos_j \le k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.InputThe first line contains an integer n (1 \le n \le 100) — the length of the sequence a.The second line contains elements of the sequence a: integer numbers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).The third line contains an integer m (1 \le m \le 100) — the number of requests.The following m lines contain pairs of integers k_j and pos_j (1 \le k \le n, 1 \le pos_j \le k_j) — the requests.OutputPrint m integers r_1, r_2, \dots, r_m (1 \le r_j \le 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j.ExamplesInput 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 NoteIn the first example, for a=[10,20,10] the optimal subsequences are: for k=1: [20], for k=2: [10,20], for k=3: [10,20,10].
3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3
20 10 20 10 20 10
3 seconds
256 megabytes
['data structures', 'greedy', '*1600']
C. Messytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are fed up with your messy room, so you decided to clean it up.Your room is a bracket sequence s=s_{1}s_{2}\dots s_{n} of length n. Each character of this string is either an opening bracket '(' or a closing bracket ')'.In one operation you can choose any consecutive substring of s and reverse it. In other words, you can choose any substring s[l \dots r]=s_l, s_{l+1}, \dots, s_r and change the order of elements in it into s_r, s_{r-1}, \dots, s_{l}.For example, if you will decide to reverse substring s[2 \dots 4] of string s="((()))" it will be equal to s="()(())".A regular (aka balanced) bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.A prefix of a string s is a substring that starts at position 1. For example, for s="(())()" there are 6 prefixes: "(", "((", "(()", "(())", "(())(" and "(())()".In your opinion, a neat and clean room s is a bracket sequence that: the whole string s is a regular bracket sequence; and there are exactly k prefixes of this sequence which are regular (including whole s itself). For example, if k = 2, then "(())()" is a neat and clean room.You want to use at most n operations to make your room neat and clean. Operations are applied one after another sequentially.It is guaranteed that the answer exists. Note that you do not need to minimize the number of operations: find any way to achieve the desired configuration in n or less operations.InputThe first line contains integer number t (1 \le t \le 100) — the number of test cases in the input. Then t test cases follow.The first line of a test case contains two integers n and k (1 \le k \le \frac{n}{2}, 2 \le n \le 2000, n is even) — length of s and required number of regular prefixes.The second line of a test case contains s of length n — the given bracket sequence. It contains only '(' and ')'.It is guaranteed that there are exactly \frac{n}{2} characters '(' and exactly \frac{n}{2} characters ')' in the given string.The sum of all values n over all the test cases in the input doesn't exceed 2000.OutputFor each test case print an answer.In the first line print integer m (0 \le m \le n) — the number of operations. You do not need to minimize m, any value is suitable.In the following m lines print description of the operations, each line should contain two integers l,r (1 \le l \le r \le n), representing single reverse operation of s[l \dots r]=s_{l}s_{l+1}\dots s_{r}. Operations are applied one after another sequentially.The final s after all operations should be a regular, also it should be exactly k prefixes (including s) which are regular.It is guaranteed that the answer exists. If there are several possible answers you can print any.ExampleInput 4 8 2 ()(())() 10 3 ))()()()(( 2 1 () 2 1 )( Output 4 3 4 1 1 5 8 2 2 3 4 10 1 4 6 7 0 1 1 2 NoteIn the first example, the final sequence is "()(()())", where two prefixes are regular, "()" and "()(()())". Note, that all the operations except "5 8" in the example output are useless (they do not change s).
4 8 2 ()(())() 10 3 ))()()()(( 2 1 () 2 1 )(
4 3 4 1 1 5 8 2 2 3 4 10 1 4 6 7 0 1 1 2
1 second
256 megabytes
['constructive algorithms', '*1700']
B. Boxtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPermutation p is a sequence of integers p=[p_1, p_2, \dots, p_n], consisting of n distinct (unique) positive integers between 1 and n, inclusive. For example, the following sequences are permutations: [3, 4, 1, 2], [1], [1, 2]. The following sequences are not permutations: [0], [1, 2, 1], [2, 3], [0, 1, 2].The important key is in the locked box that you need to open. To open the box you need to enter secret code. Secret code is a permutation p of length n. You don't know this permutation, you only know the array q of prefix maximums of this permutation. Formally: q_1=p_1, q_2=\max(p_1, p_2), q_3=\max(p_1, p_2,p_3), ... q_n=\max(p_1, p_2,\dots,p_n). You want to construct any possible suitable permutation (i.e. any such permutation, that calculated q for this permutation is equal to the given array).InputThe first line contains integer number t (1 \le t \le 10^4) — the number of test cases in the input. Then t test cases follow.The first line of a test case contains one integer n (1 \le n \le 10^{5}) — the number of elements in the secret code permutation p.The second line of a test case contains n integers q_1, q_2, \dots, q_n (1 \le q_i \le n) — elements of the array q for secret permutation. It is guaranteed that q_i \le q_{i+1} for all i (1 \le i < n).The sum of all values n over all the test cases in the input doesn't exceed 10^5.OutputFor each test case, print: If it's impossible to find such a permutation p, print "-1" (without quotes). Otherwise, print n distinct integers p_1, p_2, \dots, p_n (1 \le p_i \le n). If there are multiple possible answers, you can print any of them. ExampleInput 4 5 1 3 4 5 5 4 1 1 3 4 2 2 2 1 1 Output 1 3 4 5 2 -1 2 1 1 NoteIn the first test case of the example answer [1,3,4,5,2] is the only possible answer: q_{1} = p_{1} = 1; q_{2} = \max(p_{1}, p_{2}) = 3; q_{3} = \max(p_{1}, p_{2}, p_{3}) = 4; q_{4} = \max(p_{1}, p_{2}, p_{3}, p_{4}) = 5; q_{5} = \max(p_{1}, p_{2}, p_{3}, p_{4}, p_{5}) = 5. It can be proved that there are no answers for the second test case of the example.
4 5 1 3 4 5 5 4 1 1 3 4 2 2 2 1 1
1 3 4 5 2 -1 2 1 1
1 second
256 megabytes
['constructive algorithms', '*1200']
A. Math Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour math teacher gave you the following problem:There are n segments on the x-axis, [l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]. The segment [l; r] includes the bounds, i.e. it is a set of such x that l \le x \le r. The length of the segment [l; r] is equal to r - l.Two segments [a; b] and [c; d] have a common point (intersect) if there exists x that a \leq x \leq b and c \leq x \leq d. For example, [2; 5] and [3; 10] have a common point, but [5; 6] and [1; 4] don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given n segments.In other words, you need to find a segment [a; b], such that [a; b] and every [l_i; r_i] have a common point for each i, and b-a is minimal.InputThe first line contains integer number t (1 \le t \le 100) — the number of test cases in the input. Then t test cases follow.The first line of each test case contains one integer n (1 \le n \le 10^{5}) — the number of segments. The following n lines contain segment descriptions: the i-th of them contains two integers l_i,r_i (1 \le l_i \le r_i \le 10^{9}).The sum of all values n over all the test cases in the input doesn't exceed 10^5.OutputFor each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.ExampleInput 4 3 4 5 5 9 7 7 5 11 19 4 17 16 16 3 12 14 17 1 1 10 1 1 1 Output 2 4 0 0 NoteIn the first test case of the example, we can choose the segment [5;7] as the answer. It is the shortest segment that has at least one common point with all given segments.
4 3 4 5 5 9 7 7 5 11 19 4 17 16 16 3 12 14 17 1 1 10 1 1 1
2 4 0 0
2 seconds
256 megabytes
['math', '*1100']
G. To Make 1time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n positive integers written on the blackboard. Also, a positive number k \geq 2 is chosen, and none of the numbers on the blackboard are divisible by k. In one operation, you can choose any two integers x and y, erase them and write one extra number f(x + y), where f(x) is equal to x if x is not divisible by k, otherwise f(x) = f(x / k).In the end, there will be a single number of the blackboard. Is it possible to make the final number equal to 1? If so, restore any sequence of operations to do so.InputThe first line contains two integers n and k — the initial number of integers on the blackboard, and the chosen number (2 \leq n \leq 16, 2 \leq k \leq 2000).The second line contains n positive integers a_1, \ldots, a_n initially written on the blackboard. It is guaranteed that none of the numbers a_i is divisible by k, and the sum of all a_i does not exceed 2000.OutputIf it is impossible to obtain 1 as the final number, print "NO" in the only line.Otherwise, print "YES" on the first line, followed by n - 1 lines describing operations. The i-th of these lines has to contain two integers x_i and y_i to be erased and replaced with f(x_i + y_i) on the i-th operation. If there are several suitable ways, output any of them.ExamplesInput 2 2 1 1 Output YES 1 1 Input 4 3 7 8 13 23 Output YES 23 13 8 7 5 4 Input 3 4 1 2 3 Output NO NoteIn the second sample case: f(8 + 7) = f(15) = f(5) = 5; f(23 + 13) = f(36) = f(12) = f(4) = 4; f(5 + 4) = f(9) = f(3) = f(1) = 1.
2 2 1 1
YES 1 1
2 seconds
512 megabytes
['bitmasks', 'constructive algorithms', 'dp', 'greedy', 'number theory', '*3100']
F. Tree Factorytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBytelandian Tree Factory produces trees for all kinds of industrial applications. You have been tasked with optimizing the production of a certain type of tree for an especially large and important order.The tree in question is a rooted tree with n vertices labelled with distinct integers from 0 to n - 1. The vertex labelled 0 is the root of the tree, and for any non-root vertex v the label of its parent p(v) is less than the label of v.All trees at the factory are made from bamboo blanks. A bamboo is a rooted tree such that each vertex has exactly one child, except for a single leaf vertex with no children. The vertices of a bamboo blank can be labelled arbitrarily before its processing is started.To process a bamboo into another tree a single type of operation can be made: choose an arbitrary non-root vertex v such that its parent p(v) is not a root either. The operation consists of changing the parent of v to its parent's parent p(p(v)). Note that parents of all other vertices remain unchanged, in particular, the subtree of v does not change.Efficiency is crucial, hence you have to minimize the number of operations to make the desired tree from a bamboo blank. Construct any optimal sequence of operations to produce the desired tree.Note that the labelling of the resulting tree has to coincide with the labelling of the desired tree. Formally, the labels of the roots have to be equal, and for non-root vertices with the same label the labels of their parents should be the same.It is guaranteed that for any test present in this problem an answer exists, and further, an optimal sequence contains at most 10^6 operations. Note that any hack that does not meet these conditions will be invalid.InputThe first line contains a single integer n — the number of vertices in the tree (2 \leq n \leq 10^5).The second line contains n - 1 integers p(1), \ldots, p(n - 1) — indices of parent vertices of 1, \ldots, n - 1 respectively (0 \leq p(i) < i).OutputIn the first line, print n distinct integers id_1, \ldots, id_n — the initial labelling of the bamboo blank starting from the root vertex (0 \leq id_i < n).In the second line, print a single integer k — the number of operations in your sequence (0 \leq k \leq 10^6).In the third line print k integers v_1, \ldots, v_k describing operations in order. The i-th operation consists of changing p(v_i) to p(p(v_i)). Each operation should be valid, i.e. neither v_i nor p(v_i) can be the root of the tree at the moment.ExamplesInput 5 0 0 1 1 Output 0 2 1 4 3 2 1 3 Input 4 0 1 2 Output 0 1 2 3 0
5 0 0 1 1
0 2 1 4 3 2 1 3
2 seconds
512 megabytes
['constructive algorithms', 'greedy', 'trees', '*2500']
E. Rock Is Pushtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are at the top left cell (1, 1) of an n \times m labyrinth. Your goal is to get to the bottom right cell (n, m). You can only move right or down, one cell per step. Moving right from a cell (x, y) takes you to the cell (x, y + 1), while moving down takes you to the cell (x + 1, y).Some cells of the labyrinth contain rocks. When you move to a cell with rock, the rock is pushed to the next cell in the direction you're moving. If the next cell contains a rock, it gets pushed further, and so on.The labyrinth is surrounded by impenetrable walls, thus any move that would put you or any rock outside of the labyrinth is illegal.Count the number of different legal paths you can take from the start to the goal modulo 10^9 + 7. Two paths are considered different if there is at least one cell that is visited in one path, but not visited in the other.InputThe first line contains two integers n, m — dimensions of the labyrinth (1 \leq n, m \leq 2000).Next n lines describe the labyrinth. Each of these lines contains m characters. The j-th character of the i-th of these lines is equal to "R" if the cell (i, j) contains a rock, or "." if the cell (i, j) is empty.It is guaranteed that the starting cell (1, 1) is empty.OutputPrint a single integer — the number of different legal paths from (1, 1) to (n, m) modulo 10^9 + 7.ExamplesInput 1 1 . Output 1 Input 2 3 ... ..R Output 0 Input 4 4 ...R .RR. .RR. R... Output 4 NoteIn the first sample case we can't (and don't have to) move, hence the only path consists of a single cell (1, 1).In the second sample case the goal is blocked and is unreachable.Illustrations for the third sample case can be found here: https://assets.codeforces.com/rounds/1225/index.html
1 1 .
1
2 seconds
512 megabytes
['binary search', 'dp', '*2200']
D. Power Productstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given n positive integers a_1, \ldots, a_n, and an integer k \geq 2. Count the number of pairs i, j such that 1 \leq i < j \leq n, and there exists an integer x such that a_i \cdot a_j = x^k.InputThe first line contains two integers n and k (2 \leq n \leq 10^5, 2 \leq k \leq 100).The second line contains n integers a_1, \ldots, a_n (1 \leq a_i \leq 10^5).OutputPrint a single integer — the number of suitable pairs.ExampleInput 6 3 1 3 9 8 24 1 Output 5 NoteIn the sample case, the suitable pairs are: a_1 \cdot a_4 = 8 = 2^3; a_1 \cdot a_6 = 1 = 1^3; a_2 \cdot a_3 = 27 = 3^3; a_3 \cdot a_5 = 216 = 6^3; a_4 \cdot a_6 = 8 = 2^3.
6 3 1 3 9 8 24 1
5
2 seconds
512 megabytes
['hashing', 'math', 'number theory', '*1800']
C. p-binarytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer p (which may be positive, negative, or zero). To combine their tastes, they invented p-binary numbers of the form 2^x + p, where x is a non-negative integer.For example, some -9-binary ("minus nine" binary) numbers are: -8 (minus eight), 7 and 1015 (-8=2^0-9, 7=2^4-9, 1015=2^{10}-9).The boys now use p-binary numbers to represent everything. They now face a problem: given a positive integer n, what's the smallest number of p-binary numbers (not necessarily distinct) they need to represent n as their sum? It may be possible that representation is impossible altogether. Help them solve this problem.For example, if p=0 we can represent 7 as 2^0 + 2^1 + 2^2.And if p=-9 we can represent 7 as one number (2^4-9).Note that negative p-binary numbers are allowed to be in the sum (see the Notes section for an example).InputThe only line contains two integers n and p (1 \leq n \leq 10^9, -1000 \leq p \leq 1000).OutputIf it is impossible to represent n as the sum of any number of p-binary numbers, print a single integer -1. Otherwise, print the smallest possible number of summands.ExamplesInput 24 0 Output 2 Input 24 1 Output 3 Input 24 -1 Output 4 Input 4 -7 Output 2 Input 1 1 Output -1 Note0-binary numbers are just regular binary powers, thus in the first sample case we can represent 24 = (2^4 + 0) + (2^3 + 0).In the second sample case, we can represent 24 = (2^4 + 1) + (2^2 + 1) + (2^0 + 1).In the third sample case, we can represent 24 = (2^4 - 1) + (2^2 - 1) + (2^2 - 1) + (2^2 - 1). Note that repeated summands are allowed.In the fourth sample case, we can represent 4 = (2^4 - 7) + (2^1 - 7). Note that the second summand is negative, which is allowed.In the fifth sample case, no representation is possible.
24 0
2
2 seconds
512 megabytes
['bitmasks', 'brute force', 'math', '*1600']
B2. TV Subscriptions (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, \dots, a_n (1 \le a_i \le k), where a_i is the show, the episode of which will be shown in i-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows d (1 \le d \le n) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of d consecutive days in which all episodes belong to the purchased shows.InputThe first line contains an integer t (1 \le t \le 10000) — the number of test cases in the input. Then t test case descriptions follow.The first line of each test case contains three integers n, k and d (1 \le n \le 2\cdot10^5, 1 \le k \le 10^6, 1 \le d \le n). The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le k), where a_i is the show that is broadcasted on the i-th day.It is guaranteed that the sum of the values ​​of n for all test cases in the input does not exceed 2\cdot10^5.OutputPrint t integers — the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for d consecutive days. Please note that it is permissible that you will be able to watch more than d days in a row.ExampleInput 4 5 2 2 1 2 1 2 1 9 3 3 3 3 3 2 2 2 1 1 1 4 10 4 10 8 6 4 16 9 8 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 Output 2 1 4 5 NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show 1 and on show 2. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows 3,5,7,8,9, and you will be able to watch shows for the last eight days.
4 5 2 2 1 2 1 2 1 9 3 3 3 3 3 2 2 2 1 1 1 4 10 4 10 8 6 4 16 9 8 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3
2 1 4 5
2 seconds
256 megabytes
['implementation', 'two pointers', '*1300']
B1. TV Subscriptions (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, \dots, a_n (1 \le a_i \le k), where a_i is the show, the episode of which will be shown in i-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows d (1 \le d \le n) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of d consecutive days in which all episodes belong to the purchased shows.InputThe first line contains an integer t (1 \le t \le 100) — the number of test cases in the input. Then t test case descriptions follow.The first line of each test case contains three integers n, k and d (1 \le n \le 100, 1 \le k \le 100, 1 \le d \le n). The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le k), where a_i is the show that is broadcasted on the i-th day.It is guaranteed that the sum of the values ​​of n for all test cases in the input does not exceed 100.OutputPrint t integers — the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for d consecutive days. Please note that it is permissible that you will be able to watch more than d days in a row.ExampleInput 4 5 2 2 1 2 1 2 1 9 3 3 3 3 3 2 2 2 1 1 1 4 10 4 10 8 6 4 16 9 8 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 Output 2 1 4 5 NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show 1 and on show 2. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows 3,5,7,8,9, and you will be able to watch shows for the last eight days.
4 5 2 2 1 2 1 2 1 9 3 3 3 3 3 2 2 2 1 1 1 4 10 4 10 8 6 4 16 9 8 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3
2 1 4 5
2 seconds
256 megabytes
['implementation', '*1000']
A. Forgetting Thingstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation a + 1 = b with positive integers a and b, but Kolya forgot the numbers a and b. He does, however, remember that the first (leftmost) digit of a was d_a, and the first (leftmost) digit of b was d_b.Can you reconstruct any equation a + 1 = b that satisfies this property? It may be possible that Kolya misremembers the digits, and there is no suitable equation, in which case report so.InputThe only line contains two space-separated digits d_a and d_b (1 \leq d_a, d_b \leq 9).OutputIf there is no equation a + 1 = b with positive integers a and b such that the first digit of a is d_a, and the first digit of b is d_b, print a single number -1.Otherwise, print any suitable a and b that both are positive and do not exceed 10^9. It is guaranteed that if a solution exists, there also exists a solution with both numbers not exceeding 10^9.ExamplesInput 1 2 Output 199 200 Input 4 4 Output 412 413 Input 5 7 Output -1 Input 6 2 Output -1
1 2
199 200
2 seconds
512 megabytes
['math', '*900']
G. Wooden Rafttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are stuck on a desert island. The only way to save yourself is to craft a wooden raft and go to the sea. Fortunately, you have a hand-made saw and a forest nearby. Moreover, you've already cut several trees and prepared it to the point that now you have n logs and the i-th log has length a_i.The wooden raft you'd like to build has the following structure: 2 logs of length x and x logs of length y. Such raft would have the area equal to x \cdot y. Both x and y must be integers since it's the only way you can measure the lengths while being on a desert island. And both x and y must be at least 2 since the raft that is one log wide is unstable.You can cut logs in pieces but you can't merge two logs in one. What is the maximum area of the raft you can craft?InputThe first line contains the only integer n (1 \le n \le 5 \cdot 10^5) — the number of logs you have.The second line contains n integers a_1, a_2, \dots, a_n (2 \le a_i \le 5 \cdot 10^5) — the corresponding lengths of the logs.It's guaranteed that you can always craft at least 2 \times 2 raft.OutputPrint the only integer — the maximum area of the raft you can craft.ExamplesInput 1 9 Output 4 Input 9 9 10 9 18 9 9 9 28 9 Output 90 NoteIn the first example, you can cut the log of the length 9 in 5 parts: 2 + 2 + 2 + 2 + 1. Now you can build 2 \times 2 raft using 2 logs of length x = 2 and x = 2 logs of length y = 2.In the second example, you can cut a_4 = 18 into two pieces 9 + 9 and a_8 = 28 in three pieces 10 + 9 + 9. Now you can make 10 \times 9 raft using 2 logs of length 10 and 10 logs of length 9.
1 9
4
2 seconds
256 megabytes
['binary search', 'math', 'number theory', '*3200']
F. Stack Exterminable Arraystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's look at the following process: initially you have an empty stack and an array s of the length l. You are trying to push array elements to the stack in the order s_1, s_2, s_3, \dots s_{l}. Moreover, if the stack is empty or the element at the top of this stack is not equal to the current element, then you just push the current element to the top of the stack. Otherwise, you don't push the current element to the stack and, moreover, pop the top element of the stack. If after this process the stack remains empty, the array s is considered stack exterminable.There are samples of stack exterminable arrays: [1, 1]; [2, 1, 1, 2]; [1, 1, 2, 2]; [1, 3, 3, 1, 2, 2]; [3, 1, 3, 3, 1, 3]; [3, 3, 3, 3, 3, 3]; [5, 1, 2, 2, 1, 4, 4, 5]; Let's consider the changing of stack more details if s = [5, 1, 2, 2, 1, 4, 4, 5] (the top of stack is highlighted). after pushing s_1 = 5 the stack turn into [\textbf{5}]; after pushing s_2 = 1 the stack turn into [5, \textbf{1}]; after pushing s_3 = 2 the stack turn into [5, 1, \textbf{2}]; after pushing s_4 = 2 the stack turn into [5, \textbf{1}]; after pushing s_5 = 1 the stack turn into [\textbf{5}]; after pushing s_6 = 4 the stack turn into [5, \textbf{4}]; after pushing s_7 = 4 the stack turn into [\textbf{5}]; after pushing s_8 = 5 the stack is empty. You are given an array a_1, a_2, \ldots, a_n. You have to calculate the number of its subarrays which are stack exterminable.Note, that you have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 3 \cdot 10^5) — the number of queries.The first line of each query contains one integer n (1 \le n \le 3 \cdot 10^5) — the length of array a.The second line of each query contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the elements.It is guaranteed that the sum of all n over all queries does not exceed 3 \cdot 10^5.OutputFor each test case print one integer in single line — the number of stack exterminable subarrays of the array a.ExampleInput 3 5 2 1 1 2 2 6 1 2 1 1 3 2 9 3 1 2 2 1 6 6 3 3 Output 4 1 8 NoteIn the first query there are four stack exterminable subarrays: a_{1 \ldots 4} = [2, 1, 1, 2], a_{2 \ldots 3} = [1, 1], a_{2 \ldots 5} = [1, 1, 2, 2], a_{4 \ldots 5} = [2, 2].In the second query, only one subarray is exterminable subarray — a_{3 \ldots 4}.In the third query, there are eight stack exterminable subarrays: a_{1 \ldots 8}, a_{2 \ldots 5}, a_{2 \ldots 7}, a_{2 \ldots 9}, a_{3 \ldots 4}, a_{6 \ldots 7}, a_{6 \ldots 9}, a_{8 \ldots 9}.
3 5 2 1 1 2 2 6 1 2 1 1 3 2 9 3 1 2 2 1 6 6 3 3
4 1 8
2 seconds
256 megabytes
['data structures', 'divide and conquer', 'dp', 'hashing', '*2600']
E. Paint the Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i.Let's define the k-coloring of the tree as an assignment of exactly k colors to each vertex, so that each color is used no more than two times. You can assume that you have infinitely many colors available. We say that an edge is saturated in the given k-coloring if its endpoints share at least one color (i.e. there exists a color that is assigned to both endpoints).Let's also define the value of a k-coloring as the sum of weights of saturated edges.Please calculate the maximum possible value of a k-coloring of the given tree.You have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 5 \cdot 10^5) – the number of queries.The first line of each query contains two integers n and k (1 \le n, k \le 5 \cdot 10^5) — the number of vertices in the tree and the number of colors to assign to each vertex, respectively.Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i (1 \le u_i, v_i \le n, u_i \ne v_i, 1 \le w_i \le 10^5) — the labels of vertices it connects and the weight of the edge. It is guaranteed that the given edges form a tree.It is guaranteed that sum of all n over all queries does not exceed 5 \cdot 10^5.OutputFor each query print one integer — the maximum value of a k-coloring of the given tree.ExampleInput 2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3 Output 8 14 NoteThe tree corresponding to the first query in the example:One of the possible k-colorings in the first example: (1), (1), (2), (2), then the 1-st and the 3-rd edges are saturated and the sum of their weights is 8.The tree corresponding to the second query in the example:One of the possible k-colorings in the second example: (1, 2), (1, 3), (2, 4), (5, 6), (7, 8), (3, 4), (5, 6), then the 1-st, 2-nd, 5-th and 6-th edges are saturated and the sum of their weights is 14.
2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3
8 14
2 seconds
256 megabytes
['dp', 'sortings', 'trees', '*2100']
D. Sequence Sortingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a_1, a_2, \dots, a_n, consisting of integers.You can apply the following operation to this sequence: choose some integer x and move all elements equal to x either to the beginning, or to the end of a. Note that you have to move all these elements in one direction in one operation.For example, if a = [2, 1, 3, 1, 1, 3, 2], you can get the following sequences in one operation (for convenience, denote elements equal to x as x-elements): [1, 1, 1, 2, 3, 3, 2] if you move all 1-elements to the beginning; [2, 3, 3, 2, 1, 1, 1] if you move all 1-elements to the end; [2, 2, 1, 3, 1, 1, 3] if you move all 2-elements to the beginning; [1, 3, 1, 1, 3, 2, 2] if you move all 2-elements to the end; [3, 3, 2, 1, 1, 1, 2] if you move all 3-elements to the beginning; [2, 1, 1, 1, 2, 3, 3] if you move all 3-elements to the end; You have to determine the minimum number of such operations so that the sequence a becomes sorted in non-descending order. Non-descending order means that for all i from 2 to n, the condition a_{i-1} \le a_i is satisfied.Note that you have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 3 \cdot 10^5) — the number of the queries. Each query is represented by two consecutive lines.The first line of each query contains one integer n (1 \le n \le 3 \cdot 10^5) — the number of elements.The second line of each query contains n integers a_1, a_2, \dots , a_n (1 \le a_i \le n) — the elements.It is guaranteed that the sum of all n does not exceed 3 \cdot 10^5.OutputFor each query print one integer — the minimum number of operation for sorting sequence a in non-descending order.ExampleInput 3 7 3 1 6 6 3 1 1 8 1 1 4 4 4 7 8 8 7 4 2 5 2 6 2 7 Output 2 0 1 NoteIn the first query, you can move all 1-elements to the beginning (after that sequence turn into [1, 1, 1, 3, 6, 6, 3]) and then move all 6-elements to the end.In the second query, the sequence is sorted initially, so the answer is zero.In the third query, you have to move all 2-elements to the beginning.
3 7 3 1 6 6 3 1 1 8 1 1 4 4 4 7 8 8 7 4 2 5 2 6 2 7
2 0 1
2 seconds
256 megabytes
['dp', 'greedy', 'two pointers', '*2000']
C. Save the Naturetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!You have n tickets to sell. The price of the i-th ticket is p_i. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of the tickets). You know that the cinema participates in two ecological restoration programs applying them to the order you chose: The x\% of the price of each the a-th sold ticket (a-th, 2a-th, 3a-th and so on) in the order you chose is aimed for research and spreading of renewable energy sources. The y\% of the price of each the b-th sold ticket (b-th, 2b-th, 3b-th and so on) in the order you chose is aimed for pollution abatement. If the ticket is in both programs then the (x + y) \% are used for environmental activities. Also, it's known that all prices are multiples of 100, so there is no need in any rounding.For example, if you'd like to sell tickets with prices [400, 100, 300, 200] and the cinema pays 10\% of each 2-nd sold ticket and 20\% of each 3-rd sold ticket, then arranging them in order [100, 200, 300, 400] will lead to contribution equal to 100 \cdot 0 + 200 \cdot 0.1 + 300 \cdot 0.2 + 400 \cdot 0.1 = 120. But arranging them in order [100, 300, 400, 200] will lead to 100 \cdot 0 + 300 \cdot 0.1 + 400 \cdot 0.2 + 200 \cdot 0.1 = 130.Nature can't wait, so you decided to change the order of tickets in such a way, so that the total contribution to programs will reach at least k in minimum number of sold tickets. Or say that it's impossible to do so. In other words, find the minimum number of tickets which are needed to be sold in order to earn at least k.InputThe first line contains a single integer q (1 \le q \le 100) — the number of independent queries. Each query consists of 5 lines.The first line of each query contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of tickets.The second line contains n integers p_1, p_2, \dots, p_n (100 \le p_i \le 10^9, p_i \bmod 100 = 0) — the corresponding prices of tickets.The third line contains two integers x and a (1 \le x \le 100, x + y \le 100, 1 \le a \le n) — the parameters of the first program.The fourth line contains two integers y and b (1 \le y \le 100, x + y \le 100, 1 \le b \le n) — the parameters of the second program.The fifth line contains single integer k (1 \le k \le 10^{14}) — the required total contribution.It's guaranteed that the total number of tickets per test doesn't exceed 2 \cdot 10^5.OutputPrint q integers — one per query. For each query, print the minimum number of tickets you need to sell to make the total ecological contribution of at least k if you can sell tickets in any order.If the total contribution can not be achieved selling all the tickets, print -1.ExampleInput 4 1 100 50 1 49 1 100 8 100 200 100 200 100 200 100 100 10 2 15 3 107 3 1000000000 1000000000 1000000000 50 1 50 1 3000000000 5 200 100 100 100 100 69 5 31 2 90 Output -1 6 3 4 NoteIn the first query the total contribution is equal to 50 + 49 = 99 < 100, so it's impossible to gather enough money.In the second query you can rearrange tickets in a following way: [100, 100, 200, 200, 100, 200, 100, 100] and the total contribution from the first 6 tickets is equal to 100 \cdot 0 + 100 \cdot 0.1 + 200 \cdot 0.15 + 200 \cdot 0.1 + 100 \cdot 0 + 200 \cdot 0.25 = 10 + 30 + 20 + 50 = 110.In the third query the full price of each ticket goes to the environmental activities.In the fourth query you can rearrange tickets as [100, 200, 100, 100, 100] and the total contribution from the first 4 tickets is 100 \cdot 0 + 200 \cdot 0.31 + 100 \cdot 0 + 100 \cdot 0.31 = 62 + 31 = 93.
4 1 100 50 1 49 1 100 8 100 200 100 200 100 200 100 100 10 2 15 3 107 3 1000000000 1000000000 1000000000 50 1 50 1 3000000000 5 200 100 100 100 100 69 5 31 2 90
-1 6 3 4
2 seconds
256 megabytes
['binary search', 'greedy', '*1600']
B. Strings Equalizationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings of equal length s and t consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.For example, if s is "acbc" you can get the following strings in one operation: "aabc" (if you perform s_2 = s_1); "ccbc" (if you perform s_1 = s_2); "accc" (if you perform s_3 = s_2 or s_3 = s_4); "abbc" (if you perform s_2 = s_3); "acbb" (if you perform s_4 = s_3); Note that you can also apply this operation to the string t.Please determine whether it is possible to transform s into t, applying the operation above any number of times.Note that you have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 100) — the number of queries. Each query is represented by two consecutive lines.The first line of each query contains the string s (1 \le |s| \le 100) consisting of lowercase Latin letters.The second line of each query contains the string t (1 \le |t| \leq 100, |t| = |s|) consisting of lowercase Latin letters.OutputFor each query, print "YES" if it is possible to make s equal to t, and "NO" otherwise.You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes", and "YES" will all be recognized as positive answer).ExampleInput 3 xabb aabx technocup technocup a z Output YES YES NO NoteIn the first query, you can perform two operations s_1 = s_2 (after it s turns into "aabb") and t_4 = t_3 (after it t turns into "aabb"). In the second query, the strings are equal initially, so the answer is "YES".In the third query, you can not make strings s and t equal. Therefore, the answer is "NO".
3 xabb aabx technocup technocup a z
YES YES NO
1 second
256 megabytes
['strings', '*1000']
A. CMEtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||. Calculate the minimum number of matches which you have to buy for assembling CME.Note, that you have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 100) — the number of queries.The only line of each query contains one integer n (2 \le n \le 10^9) — the number of matches.OutputFor each test case print one integer in single line — the minimum number of matches which you have to buy for assembling CME. ExampleInput 4 2 5 8 11 Output 2 1 0 1 NoteThe first and second queries are explained in the statement.In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
4 2 5 8 11
2 1 0 1
1 second
256 megabytes
['math', '*800']
G. Graph And Numberstime limit per test3.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph with n vertices and m edges. You have to write a number on each vertex of this graph, each number should be either 0 or 1. After that, you write a number on each edge equal to the sum of numbers on vertices incident to that edge.You have to choose the numbers you will write on the vertices so that there is at least one edge with 0 written on it, at least one edge with 1 and at least one edge with 2. How many ways are there to do it? Two ways to choose numbers are different if there exists at least one vertex which has different numbers written on it in these two ways.InputThe first line contains two integers n and m (1 \le n \le 40, 0 \le m \le \frac{n(n - 1)}{2}) — the number of vertices and the number of edges, respectively.Then m lines follow, each line contains two numbers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i) — the endpoints of the i-th edge. It is guaranteed that each pair of vertices is connected by at most one edge.OutputPrint one integer — the number of ways to write numbers on all vertices so that there exists at least one edge with 0 written on it, at least one edge with 1 and at least one edge with 2.ExamplesInput 6 5 1 2 2 3 3 4 4 5 5 1 Output 20 Input 4 4 1 2 2 3 3 4 4 1 Output 4 Input 35 29 1 2 2 3 3 1 4 1 4 2 3 4 7 8 8 9 9 10 10 7 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23 24 24 25 25 26 26 27 27 28 28 29 29 30 Output 34201047040
6 5 1 2 2 3 3 4 4 5 5 1
20
3.5 seconds
512 megabytes
['bitmasks', 'brute force', 'combinatorics', 'dp', 'meet-in-the-middle', '*2900']
F. Choose a Squaretime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya recently found a game "Choose a Square". In this game, there are n points numbered from 1 to n on an infinite field. The i-th point has coordinates (x_i, y_i) and cost c_i.You have to choose a square such that its sides are parallel to coordinate axes, the lower left and upper right corners belong to the line y = x, and all corners have integer coordinates.The score you get is the sum of costs of the points covered by the selected square minus the length of the side of the square. Note that the length of the side can be zero.Petya asks you to calculate the maximum possible score in the game that can be achieved by placing exactly one square.InputThe first line of the input contains one integer n (1 \le n \le 5 \cdot 10^5) — the number of points on the field.Each of the following n lines contains three integers x_i, y_i, c_i (0 \le x_i, y_i \le 10^9, -10^6 \le c_i \le 10^6) — coordinates of the i-th point and its cost, respectively.OutputIn the first line print the maximum score Petya can achieve.In the second line print four integers x_1, y_1, x_2, y_2 (0 \le x_1, y_1, x_2, y_2 \le 2 \cdot 10^9, x_1 = y_1, x_2 = y_2, x_1 \le x_2) separated by spaces — the coordinates of the lower left and upper right corners of the square which Petya has to select in order to achieve the maximum score.ExamplesInput 6 0 0 2 1 0 -5 1 1 3 2 3 4 1 4 -4 3 1 -1 Output 4 1 1 3 3 Input 5 3 3 0 3 3 -3 0 2 -1 3 1 3 0 0 -2 Output 0 1 1 1 1 NoteThe field corresponding to the first example:
6 0 0 2 1 0 -5 1 1 3 2 3 4 1 4 -4 3 1 -1
4 1 1 3 3
6 seconds
256 megabytes
['binary search', 'data structures', 'sortings', '*2400']
E. Game With Stringtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob play a game. Initially they have a string s_1, s_2, \dots, s_n, consisting of only characters . and X. They take alternating turns, and Alice is moving first. During each turn, the player has to select a contiguous substring consisting only of characters . and replaces each of them with X. Alice must select a substing of length a, and Bob must select a substring of length b. It is guaranteed that a > b.For example, if s = ...X.. and a = 3, b = 2, then after Alice's move string can turn only into XXXX... And if it's Bob's turn and the string s = ...X.., then after Bob's move the string can turn into XX.X.., .XXX.. or ...XXX.Whoever is unable to make a move, loses. You have to determine who wins if they both play optimally.You have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 3 \cdot 10^5) — the number of queries.The first line of each query contains two integers a and b (1 \le b < a \le 3 \cdot 10^5).The second line of each query contains the string s (1 \le |s| \le 3 \cdot 10^5), consisting of only characters . and X.It is guaranteed that sum of all |s| over all queries not exceed 3 \cdot 10^5.OutputFor each test case print YES if Alice can win and NO otherwise.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).ExampleInput 3 3 2 XX......XX...X 4 2 X...X.X..X 5 3 .......X..X Output YES NO YES NoteIn the first query Alice can select substring s_3 \dots s_5. After that s turns into XXXXX...XX...X. After that, no matter what move Bob makes, Alice can make the move (this will be her second move), but Bob can't make his second move.In the second query Alice can not win because she cannot even make one move.In the third query Alice can choose substring s_2 \dots s_6. After that s turns into .XXXXX.X..X, and Bob can't make a move after that.
3 3 2 XX......XX...X 4 2 X...X.X..X 5 3 .......X..X
YES NO YES
3 seconds
256 megabytes
['games', '*2500']
D. Make The Fence Great Againtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a fence consisting of n vertical boards. The width of each board is 1. The height of the i-th board is a_i. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fence is great if and only if for all indices from 2 to n, the condition a_{i-1} \neq a_i holds.Unfortunately, it is possible that now your fence is not great. But you can change it! You can increase the length of the i-th board by 1, but you have to pay b_i rubles for it. The length of each board can be increased any number of times (possibly, zero).Calculate the minimum number of rubles you have to spend to make the fence great again!You have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 3 \cdot 10^5) — the number of queries.The first line of each query contains one integers n (1 \le n \le 3 \cdot 10^5) — the number of boards in the fence.The following n lines of each query contain the descriptions of the boards. The i-th line contains two integers a_i and b_i (1 \le a_i, b_i \le 10^9) — the length of the i-th board and the price for increasing it by 1, respectively.It is guaranteed that sum of all n over all queries not exceed 3 \cdot 10^5.It is guaranteed that answer to each query will not exceed 10^{18}.OutputFor each query print one integer — the minimum number of rubles you have to spend to make the fence great.ExampleInput 3 3 2 4 2 1 3 5 3 2 3 2 10 2 6 4 1 7 3 3 2 6 1000000000 2 Output 2 9 0 NoteIn the first query you have to increase the length of second board by 2. So your total costs if 2 \cdot b_2 = 2.In the second query you have to increase the length of first board by 1 and the length of third board by 1. So your total costs if 1 \cdot b_1 + 1 \cdot b_3 = 9.In the third query the fence is great initially, so you don't need to spend rubles.
3 3 2 4 2 1 3 5 3 2 3 2 10 2 6 4 1 7 3 3 2 6 1000000000 2
2 9 0
2 seconds
256 megabytes
['dp', '*1800']
C. Perfect Teamtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that c of your students are coders, m are mathematicians and x have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer q independent queries.InputThe first line contains a single integer q (1 \le q \le 10^4) — the number of queries. Each of the next q lines contains three integers c, m and x (0 \le c, m, x \le 10^8) — the number of coders, mathematicians and students without any specialization in the university, respectively.Note that the no student is both coder and mathematician at the same time. OutputPrint q integers — the i-th of them should be the answer to the i query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into. ExampleInput 6 1 1 1 3 6 0 0 0 0 0 1 1 10 1 10 4 4 1 Output 1 3 0 0 1 3 NoteIn the first example here are how teams are formed: the only team of 1 coder, 1 mathematician and 1 without specialization; all three teams consist of 1 coder and 2 mathematicians; no teams can be formed; no teams can be formed; one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team; one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians.
6 1 1 1 3 6 0 0 0 0 0 1 1 10 1 10 4 4 1
1 3 0 0 1 3
2 seconds
256 megabytes
['binary search', 'math', '*1200']
B. Knightstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a chess board with n rows and n columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board.A knight is a chess piece that can attack a piece in cell (x_2, y_2) from the cell (x_1, y_1) if one of the following conditions is met: |x_1 - x_2| = 2 and |y_1 - y_2| = 1, or |x_1 - x_2| = 1 and |y_1 - y_2| = 2. Here are some examples of which cells knight can attack. In each of the following pictures, if the knight is currently in the blue cell, it can attack all red cells (and only them). A duel of knights is a pair of knights of different colors such that these knights attack each other. You have to put a knight (a white one or a black one) into each cell in such a way that the number of duels is maximum possible.InputThe first line contains one integer n (3 \le n \le 100) — the number of rows (and columns) in the board.OutputPrint n lines with n characters in each line. The j-th character in the i-th line should be W, if the cell (i, j) contains a white knight, or B, if it contains a black knight. The number of duels should be maximum possible. If there are multiple optimal answers, print any of them.ExampleInput 3 Output WBW BBB WBW NoteIn the first example, there are 8 duels: the white knight in (1, 1) attacks the black knight in (3, 2); the white knight in (1, 1) attacks the black knight in (2, 3); the white knight in (1, 3) attacks the black knight in (3, 2); the white knight in (1, 3) attacks the black knight in (2, 1); the white knight in (3, 1) attacks the black knight in (1, 2); the white knight in (3, 1) attacks the black knight in (2, 3); the white knight in (3, 3) attacks the black knight in (1, 2); the white knight in (3, 3) attacks the black knight in (2, 1).
3
WBW BBB WBW
1 second
256 megabytes
['constructive algorithms', 'greedy', '*1100']
A. 2048 Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset.During each operation you choose two equal integers from s, remove them from s and insert the number equal to their sum into s.For example, if s = \{1, 2, 1, 1, 4, 2, 2\} and you choose integers 2 and 2, then the multiset becomes \{1, 1, 1, 4, 4, 2\}.You win if the number 2048 belongs to your multiset. For example, if s = \{1024, 512, 512, 4\} you can win as follows: choose 512 and 512, your multiset turns into \{1024, 1024, 4\}. Then choose 1024 and 1024, your multiset turns into \{2048, 4\} and you win.You have to determine if you can win this game.You have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 100) – the number of queries.The first line of each query contains one integer n (1 \le n \le 100) — the number of elements in multiset.The second line of each query contains n integers s_1, s_2, \dots, s_n (1 \le s_i \le 2^{29}) — the description of the multiset. It is guaranteed that all elements of the multiset are powers of two. OutputFor each query print YES if it is possible to obtain the number 2048 in your multiset, and NO otherwise.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).ExampleInput 6 4 1024 512 64 512 1 2048 3 64 512 2 2 4096 4 7 2048 2 2048 2048 2048 2048 2048 2 2048 4096 Output YES YES NO NO YES YES NoteIn the first query you can win as follows: choose 512 and 512, and s turns into \{1024, 64, 1024\}. Then choose 1024 and 1024, and s turns into \{2048, 64\} and you win.In the second query s contains 2048 initially.
6 4 1024 512 64 512 1 2048 3 64 512 2 2 4096 4 7 2048 2 2048 2048 2048 2048 2048 2 2048 4096
YES YES NO NO YES YES
1 second
256 megabytes
['brute force', 'greedy', 'math', '*1000']
G. Geolocationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are working for the Gryzzl company, headquartered in Pawnee, Indiana.The new national park has been opened near Pawnee recently and you are to implement a geolocation system, so people won't get lost. The concept you developed is innovative and minimalistic. There will be n antennas located somewhere in the park. When someone would like to know their current location, their Gryzzl hologram phone will communicate with antennas and obtain distances from a user's current location to all antennas.Knowing those distances and antennas locations it should be easy to recover a user's location... Right? Well, almost. The only issue is that there is no way to distinguish antennas, so you don't know, which distance corresponds to each antenna. Your task is to find a user's location given as little as all antennas location and an unordered multiset of distances.InputThe first line of input contains a single integer n (2 \leq n \leq 10^5) which is the number of antennas.The following n lines contain coordinates of antennas, i-th line contain two integers x_i and y_i (0 \leq x_i,y_i \leq 10^8). It is guaranteed that no two antennas coincide.The next line of input contains integer m (1 \leq n \cdot m \leq 10^5), which is the number of queries to determine the location of the user.Following m lines contain n integers 0 \leq d_1 \leq d_2 \leq \dots \leq d_n \leq 2 \cdot 10^{16} each. These integers form a multiset of squared distances from unknown user's location (x;y) to antennas.For all test cases except the examples it is guaranteed that all user's locations (x;y) were chosen uniformly at random, independently from each other among all possible integer locations having 0 \leq x, y \leq 10^8.OutputFor each query output k, the number of possible a user's locations matching the given input and then output the list of these locations in lexicographic order.It is guaranteed that the sum of all k over all points does not exceed 10^6.ExamplesInput 3 0 0 0 1 1 0 1 1 1 2 Output 1 1 1 Input 4 0 0 0 1 1 0 1 1 2 0 1 1 2 2 5 5 8 Output 4 0 0 0 1 1 0 1 1 4 -1 -1 -1 2 2 -1 2 2 NoteAs you see in the second example, although initially a user's location is picked to have non-negative coordinates, you have to output all possible integer locations.
3 0 0 0 1 1 0 1 1 1 2
1 1 1
2 seconds
256 megabytes
['geometry', '*3400']
F. Gardener Alextime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on n vertices. Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from 1 to n which he was presented at his last birthday, so he decided to grow a tree according to this permutation. To do so he does the following process: he finds a minimum element and makes it a root of the tree. After that permutation is divided into two parts: everything that is to the left of the minimum element, and everything that is to the right. The minimum element on the left part becomes the left son of the root, and the minimum element on the right part becomes the right son of the root. After that, this process is repeated recursively on both parts.Now Alex wants to grow a forest of trees: one tree for each cyclic shift of the permutation. He is interested in what cyclic shift gives the tree of minimum depth. Unfortunately, growing a forest is a hard and long process, but Alex wants the answer right now. Will you help him?We remind that cyclic shift of permutation a_1, a_2, \ldots, a_k, \ldots, a_n for k elements to the left is the permutation a_{k + 1}, a_{k + 2}, \ldots, a_n, a_1, a_2, \ldots, a_k.InputFirst line contains an integer number n ~ (1 \leqslant n \leqslant 200\,000) — length of the permutation.Second line contains n integer numbers a_1, a_2, \ldots, a_n ~ (1 \leqslant a_i \leqslant n), and it is guaranteed that all numbers occur exactly one time.OutputPrint two numbers separated with space: minimum possible depth of a tree and how many elements we need to shift left to achieve this depth. The number of elements should be a number from 0 to n - 1. If there are several possible answers, print any of them.ExampleInput 4 1 2 3 4 Output 3 3 NoteThe following picture depicts all possible trees for sample test and cyclic shifts on which they are achieved.
4 1 2 3 4
3 3
2 seconds
256 megabytes
['binary search', 'data structures', '*2700']
E. Tourismtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlex decided to go on a touristic trip over the country.For simplicity let's assume that the country has n cities and m bidirectional roads connecting them. Alex lives in city s and initially located in it. To compare different cities Alex assigned each city a score w_i which is as high as interesting city seems to Alex.Alex believes that his trip will be interesting only if he will not use any road twice in a row. That is if Alex came to city v from city u, he may choose as the next city in the trip any city connected with v by the road, except for the city u.Your task is to help Alex plan his city in a way that maximizes total score over all cities he visited. Note that for each city its score is counted at most once, even if Alex been there several times during his trip.InputFirst line of input contains two integers n and m, (1 \le n \le 2 \cdot 10^5, 0 \le m \le 2 \cdot 10^5) which are numbers of cities and roads in the country.Second line contains n integers w_1, w_2, \ldots, w_n (0 \le w_i \le 10^9) which are scores of all cities.The following m lines contain description of the roads. Each of these m lines contains two integers u and v (1 \le u, v \le n) which are cities connected by this road.It is guaranteed that there is at most one direct road between any two cities, no city is connected to itself by the road and, finally, it is possible to go from any city to any other one using only roads.The last line contains single integer s (1 \le s \le n), which is the number of the initial city.OutputOutput single integer which is the maximum possible sum of scores of visited cities.ExamplesInput 5 7 2 2 8 6 9 1 2 1 3 2 4 3 2 4 5 2 5 1 5 2 Output 27 Input 10 12 1 7 1 9 3 3 6 30 1 10 1 2 1 3 3 5 5 7 2 3 5 4 6 9 4 6 3 7 6 8 9 4 9 10 6 Output 61
5 7 2 2 8 6 9 1 2 1 3 2 4 3 2 4 5 2 5 1 5 2
27
2 seconds
256 megabytes
['dfs and similar', 'dp', 'dsu', 'graphs', 'greedy', 'trees', '*2200']
D. Alex and Juliantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBoy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.InputFirst line contains an integer n ~ (1 \leqslant n \leqslant 200\,000) — size of BSecond line contains n integers b_1, b_2, \ldots, b_n ~ (1 \leqslant b_i \leqslant 10^{18}) — numbers of B, all b_i are uniqueOutputIn the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.If there are multiple answers, print any of them.ExamplesInput 3 1 2 3 Output 1 2 Input 2 2 6 Output 0
3 1 2 3
1 2
2 seconds
256 megabytes
['bitmasks', 'math', 'number theory', '*1900']
C. Substring Game in the Lessontime limit per test2 secondsmemory limit per test256 mebibytesinputstandard inputoutputstandard outputMike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string s and a number k (0 \le k < |s|).At the beginning of the game, players are given a substring of s with left border l and right border r, both equal to k (i.e. initially l=r=k). Then players start to make moves one by one, according to the following rules: A player chooses l^{\prime} and r^{\prime} so that l^{\prime} \le l, r^{\prime} \ge r and s[l^{\prime}, r^{\prime}] is lexicographically less than s[l, r]. Then the player changes l and r in this way: l := l^{\prime}, r := r^{\prime}. Ann moves first. The player, that can't make a move loses.Recall that a substring s[l, r] (l \le r) of a string s is a continuous segment of letters from s that starts at position l and ends at position r. For example, "ehn" is a substring (s[3, 5]) of "aaaehnsvz" and "ahz" is not.Mike and Ann were playing so enthusiastically that they did not notice the teacher approached them. Surprisingly, the teacher didn't scold them, instead of that he said, that he can figure out the winner of the game before it starts, even if he knows only s and k.Unfortunately, Mike and Ann are not so keen in the game theory, so they ask you to write a program, that takes s and determines the winner for all possible k.InputThe first line of the input contains a single string s (1 \leq |s| \leq 5 \cdot 10^5) consisting of lowercase English letters.OutputPrint |s| lines.In the line i write the name of the winner (print Mike or Ann) in the game with string s and k = i, if both play optimallyExamplesInput abba Output Mike Ann Ann Mike Input cba Output Mike Mike Mike
abba
Mike Ann Ann Mike
2 seconds
256 mebibytes
['games', 'greedy', 'strings', '*1300']
B. Multiplication Tabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i \cdot a_j where a_1, \dots, a_n is some sequence of positive integers.Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, \dots, a_n. Help Sasha restore the array!InputThe first line contains a single integer n (3 \leqslant n \leqslant 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 \leq M_{ij} \leq 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0.OutputIn a single line print n integers, the original array a_1, \dots, a_n (1 \leq a_i \leq 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any.ExamplesInput 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998
5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0
2 2 3 1 2
2 seconds
256 megabytes
['math', 'number theory', '*1300']
A. Cardstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one. InputThe first line contains a single integer n (1 \leqslant n \leqslant 10^5) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'.It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit 0 or "one" which corresponds to the digit 1.OutputPrint the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.ExamplesInput 4 ezor Output 0 Input 10 nznooeeoer Output 1 1 0 NoteIn the first example, the correct initial ordering is "zero".In the second example, the correct initial ordering is "oneonezero".
4 ezor
0
2 seconds
256 megabytes
['implementation', 'sortings', 'strings', '*800']
G. Harvestertime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Bubble Cup finals season and farmer Johnny Bubbles must harvest his bubbles. The bubbles are in a rectangular bubblefield formed of N x M square parcels divided into N rows and M columns. The parcel in i^{th} row and j^{th} column yields A_{i,j} bubbles.Johnny Bubbles has available a very special self-driving bubble harvester that, once manually positioned at the beginning of a row or column, automatically harvests all the bubbles in that row or column. Once the harvester reaches the end of the row or column it stops and must be repositioned. The harvester can pass through any parcel any number of times, but it can collect bubbles from the parcel only once.Johnny is very busy farmer, so he is available to manually position the harvester at most four times per day. Johnny is also impatient, so he wants to harvest as many bubbles as possible on the first day.Please help Johnny to calculate what is the maximum number of bubbles he can collect on the first day.InputThe first line contains two integers N and M (1 \leq N, M \leq N * M \leq 10^{5}) - the bubblefield size.Each of the next N lines contains M integers. The j^{th} element in the i^{th} line is A_{i,j} (0 \leq a_{i,j} \leq 10^{9}) — the yield of the parcel located in the i^{th} row and the j^{th} column.OutputOutput contains one integer number - maximum number of the bubbles Johnny can harvest on the first day.ExamplesInput 2 2 1 2 3 4 Output 10 Input 5 5 0 9 2 7 0 9 0 3 0 5 0 8 0 3 1 6 7 4 3 9 3 6 4 1 0 Output 80 NoteIn the first example, farmer Johnny can harvest all the bubbles by positioning the harvester on the first and the second row.In the second example, one way Johnny can harvest maximum number of bubbles is to position the harvester in the second row, the fourth row, the second column and the fourth column.
2 2 1 2 3 4
10
0.5 seconds
256 megabytes
['implementation', '*2000']
C. Periodic integer numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice became interested in periods of integer numbers. We say positive X integer number is periodic with length L if there exists positive integer number P with L digits such that X can be written as PPPP…P. For example:X = 123123123 is periodic number with length L = 3 and L = 9X = 42424242 is periodic number with length L = 2,L = 4 and L = 8X = 12345 is periodic number with length L = 5For given positive period length L and positive integer number A, Alice wants to find smallest integer number X strictly greater than A that is periodic with length L.InputFirst line contains one positive integer number L \ (1 \leq L \leq 10^5) representing length of the period. Second line contains one positive integer number A \ (1 \leq A \leq 10^{100 000}).OutputOne positive integer number representing smallest positive number that is periodic with length L and is greater than A.ExamplesInput 3 123456 Output 124124 Input 3 12345 Output 100100 NoteIn first example 124124 is the smallest number greater than 123456 that can be written with period L = 3 (P = 124).In the second example 100100 is the smallest number greater than 12345 with period L = 3 (P=100)
3 123456
124124
1 second
256 megabytes
['implementation', 'strings', '*1700']
I. The Light Squaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor her birthday Alice received an interesting gift from her friends – The Light Square. The Light Square game is played on an N \times N lightbulbs square board with a magical lightbulb bar of size N \times 1 that has magical properties. At the start of the game some lights on the square board and magical bar are turned on. The goal of the game is to transform the starting light square board pattern into some other pattern using the magical bar without rotating the square board. The magical bar works as follows: It can be placed on any row or column The orientation of the magical lightbulb must be left to right or top to bottom for it to keep its magical properties The entire bar needs to be fully placed on a board The lights of the magical bar never change If the light on the magical bar is the same as the light of the square it is placed on it will switch the light on the square board off, otherwise it will switch the light on The magical bar can be used an infinite number of times Alice has a hard time transforming her square board into the pattern Bob gave her. Can you help her transform the board or let her know it is impossible? If there are multiple solutions print any. InputThe first line contains one positive integer number N\ (1 \leq N \leq 2000) representing the size of the square board. The next N lines are strings of length N consisting of 1's and 0's representing the initial state of the square board starting from the top row. If the character in a string is 1 it means the light is turned on, otherwise it is off. The next N lines are strings of length N consisting of 1's and 0's representing the desired state of the square board starting from the top row that was given to Alice by Bob. The last line is one string of length N consisting of 1's and 0's representing the pattern of the magical bar in a left to right order. OutputTransform the instructions for Alice in order to transform the square board into the pattern Bob gave her. The first line of the output contains an integer number M\ (0 \leq M \leq 10^5) representing the number of times Alice will need to apply the magical bar. The next M lines are of the form "col X" or "row X", where X is 0-based index of the matrix, meaning the magical bar should be applied to either row X or column X. If there is no solution, print only -1. In case of multiple solutions print any correct one. ExamplesInput 2 11 11 00 01 11 Output -1 Input 2 10 00 00 00 10 Output 1 row 0 Input 3 110 011 100 100 011 100 100 Output 3 row 0 col 0 col 1 NoteExample 1: It is impossible to transform square board from one format to anotherExample 2: Magic bar can be applied on first row or column.
2 11 11 00 01 11
-1
2 seconds
256 megabytes
['2-sat', 'dfs and similar', 'greedy', '*2100']
H. Function Compositiontime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe are definitely not going to bother you with another generic story when Alice finds about an array or when Alice and Bob play some stupid game. This time you'll get a simple, plain text.First, let us define several things. We define function F on the array A such that F(i, 1) = A[i] and F(i, m) = A[F(i, m - 1)] for m > 1. In other words, value F(i, m) represents composition A[...A[i]] applied m times.You are given an array of length N with non-negative integers. You are expected to give an answer on Q queries. Each query consists of two numbers – m and y. For each query determine how many x exist such that F(x,m) = y.InputThe first line contains one integer N (1 \leq N \leq 2 \cdot 10^5) – the size of the array A. The next line contains N non-negative integers – the array A itself (1 \leq A_i \leq N). The next line contains one integer Q (1 \leq Q \leq 10^5) – the number of queries. Each of the next Q lines contain two integers m and y (1 \leq m \leq 10^{18}, 1\leq y \leq N).OutputOutput exactly Q lines with a single integer in each that represent the solution. Output the solutions in the order the queries were asked in.ExampleInput 10 2 3 1 5 6 4 2 10 7 7 5 10 1 5 7 10 6 1 1 10 8 Output 3 0 1 1 0 NoteFor the first query we can notice that F(3, 10) = 1,\ F(9, 10) = 1 and F(10, 10) = 1.For the second query no x satisfies condition F(x, 5) = 7.For the third query F(5, 10) = 6 holds.For the fourth query F(3, 1) = 1.For the fifth query no x satisfies condition F(x, 10) = 8.
10 2 3 1 5 6 4 2 10 7 7 5 10 1 5 7 10 6 1 1 10 8
3 0 1 1 0
0.5 seconds
256 megabytes
['dfs and similar', '*2900']
G. Alpha planetary systemtime limit per test1 secondmemory limit per test128 megabytesinputstandard inputoutputstandard outputThree planets X, Y and Z within the Alpha planetary system are inhabited with an advanced civilization. The spaceports of these planets are connected by interplanetary space shuttles. The flight scheduler should decide between 1, 2 and 3 return flights for every existing space shuttle connection. Since the residents of Alpha are strong opponents of the symmetry, there is a strict rule that any two of the spaceports connected by a shuttle must have a different number of flights. For every pair of connected spaceports, your goal is to propose a number 1, 2 or 3 for each shuttle flight, so that for every two connected spaceports the overall number of flights differs. You may assume that:1) Every planet has at least one spaceport 2) There exist only shuttle flights between spaceports of different planets 3) For every two spaceports there is a series of shuttle flights enabling traveling between them4) Spaceports are not connected by more than one shuttleInputThe first row of the input is the integer number N (3 \leq N \leq 100 000), representing overall number of spaceports. The second row is the integer number M (2 \leq M \leq 100 000) representing number of shuttle flight connections. Third row contains N characters from the set \{X, Y, Z\}. Letter on I^{th} position indicates on which planet is situated spaceport I. For example, "XYYXZZ" indicates that the spaceports 0 and 3 are located at planet X, spaceports 1 and 2 are located at Y, and spaceports 4 and 5 are at Z. Starting from the fourth row, every row contains two integer numbers separated by a whitespace. These numbers are natural numbers smaller than N and indicate the numbers of the spaceports that are connected. For example, "12\ 15" indicates that there is a shuttle flight between spaceports 12 and 15. OutputThe same representation of shuttle flights in separate rows as in the input, but also containing a third number from the set \{1, 2, 3\} standing for the number of shuttle flights between these spaceports.ExampleInput 10 15 XXXXYYYZZZ 0 4 0 5 0 6 4 1 4 8 1 7 1 9 7 2 7 5 5 3 6 2 6 9 8 2 8 3 9 3 Output 0 4 2 0 5 2 0 6 2 4 1 1 4 8 1 1 7 2 1 9 3 7 2 2 7 5 1 5 3 1 6 2 1 6 9 1 8 2 3 8 3 1 9 3 1
10 15 XXXXYYYZZZ 0 4 0 5 0 6 4 1 4 8 1 7 1 9 7 2 7 5 5 3 6 2 6 9 8 2 8 3 9 3
0 4 2 0 5 2 0 6 2 4 1 1 4 8 1 1 7 2 1 9 3 7 2 2 7 5 1 5 3 1 6 2 1 6 9 1 8 2 3 8 3 1 9 3 1
1 second
128 megabytes
['constructive algorithms', 'graphs', 'shortest paths', '*3000']
F. Workout plantime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.InputThe first one contains two integer numbers, integers N (1 \leq N \leq 10^5) and K (1 \leq K \leq 10^5) – representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 \leq X[i] \leq 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 \leq A \leq 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 \leq C[i] \leq 10^9) , representing cost of performance booster drink in the gym he visits on day i.OutputOne integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.ExamplesInput 5 10000 10000 30000 30000 40000 20000 20000 5 2 8 3 6 Output 5 Input 5 10000 10000 40000 30000 30000 20000 10000 5 2 8 3 6 Output -1 NoteFirst example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
5 10000 10000 30000 30000 40000 20000 20000 5 2 8 3 6
5
1 second
256 megabytes
['data structures', 'greedy', '*1500']
E. Product Tuplestime limit per test8 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputWhile roaming the mystic areas of Stonefalls, in order to drop legendary loot, an adventurer was given a quest as follows. He was given an array A = {a_1,a_2,...,a_N } of length N, and a number K.Define array B as B(q, A) = { q-a_1, q-a_2, ..., q-a_N }. Define function F as F(B,K) being sum of products of all K-tuples of elements in array B. For example, if the array B is [2,3,4,5], and with K=3, sum of products of all 3-tuples is F(B, 3) = 2*3*4+2*3*5+3*4*5+2*4*5He was then given a number Q, number of queries of two types: Type 1: Given q, i, and d calculate F(B(q, A), K) where we make change to initial array as A[i] = d. Type 2: Given q, L, R, and d calculate F(B(q, A), K) where we make change to initial array as A[i] = A[i] + d for all i in range [L, R] inclusive. All changes are temporarily made to initial array, and don't propagate to following queries. Help the adventurer calculate the answer to a quest, and finally get that loot!InputIn the first two lines, numbers N (1 \leq N \leq 2*10^4) and K (1 \leq K \leq N), the length of initial array A, and tuple size, followed by a_1,a_2,a_3,…,a_N (0 \leq a_i \leq 10^9) , elements of array A, in the next line. Then follows number Q (Q \leq 10), number of queries. In the next Q lines come queries of the form: 1 q i d, for type 1, 2 q L R d, for type 2, as explained above (0 \leq q, d \leq 10^9, 1 \leq i,L,R \leq N)OutputPrint Q lines, the answers to queries, modulo 998244353.ExampleInput 5 2 1 2 3 4 5 3 1 6 1 1 1 6 5 2 2 6 2 3 1 Output 85 127 63 NoteIn the first query array A = [1, 2, 3, 4, 5], B = [5, 4, 3, 2, 1], sum of products of 2-tuples = 85.In second query array A = [1, 2, 3, 4, 2], B = [5, 4, 3, 2, 4], sum of products of 2-tuples = 127In third query array A = [1, 3, 4, 4, 5], B = [5, 3, 2, 2, 1], sum of products of 2-tuples = 63
5 2 1 2 3 4 5 3 1 6 1 1 1 6 5 2 2 6 2 3 1
85 127 63
8 seconds
128 megabytes
['divide and conquer', 'fft', '*2500']
D. Xor Spanning Treetime limit per test2 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputIn the galaxy far far away is the ancient interplanetary republic of Bubbleland, consisting of N planets. Between them, there are M bidirectional wormholes, each connecting a pair of planets. Bubbleland is a very centralized republic, having a capital planet Whiteplanet, from which any another planet can be reached using these wormholes. It is also guaranteed that no wormhole connects planet to itself and that no two different wormholes connect same pair of planets. We call a path that begins at one planet, visits other planets and each of them at most once and returns to starting point a tour. Interplanetary Safety Regulations guarantee that each planet belongs to at most one tour and that there are at most 42 tours.After many eons of usage, wormholes need to be repaired and each wormhole has the cost W_{i} which needs to be payed for reparation. Unfortunately, the Senate of Bubbleland is short on budget. Therefore, they have decided only to fix as many wormholes as they need in order to have all planets reachable from capital and to pay as little money as they have to for this repair. However the way in which the Senate calculates the cost is different. Cost of the set of reparations is binary xor of costs of each individual reparation, that is if reparations to be made have costs A_{1},A_{2},...,A_{k}, the cost of entire set is A_{1} \oplus A_{2} \oplus ... \oplus A_{k}.Now the Senate would like to know how much money do they have to pay and also the number of different ways to achieve that cost modulo 1000000007.InputFirst line of input contains two numbers N (1 \leq N \leq 100.000), the number of planets and M (1 \leq M \leq 100.041), the number of wormholes. Following M lines contain three numbers U, V (1 \leq U \neq V \leq N) and W (1 \leq W \leq 100.000), meaning that there exists a wormhole connecting planets U and V, with repair cost of W.OutputOutput two numbers, the smallest possible cost of entire reparation and the number of different valid reparations with that cost modulo 1000000007.ExampleInput 6 6 4 1 5 5 2 1 6 3 2 1 2 6 1 3 3 2 3 4 Output 1 1NoteWe can repair wormholes 1,2,3,5 and 6, paying 5 \oplus 1\oplus 2 \oplus 3 \oplus 4=1, one can check that this is the cheapest repair in which all of the planets are connected and the only valid repair with that cost.
6 6 4 1 5 5 2 1 6 3 2 1 2 6 1 3 3 2 3 4
1 1
2 seconds
128 megabytes
['divide and conquer', 'fft', 'graphs', '*2400']
C. Jumping Transformerstime limit per test4 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputYou, the mighty Blackout, are standing in the upper-left (0,0) corner of NxM matrix. You must move either right or down each second. There are K transformers jumping around the matrix in the following way. Each transformer starts jumping from position (x,y), at time t, and jumps to the next position each second. The x-axes grows downwards, and y-axes grows to the right. The order of jumping positions is defined as {(x,y),(x+d,y-d),(x+d,y),(x,y+d)}, and is periodic. Before time t transformer is not in the matrix.You want to arrive to the bottom-right corner (N-1,M-1), while slaying transformers and losing the least possible amount of energy. When you meet the transformer (or more of them) in the matrix field, you must kill them all, and you lose the sum of the energy amounts required to kill each transformer.After the transformer is killed, he of course stops jumping, falls into the abyss and leaves the matrix world. Output minimum possible amount of energy wasted.InputIn the first line, integers N,M (1 \leq N, M \leq 500), representing size of the matrix, and K (0 \leq K \leq 5*10^5) , the number of jumping transformers.In next K lines, for each transformer, numbers x, y, d (d \geq 1), t (0 \leq t \leq N+M-2), and e (0 \leq e \leq 10^9), representing starting coordinates of transformer, jumping positions distance in pattern described above, time when transformer starts jumping, and energy required to kill it.It is guaranteed that all 4 of jumping points of the transformers are within matrix coordinatesOutputPrint single integer, the minimum possible amount of energy wasted, for Blackout to arrive at bottom-right corner.ExampleInput 3 3 5 0 1 1 0 7 1 1 1 0 10 1 1 1 1 2 1 1 1 2 2 0 1 1 2 3 Output 9NoteIf Blackout takes the path from (0, 0) to (2, 0), and then from (2, 0) to (2, 2) he will need to kill the first and third transformer for a total energy cost of 9. There exists no path with less energy value.
3 3 5 0 1 1 0 7 1 1 1 0 10 1 1 1 1 2 1 1 1 2 2 0 1 1 2 3
9
4 seconds
128 megabytes
['dp', '*2600']
B. Guarding warehousestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob Bubblestrong just got a new job as security guard. Bob is now responsible for safety of a collection of warehouses, each containing the most valuable Bubble Cup assets - the high-quality bubbles. His task is to detect thieves inside the warehouses and call the police.Looking from the sky, each warehouse has a shape of a convex polygon. Walls of no two warehouses intersect, and of course, none of the warehouses is built inside of another warehouse.Little did the Bubble Cup bosses know how lazy Bob is and that he enjoys watching soap operas (he heard they are full of bubbles) from the coziness of his office. Instead of going from one warehouse to another to check if warehouses are secured, the plan Bob has is to monitor all the warehouses from the comfort of his office using the special X-ray goggles. The goggles have an infinite range, so a thief in any of the warehouses could easily be spotted.However, the goggles promptly broke and the X-rays are now strong only enough to let Bob see through a single wall. Now, Bob would really appreciate if you could help him find out what is the total area inside of the warehouses monitored by the broken goggles, so that he could know how much area of the warehouses he needs to monitor in person.InputThe first line contains one integer N (1 \leq N \leq 10^4) – the number of warehouses.The next N lines describe the warehouses.The first number of the line is integer c_i (3 \leq c_i \leq 10^4) – the number corners in the i^{th} warehouse, followed by c_i pairs of integers. The j^{th} pair is (x_j, y_j) – the coordinates of the j^{th} corner (|x_j|, |y_j| \leq 3 * 10^4). The corners are listed in the clockwise order. The total number of corners in all the warehouses is at most 5 * 10^4.Bob's office is positioned at the point with coordinates (0, 0). The office is not contained within any of the warehouses.OutputPrint a single line containing a single decimal number accurate to at least four decimal places – the total area of the warehouses Bob can monitor using the broken X-ray goggles.ExampleInput 5 4 1 1 1 3 3 3 3 1 4 4 3 6 2 6 0 4 0 6 -5 3 -4 4 -3 4 -2 3 -3 2 -4 2 3 0 -1 1 -3 -1 -3 4 1 -4 1 -6 -1 -6 -1 -4 Output 13.333333333333 Note Areas monitored by the X-ray goggles are colored green and areas not monitored by the goggles are colored red.The warehouses ABCD, IJK and LMNOPQ are completely monitored using the googles.The warehouse EFGH is partially monitored using the goggles: part EFW is not monitored because to monitor each point inside it, the X-rays must go through two walls of warehouse ABCD.The warehouse RUTS is not monitored from the Bob's office, because there are two walls of the warehouse IJK between Bob's office and each point in RUTS.The total area monitored by the goggles is P = P_{ABCD} + P_{FGHW} + P_{IJK} + P_{LMNOPQ} = 4 + 3.333333333333 + 2 + 4 = 13.333333333333.
5 4 1 1 1 3 3 3 3 1 4 4 3 6 2 6 0 4 0 6 -5 3 -4 4 -3 4 -2 3 -3 2 -4 2 3 0 -1 1 -3 -1 -3 4 1 -4 1 -6 -1 -6 -1 -4
13.333333333333
1 second
256 megabytes
['data structures', 'geometry', '*3000']
A. BubbleReactortime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are in charge of the BubbleReactor. It consists of N BubbleCores connected with N lines of electrical wiring. Each electrical wiring connects two distinct BubbleCores. There are no BubbleCores connected with more than one line of electrical wiring.Your task is to start the BubbleReactor by starting each BubbleCore. In order for a BubbleCore to be started it needs to be receiving power from a directly connected BubbleCore which is already started. However, you can kick-start one BubbleCore manually without needing power. It is guaranteed that all BubbleCores can be started.Before the BubbleCore boot up procedure its potential is calculated as the number of BubbleCores it can power on (the number of inactive BubbleCores which are connected to it directly or with any number of inactive BubbleCores in between, itself included)Start the BubbleReactor so that the sum of all BubbleCores' potentials is maximum.InputFirst line contains one integer N (3 \leq N \leq 15.000), the number of BubbleCores.The following N lines contain two integers U, V (0 \leq U \neq V < N) denoting that there exists electrical wiring between BubbleCores U and V.OutputSingle integer, the maximum sum of all BubbleCores' potentials.ExampleInput 10 0 1 0 3 0 4 0 9 1 2 2 3 2 7 4 5 4 6 7 8 Output 51 NoteIf we start by kickstarting BubbleCup 8 and then turning on cores 7, 2, 1, 3, 0, 9, 4, 5, 6 in that order we get potentials 10 + 9 + 8 + 7 + 6 + 5 + 1 + 3 + 1 + 1 = 51
10 0 1 0 3 0 4 0 9 1 2 2 3 2 7 4 5 4 6 7 8
51
1.5 seconds
256 megabytes
['dp', 'graphs', '*2800']
F. Forced Online Queries Problemtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph with n vertices numbered from 1 to n. Initially there are no edges.You are asked to perform some queries on the graph. Let last be the answer to the latest query of the second type, it is set to 0 before the first such query. Then the queries are the following: 1~x~y (1 \le x, y \le n, x \ne y) — add an undirected edge between the vertices (x + last - 1)~mod~n + 1 and (y + last - 1)~mod~n + 1 if it doesn't exist yet, otherwise remove it; 2~x~y (1 \le x, y \le n, x \ne y) — check if there exists a path between the vertices (x + last - 1)~mod~n + 1 and (y + last - 1)~mod~n + 1, which goes only through currently existing edges, and set last to 1 if so and 0 otherwise. Good luck!InputThe first line contains two integer numbers n and m (2 \le n, m \le 2 \cdot 10^5) — the number of vertices and the number of queries, respectively.Each of the following m lines contains a query of one of two aforementioned types. It is guaranteed that there is at least one query of the second type.OutputPrint a string, consisting of characters '0' and '1'. The i-th character should be the answer to the i-th query of the second type. Therefore the length of the string should be equal to the number of queries of the second type.ExamplesInput 5 9 1 1 2 1 1 3 2 3 2 1 2 4 2 3 4 1 2 4 2 3 4 1 1 3 2 4 3 Output 1010 Input 3 9 1 1 2 1 2 3 1 3 1 2 1 3 1 3 2 2 2 3 1 1 2 2 1 2 2 1 2 Output 1101 NoteThe converted queries in the first example are: 1 1 2 1 1 3 2 3 2 1 3 5 2 4 5 1 2 4 2 3 4 1 2 4 2 5 4 The converted queries in the second example are: 1 1 2 1 2 3 1 3 1 2 1 3 1 1 3 2 3 1 1 2 3 2 2 3 2 1 2
5 9 1 1 2 1 1 3 2 3 2 1 2 4 2 3 4 1 2 4 2 3 4 1 1 3 2 4 3
1010
5 seconds
256 megabytes
['data structures', 'divide and conquer', 'dsu', 'graphs', 'trees', '*2600']
E. Sum Queries?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a balanced multiset the following way. Write down the sum of all elements of the multiset in its decimal representation. For each position of that number check if the multiset includes at least one element such that the digit of the element and the digit of the sum at that position are the same. If that holds for every position, then the multiset is balanced. Otherwise it's unbalanced.For example, multiset \{20, 300, 10001\} is balanced and multiset \{20, 310, 10001\} is unbalanced: The red digits mark the elements and the positions for which these elements have the same digit as the sum. The sum of the first multiset is 10321, every position has the digit required. The sum of the second multiset is 10331 and the second-to-last digit doesn't appear in any number, thus making the multiset unbalanced.You are given an array a_1, a_2, \dots, a_n, consisting of n integers.You are asked to perform some queries on it. The queries can be of two types: 1~i~x — replace a_i with the value x; 2~l~r — find the unbalanced subset of the multiset of the numbers a_l, a_{l + 1}, \dots, a_r with the minimum sum, or report that no unbalanced subset exists. Note that the empty multiset is balanced.For each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.InputThe first line contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the number of elements in the array and the number of queries, respectively.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i < 10^9).Each of the following m lines contains a query of one of two types: 1~i~x (1 \le i \le n, 1 \le x < 10^9) — replace a_i with the value x; 2~l~r (1 \le l \le r \le n) — find the unbalanced subset of the multiset of the numbers a_l, a_{l + 1}, \dots, a_r with the lowest sum, or report that no unbalanced subset exists. It is guaranteed that there is at least one query of the second type.OutputFor each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.ExampleInput 4 5 300 10001 20 20 2 1 3 1 1 310 2 1 3 2 3 3 2 3 4 Output -1 330 -1 40 NoteAll the subsets of multiset \{20, 300, 10001\} are balanced, thus the answer is -1.The possible unbalanced subsets in the third query are \{20, 310\} and \{20, 310, 10001\}. The lowest sum one is \{20, 310\}. Note that you are asked to choose a subset, not a subsegment, thus the chosen elements might not be adjancent in the array.The fourth query includes only the empty subset and subset \{20\}. Both of them are balanced.The last query includes the empty subset and the subsets \{20\}, \{20\} and \{20, 20\}. Only \{20, 20\} is unbalanced, its sum is 40. Note that you are asked to choose a multiset, thus it might include equal elements.
4 5 300 10001 20 20 2 1 3 1 1 310 2 1 3 2 3 3 2 3 4
-1 330 -1 40
2 seconds
256 megabytes
['data structures', 'greedy', 'implementation', 'math', '*2300']
D. Coloring Edgestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a directed graph with n vertices and m directed edges without self-loops or multiple edges.Let's denote the k-coloring of a digraph as following: you color each edge in one of k colors. The k-coloring is good if and only if there no cycle formed by edges of same color.Find a good k-coloring of given digraph with minimum possible k.InputThe first line contains two integers n and m (2 \le n \le 5000, 1 \le m \le 5000) — the number of vertices and edges in the digraph, respectively.Next m lines contain description of edges — one per line. Each edge is a pair of integers u and v (1 \le u, v \le n, u \ne v) — there is directed edge from u to v in the graph.It is guaranteed that each ordered pair (u, v) appears in the list of edges at most once.OutputIn the first line print single integer k — the number of used colors in a good k-coloring of given graph.In the second line print m integers c_1, c_2, \dots, c_m (1 \le c_i \le k), where c_i is a color of the i-th edge (in order as they are given in the input).If there are multiple answers print any of them (you still have to minimize k).ExamplesInput 4 5 1 2 1 3 3 4 2 4 1 4 Output 1 1 1 1 1 1 Input 3 3 1 2 2 3 3 1 Output 2 1 1 2
4 5 1 2 1 3 3 4 2 4 1 4
1 1 1 1 1 1
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', '*2100']
C. The Number Of Good Substringstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string s (recall that a string is binary if each character is either 0 or 1).Let f(t) be the decimal representation of integer t written in binary form (possibly with leading zeroes). For example f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0 and f(000100) = 4.The substring s_{l}, s_{l+1}, \dots , s_{r} is good if r - l + 1 = f(s_l \dots s_r).For example string s = 1011 has 5 good substrings: s_1 \dots s_1 = 1, s_3 \dots s_3 = 1, s_4 \dots s_4 = 1, s_1 \dots s_2 = 10 and s_2 \dots s_4 = 011. Your task is to calculate the number of good substrings of string s.You have to answer t independent queries.InputThe first line contains one integer t (1 \le t \le 1000) — the number of queries.The only line of each query contains string s (1 \le |s| \le 2 \cdot 10^5), consisting of only digits 0 and 1.It is guaranteed that \sum\limits_{i=1}^{t} |s_i| \le 2 \cdot 10^5.OutputFor each query print one integer — the number of good substrings of string s.ExampleInput 4 0110 0101 00001000 0001000 Output 4 3 4 3
4 0110 0101 00001000 0001000
4 3 4 3
4 seconds
256 megabytes
['binary search', 'bitmasks', 'brute force', '*1700']
B. Zmei Gorynichtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads! Initially Zmei Gorynich has x heads. You can deal n types of blows. If you deal a blow of the i-th type, you decrease the number of Gorynich's heads by min(d_i, curX), there curX is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows h_i new heads. If curX = 0 then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if curX = 10, d = 7, h = 10 then the number of heads changes to 13 (you cut 7 heads off, but then Zmei grows 10 new ones), but if curX = 10, d = 11, h = 100 then number of heads changes to 0 and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer t independent queries.InputThe first line contains one integer t (1 \le t \le 100) – the number of queries.The first line of each query contains two integers n and x (1 \le n \le 100, 1 \le x \le 10^9) — the number of possible types of blows and the number of heads Zmei initially has, respectively.The following n lines of each query contain the descriptions of types of blows you can deal. The i-th line contains two integers d_i and h_i (1 \le d_i, h_i \le 10^9) — the description of the i-th blow.OutputFor each query print the minimum number of blows you have to deal to defeat Zmei Gorynich. If Zmei Gorynuch cannot be defeated print -1.ExampleInput 3 3 10 6 3 8 2 1 4 4 10 4 1 3 2 2 6 1 100 2 15 10 11 14 100 Output 2 3 -1 NoteIn the first query you can deal the first blow (after that the number of heads changes to 10 - 6 + 3 = 7), and then deal the second blow.In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?
3 3 10 6 3 8 2 1 4 4 10 4 1 3 2 2 6 1 100 2 15 10 11 14 100
2 3 -1
1 second
256 megabytes
['greedy', 'math', '*1600']
A. Creating a Charactertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou play your favourite game yet another time. You chose the character you didn't play before. It has str points of strength and int points of intelligence. Also, at start, the character has exp free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by 1 or raise intelligence by 1).Since you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is strictly greater than the resulting intelligence).Calculate the number of different character builds you can create (for the purpose of replayability) if you must invest all free points. Two character builds are different if their strength and/or intellect are different.InputThe first line contains the single integer T (1 \le T \le 100) — the number of queries. Next T lines contain descriptions of queries — one per line.This line contains three integers str, int and exp (1 \le str, int \le 10^8, 0 \le exp \le 10^8) — the initial strength and intelligence of the character and the number of free points, respectively.OutputPrint T integers — one per query. For each query print the number of different character builds you can create.ExampleInput 4 5 3 4 2 1 0 3 5 5 4 10 6 Output 3 1 2 0 NoteIn the first query there are only three appropriate character builds: (str = 7, int = 5), (8, 4) and (9, 3). All other builds are either too smart or don't use all free points.In the second query there is only one possible build: (2, 1).In the third query there are two appropriate builds: (7, 6), (8, 5).In the fourth query all builds have too much brains.
4 5 3 4 2 1 0 3 5 5 4 10 6
3 1 2 0
1 second
256 megabytes
['binary search', 'math', '*1300']
F. Wi-Fitime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou work as a system administrator in a dormitory, which has n rooms one after another along a straight hallway. Rooms are numbered from 1 to n.You have to connect all n rooms to the Internet.You can connect each room to the Internet directly, the cost of such connection for the i-th room is i coins. Some rooms also have a spot for a router. The cost of placing a router in the i-th room is also i coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room i, you connect all rooms with the numbers from max(1,~i - k) to min(n,~i + k) inclusive to the Internet, where k is the range of router. The value of k is the same for all routers. Calculate the minimum total cost of connecting all n rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have.InputThe first line of the input contains two integers n and k (1 \le n, k \le 2 \cdot 10^5) — the number of rooms and the range of each router.The second line of the input contains one string s of length n, consisting only of zeros and ones. If the i-th character of the string equals to '1' then there is a spot for a router in the i-th room. If the i-th character of the string equals to '0' then you cannot place a router in the i-th room.OutputPrint one integer — the minimum total cost of connecting all n rooms to the Internet.ExamplesInput 5 2 00100 Output 3 Input 6 1 000000 Output 21 Input 4 1 0011 Output 4 Input 12 6 000010000100 Output 15 NoteIn the first example it is enough to place the router in the room 3, then all rooms will be connected to the Internet. The total cost of connection is 3.In the second example you can place routers nowhere, so you need to connect all rooms directly. Thus, the total cost of connection of all rooms is 1 + 2 + 3 + 4 + 5 + 6 = 21.In the third example you need to connect the room 1 directly and place the router in the room 3. Thus, the total cost of connection of all rooms is 1 + 3 = 4.In the fourth example you need to place routers in rooms 5 and 10. Then all rooms will be connected to the Internet. The total cost of connection is 5 + 10 = 15.
5 2 00100
3
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', '*2100']
E2. Numerical Sequence (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the easy and the hard versions is the maximum value of k.You are given an infinite sequence of form "112123123412345\dots" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, \dots, the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.InputThe first line of the input contains one integer q (1 \le q \le 500) — the number of queries.The i-th of the following q lines contains one integer k_i (1 \le k_i \le 10^{18}) — the description of the corresponding query.OutputPrint q lines. In the i-th line print one digit x_i (0 \le x_i \le 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.ExamplesInput 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 NoteAnswers on queries from the first example are described in the problem statement.
5 1 3 20 38 56
1 2 5 2 0
2 seconds
256 megabytes
['binary search', 'math', '*2200']
E1. Numerical Sequence (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the easy and the hard versions is the maximum value of k.You are given an infinite sequence of form "112123123412345\dots" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, \dots, the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.InputThe first line of the input contains one integer q (1 \le q \le 500) — the number of queries.The i-th of the following q lines contains one integer k_i (1 \le k_i \le 10^9) — the description of the corresponding query.OutputPrint q lines. In the i-th line print one digit x_i (0 \le x_i \le 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.ExamplesInput 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999 1000000000 Output 8 2 9 8 NoteAnswers on queries from the first example are described in the problem statement.
5 1 3 20 38 56
1 2 5 2 0
2 seconds
256 megabytes
['binary search', 'brute force', 'math', '*1900']
D. Swordstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere were n types of swords in the theater basement which had been used during the plays. Moreover there were exactly x swords of each type. y people have broken into the theater basement and each of them has taken exactly z swords of some single type. Note that different people might have taken different types of swords. Note that the values x, y and z are unknown for you.The next morning the director of the theater discovers the loss. He counts all swords — exactly a_i swords of the i-th type are left untouched.The director has no clue about the initial number of swords of each type in the basement, the number of people who have broken into the basement and how many swords each of them have taken.For example, if n=3, a = [3, 12, 6] then one of the possible situations is x=12, y=5 and z=3. Then the first three people took swords of the first type and the other two people took swords of the third type. Note that you don't know values x, y and z beforehand but know values of n and a.Thus he seeks for your help. Determine the minimum number of people y, which could have broken into the theater basement, and the number of swords z each of them has taken.InputThe first line of the input contains one integer n (2 \le n \le 2 \cdot 10^{5}) — the number of types of swords.The second line of the input contains the sequence a_1, a_2, \dots, a_n (0 \le a_i \le 10^{9}), where a_i equals to the number of swords of the i-th type, which have remained in the basement after the theft. It is guaranteed that there exists at least one such pair of indices (j, k) that a_j \neq a_k.OutputPrint two integers y and z — the minimum number of people which could have broken into the basement and the number of swords each of them has taken.ExamplesInput 3 3 12 6 Output 5 3 Input 2 2 9 Output 1 7 Input 7 2 1000000000 4 6 8 4 2 Output 2999999987 2 Input 6 13 52 0 13 26 52 Output 12 13 NoteIn the first example the minimum value of y equals to 5, i.e. the minimum number of people who could have broken into the basement, is 5. Each of them has taken 3 swords: three of them have taken 3 swords of the first type, and two others have taken 3 swords of the third type.In the second example the minimum value of y is 1, i.e. the minimum number of people who could have broken into the basement, equals to 1. He has taken 7 swords of the first type.
3 3 12 6
5 3
2 seconds
256 megabytes
['math', '*1300']
C. White Sheettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates (0, 0), and coordinate axes are left and bottom sides of the table, then the bottom left corner of the white sheet has coordinates (x_1, y_1), and the top right — (x_2, y_2).After that two black sheets of paper are placed on the table. Sides of both black sheets are also parallel to the sides of the table. Coordinates of the bottom left corner of the first black sheet are (x_3, y_3), and the top right — (x_4, y_4). Coordinates of the bottom left corner of the second black sheet are (x_5, y_5), and the top right — (x_6, y_6). Example of three rectangles. Determine if some part of the white sheet can be seen from the above after the two black sheets are placed. The part of the white sheet can be seen if there is at least one point lying not strictly inside the white sheet and strictly outside of both black sheets.InputThe first line of the input contains four integers x_1, y_1, x_2, y_2 (0 \le x_1 < x_2 \le 10^{6}, 0 \le y_1 < y_2 \le 10^{6}) — coordinates of the bottom left and the top right corners of the white sheet.The second line of the input contains four integers x_3, y_3, x_4, y_4 (0 \le x_3 < x_4 \le 10^{6}, 0 \le y_3 < y_4 \le 10^{6}) — coordinates of the bottom left and the top right corners of the first black sheet.The third line of the input contains four integers x_5, y_5, x_6, y_6 (0 \le x_5 < x_6 \le 10^{6}, 0 \le y_5 < y_6 \le 10^{6}) — coordinates of the bottom left and the top right corners of the second black sheet.The sides of each sheet of paper are parallel (perpendicular) to the coordinate axes.OutputIf some part of the white sheet can be seen from the above after the two black sheets are placed, print "YES" (without quotes). Otherwise print "NO".ExamplesInput 2 2 4 4 1 1 3 5 3 1 5 5 Output NO Input 3 3 7 5 0 0 4 6 0 0 7 4 Output YES Input 5 2 10 5 3 1 7 6 8 1 11 7 Output YES Input 0 0 1000000 1000000 0 0 499999 1000000 500000 0 1000000 1000000 Output YES NoteIn the first example the white sheet is fully covered by black sheets.In the second example the part of the white sheet can be seen after two black sheets are placed. For example, the point (6.5, 4.5) lies not strictly inside the white sheet and lies strictly outside of both black sheets.
2 2 4 4 1 1 3 5 3 1 5 5
NO
1 second
256 megabytes
['geometry', 'math', '*1700']
B. Shootingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down.Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i \cdot x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down.Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible.InputThe first line of the input contains one integer n (2 \le n \le 1\,000) — the number of cans.The second line of the input contains the sequence a_1, a_2, \dots, a_n (1 \le a_i \le 1\,000), where a_i is the durability of the i-th can.OutputIn the first line print the minimum number of shots required to knock each of the n given cans down exactly once.In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them.ExamplesInput 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 NoteIn the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 \cdot 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 \cdot 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43.In the second example the order of shooting does not matter because all cans have the same durability.
3 20 10 20
43 1 3 2
1 second
256 megabytes
['greedy', 'implementation', 'sortings', '*900']
A. Prefixestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay got a string s of even length n, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from 1 to n.He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arbitrary number of times (possibly, zero): choose some position in his string and replace the letter on this position with the other letter (i.e. replace 'a' with 'b' or replace 'b' with 'a'). Nikolay can use no letters except 'a' and 'b'.The prefix of string s of length l (1 \le l \le n) is a string s[1..l].For example, for the string s="abba" there are two prefixes of the even length. The first is s[1\dots2]="ab" and the second s[1\dots4]="abba". Both of them have the same number of 'a' and 'b'.Your task is to calculate the minimum number of operations Nikolay has to perform with the string s to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'.InputThe first line of the input contains one even integer n (2 \le n \le 2\cdot10^{5}) — the length of string s.The second line of the input contains the string s of length n, which consists only of lowercase Latin letters 'a' and 'b'.OutputIn the first line print the minimum number of operations Nikolay has to perform with the string s to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'.In the second line print the string Nikolay obtains after applying all the operations. If there are multiple answers, you can print any of them.ExamplesInput 4 bbbb Output 2 abba Input 6 ababab Output 0 ababab Input 2 aa Output 1 ba NoteIn the first example Nikolay has to perform two operations. For example, he can replace the first 'b' with 'a' and the last 'b' with 'a'. In the second example Nikolay doesn't need to do anything because each prefix of an even length of the initial string already contains an equal amount of letters 'a' and 'b'.
4 bbbb
2 abba
1 second
256 megabytes
['strings', '*800']
F. Radio Stationstime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn addition to complaints about lighting, a lot of complaints about insufficient radio signal covering has been received by Bertown city hall recently. n complaints were sent to the mayor, all of which are suspiciosly similar to each other: in the i-th complaint, one of the radio fans has mentioned that the signals of two radio stations x_i and y_i are not covering some parts of the city, and demanded that the signal of at least one of these stations can be received in the whole city.Of cousre, the mayor of Bertown is currently working to satisfy these complaints. A new radio tower has been installed in Bertown, it can transmit a signal with any integer power from 1 to M (let's denote the signal power as f). The mayor has decided that he will choose a set of radio stations and establish a contract with every chosen station. To establish a contract with the i-th station, the following conditions should be met: the signal power f should be not less than l_i, otherwise the signal of the i-th station won't cover the whole city; the signal power f should be not greater than r_i, otherwise the signal will be received by the residents of other towns which haven't established a contract with the i-th station. All this information was already enough for the mayor to realise that choosing the stations is hard. But after consulting with specialists, he learned that some stations the signals of some stations may interfere with each other: there are m pairs of stations (u_i, v_i) that use the same signal frequencies, and for each such pair it is impossible to establish contracts with both stations. If stations x and y use the same frequencies, and y and z use the same frequencies, it does not imply that x and z use the same frequencies.The mayor finds it really hard to analyze this situation, so he hired you to help him. You have to choose signal power f and a set of stations to establish contracts with such that: all complaints are satisfied (formally, for every i \in [1, n] the city establishes a contract either with station x_i, or with station y_i); no two chosen stations interfere with each other (formally, for every i \in [1, m] the city does not establish a contract either with station u_i, or with station v_i); for each chosen station, the conditions on signal power are met (formally, for each chosen station i the condition l_i \le f \le r_i is met). InputThe first line contains 4 integers n, p, M and m (2 \le n, p, M, m \le 4 \cdot 10^5) — the number of complaints, the number of radio stations, maximum signal power and the number of interfering pairs, respectively.Then n lines follow, which describe the complains. Each line contains two integers x_i and y_i (1 \le x_i < y_i \le p) — the indices of the radio stations mentioned in the i-th complaint). All complaints are distinct.Then p lines follow, which describe the radio stations. Each line contains two integers l_i and r_i (1 \le l_i \le r_i \le M) — the constrains on signal power that should be satisfied if the city establishes a contract with the i-th station.Then m lines follow, which describe the pairs of interfering radio stations. Each line contains two integers u_i and v_i (1 \le u_i < v_i \le p) — the indices of interfering radio stations. All these pairs are distinct.OutputIf it is impossible to choose signal power and a set of stations to meet all conditions, print -1.Otherwise print two integers k and f in the first line — the number of stations in the chosen set and the chosen signal power, respectively. In the second line print k distinct integers from 1 to p — the indices of stations to establish contracts with (in any order). If there are multiple answers, print any of them; you don't have to minimize/maximize the number of chosen stations, and the same applies to signal power.ExamplesInput 2 4 4 2 1 3 2 3 1 4 1 2 3 4 1 4 1 2 3 4 Output 2 3 1 3 Input 2 4 4 2 1 3 2 4 1 2 1 2 3 4 3 4 1 2 3 4 Output -1
2 4 4 2 1 3 2 3 1 4 1 2 3 4 1 4 1 2 3 4
2 3 1 3
7 seconds
256 megabytes
['2-sat', '*2700']
E. Marblestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp has arranged n colored marbles in a row. The color of the i-th marble is a_i. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color). In other words, Monocarp wants to rearrange marbles so that, for every color j, if the leftmost marble of color j is l-th in the row, and the rightmost marble of this color has position r in the row, then every marble from l to r has color j.To achieve his goal, Monocarp can do the following operation any number of times: choose two neighbouring marbles, and swap them.You have to calculate the minimum number of operations Monocarp has to perform to rearrange the marbles. Note that the order of segments of marbles having equal color does not matter, it is only required that, for every color, all the marbles of this color form exactly one contiguous segment.InputThe first line contains one integer n (2 \le n \le 4 \cdot 10^5) — the number of marbles.The second line contains an integer sequence a_1, a_2, \dots, a_n (1 \le a_i \le 20), where a_i is the color of the i-th marble.OutputPrint the minimum number of operations Monocarp has to perform to achieve his goal.ExamplesInput 7 3 4 2 3 4 2 2 Output 3 Input 5 20 1 14 10 2 Output 0 Input 13 5 5 4 4 3 5 7 6 5 4 4 6 5 Output 21 NoteIn the first example three operations are enough. Firstly, Monocarp should swap the third and the fourth marbles, so the sequence of colors is [3, 4, 3, 2, 4, 2, 2]. Then Monocarp should swap the second and the third marbles, so the sequence is [3, 3, 4, 2, 4, 2, 2]. And finally, Monocarp should swap the fourth and the fifth marbles, so the sequence is [3, 3, 4, 4, 2, 2, 2]. In the second example there's no need to perform any operations.
7 3 4 2 3 4 2 2
3
4 seconds
256 megabytes
['bitmasks', 'dp', '*2200']
D. Ticket Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp and Bicarp live in Berland, where every bus ticket consists of n digits (n is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first \frac{n}{2} digits of this ticket is equal to the sum of the last \frac{n}{2} digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from 0 to 9. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally.InputThe first line contains one even integer n (2 \le n \le 2 \cdot 10^{5}) — the number of digits in the ticket.The second line contains a string of n digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the i-th character is "?", then the i-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even.OutputIf Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes).ExamplesInput 4 0523 Output Bicarp Input 2 ?? Output Bicarp Input 8 ?054??0? Output Bicarp Input 6 ???00? Output Monocarp NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy.
4 0523
Bicarp
1 second
256 megabytes
['games', 'greedy', 'math', '*1700']
C. Swap Letterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp has got two strings s and t having equal length. Both strings consist of lowercase Latin letters "a" and "b". Monocarp wants to make these two strings s and t equal to each other. He can do the following operation any number of times: choose an index pos_1 in the string s, choose an index pos_2 in the string t, and swap s_{pos_1} with t_{pos_2}.You have to determine the minimum number of operations Monocarp has to perform to make s and t equal, and print any optimal sequence of operations — or say that it is impossible to make these strings equal.InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^{5}) — the length of s and t.The second line contains one string s consisting of n characters "a" and "b". The third line contains one string t consisting of n characters "a" and "b". OutputIf it is impossible to make these strings equal, print -1.Otherwise, in the first line print k — the minimum number of operations required to make the strings equal. In each of the next k lines print two integers — the index in the string s and the index in the string t that should be used in the corresponding swap operation. ExamplesInput 4 abab aabb Output 2 3 3 3 2 Input 1 a b Output -1 Input 8 babbaabb abababaa Output 3 2 6 1 3 7 8 NoteIn the first example two operations are enough. For example, you can swap the third letter in s with the third letter in t. Then s = "abbb", t = "aaab". Then swap the third letter in s and the second letter in t. Then both s and t are equal to "abab".In the second example it's impossible to make two strings equal.
4 abab aabb
2 3 3 3 2
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*1500']
B. The Number of Productstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a_1, a_2, \dots, a_n consisting of n non-zero integers (i.e. a_i \ne 0). You have to calculate two following values: the number of pairs of indices (l, r) (l \le r) such that a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r is negative; the number of pairs of indices (l, r) (l \le r) such that a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r is positive; InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^{5}) — the number of elements in the sequence.The second line contains n integers a_1, a_2, \dots, a_n (-10^{9} \le a_i \le 10^{9}; a_i \neq 0) — the elements of the sequence.OutputPrint two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.ExamplesInput 5 5 -3 3 -1 1 Output 8 7 Input 10 4 2 -4 3 1 2 -4 3 2 3 Output 28 27 Input 5 -1 -2 -3 -4 -5 Output 9 6
5 5 -3 3 -1 1
8 7
2 seconds
256 megabytes
['combinatorics', 'dp', 'implementation', '*1400']
A. Yellow Cardstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe final match of the Berland Football Cup has been held recently. The referee has shown n yellow cards throughout the match. At the beginning of the match there were a_1 players in the first team and a_2 players in the second team.The rules of sending players off the game are a bit different in Berland football. If a player from the first team receives k_1 yellow cards throughout the match, he can no longer participate in the match — he's sent off. And if a player from the second team receives k_2 yellow cards, he's sent off. After a player leaves the match, he can no longer receive any yellow cards. Each of n yellow cards was shown to exactly one player. Even if all players from one team (or even from both teams) leave the match, the game still continues.The referee has lost his records on who has received each yellow card. Help him to determine the minimum and the maximum number of players that could have been thrown out of the game.InputThe first line contains one integer a_1 (1 \le a_1 \le 1\,000) — the number of players in the first team.The second line contains one integer a_2 (1 \le a_2 \le 1\,000) — the number of players in the second team.The third line contains one integer k_1 (1 \le k_1 \le 1\,000) — the maximum number of yellow cards a player from the first team can receive (after receiving that many yellow cards, he leaves the game).The fourth line contains one integer k_2 (1 \le k_2 \le 1\,000) — the maximum number of yellow cards a player from the second team can receive (after receiving that many yellow cards, he leaves the game).The fifth line contains one integer n (1 \le n \le a_1 \cdot k_1 + a_2 \cdot k_2) — the number of yellow cards that have been shown during the match.OutputPrint two integers — the minimum and the maximum number of players that could have been thrown out of the game.ExamplesInput 2 3 5 1 8 Output 0 4 Input 3 1 6 7 25 Output 4 4 Input 6 4 9 10 89 Output 5 9 NoteIn the first example it could be possible that no player left the game, so the first number in the output is 0. The maximum possible number of players that could have been forced to leave the game is 4 — one player from the first team, and three players from the second.In the second example the maximum possible number of yellow cards has been shown (3 \cdot 6 + 1 \cdot 7 = 25), so in any case all players were sent off.
2 3 5 1 8
0 4
1 second
256 megabytes
['greedy', 'implementation', 'math', '*1000']
H. Tiles Placementtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe new pedestrian zone in Moscow city center consists of n squares connected with each other by n - 1 footpaths. We define a simple path as a sequence of squares such that no square appears in this sequence twice and any two adjacent squares in this sequence are directly connected with a footpath. The size of a simple path is the number of squares in it. The footpaths are designed in a such a way that there is exactly one simple path between any pair of different squares.During preparations for Moscow City Day the city council decided to renew ground tiles on all n squares. There are k tile types of different colors, numbered from 1 to k. For each square exactly one tile type must be selected and then used to cover this square surface. To make walking through the city center more fascinating, it was decided to select tiles types for each square in such a way that any possible simple path of size exactly k contains squares with all k possible tile colors.You need to find out whether it is possible to place the tiles this way or not.InputThe first line contains two integers n, k (2 \le k \le n \le 200\,000) — the number of squares in the new pedestrian zone, the number of different tile colors.Each of the following n - 1 lines contains two integers v_i and u_i (1 \le v_i, u_i \le n) — numbers of the squares connected by the corresponding road.It's guaranteed, that it's possible to go from any square to any other square, moreover there is exactly one such simple path.OutputPrint "Yes" if it is possible to assign tile colors this way and "No" otherwise.In case your answer is "Yes", print n integers from 1 to k each, the color of the tile for every square.ExamplesInput 7 4 1 3 2 3 3 4 4 5 5 6 5 7 Output Yes 1 1 2 3 4 1 1 Input 7 3 1 3 2 3 3 4 4 5 5 6 5 7 Output No NoteThe following pictures illustrate the pedestrian zone in first and second examples. The second picture also shows one possible distribution of colors among the squares for k = 4.
7 4 1 3 2 3 3 4 4 5 5 6 5 7
Yes 1 1 2 3 4 1 1
3 seconds
512 megabytes
['constructive algorithms', 'dfs and similar', 'trees', '*2800']
G. Feeling Goodtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRecently biologists came to a fascinating conclusion about how to find a chameleon mood. Consider chameleon body to be a rectangular table n \times m, each cell of which may be green or blue and may change between these two colors. We will denote as (x, y) (1 \leq x \leq n, 1 \leq y \leq m) the cell in row x and column y.Let us define a chameleon good mood certificate to be four cells which are corners of some subrectangle of the table, such that colors in opposite cells among these four are similar, and at the same time not all of the four cell colors are similar. Formally, it is a group of four cells (x_1, y_1), (x_1, y_2), (x_2, y_1), (x_2, y_2) for some 1 \leq x_1 < x_2 \leq n, 1 \leq y_1 < y_2 \leq m, that colors of (x_1, y_1) and (x_2, y_2) coincide and colors of (x_1, y_2) and (x_2, y_1) coincide, but not all of the four cells share the same color. It was found that whenever such four cells are present, chameleon is in good mood, and vice versa: if there are no such four cells, chameleon is in bad mood.You are asked to help scientists write a program determining the mood of chameleon. Let us consider that initially all cells of chameleon are green. After that chameleon coloring may change several times. On one change, colors of contiguous segment of some table row are replaced with the opposite. Formally, each color change is defined by three integers a, l, r (1 \leq a \leq n, 1 \leq l \leq r \leq m). On such change colors of all cells (a, b) such that l \leq b \leq r are replaced with the opposite.Write a program that reports mood of the chameleon after each change. Additionally, if the chameleon mood is good, program should find out any four numbers x_1, y_1, x_2, y_2 such that four cells (x_1, y_1), (x_1, y_2), (x_2, y_1), (x_2, y_2) are the good mood certificate.InputThe first line of input contains three integers n, m, q (1 \leq n, m \leq 2000, 1 \leq q \leq 500\,000), the sizes of the table and the number of changes respectively. Each of the following q lines contains 3 integers a_i, l_i, r_i (1 \leq a_i \leq n, 1 \leq l_i \leq r_i \leq m), describing i-th coloring change.OutputPrint q lines. In the i-th line report the chameleon mood after first i color changes for all 1 \leq i \leq q.If chameleon is in bad mood, print the only integer -1.Otherwise, print four integers x_1, y_1, x_2, y_2 (1 \leq x_1 < x_2 \leq n, 1 \leq y_1 < y_2 \leq m) such that four cells (x_1, y_1), (x_1, y_2), (x_2, y_1), (x_2, y_2) are the good mood certificate. If there are several ways to choose such four integers, print any valid one.ExamplesInput 2 2 6 1 1 1 2 2 2 2 1 1 1 2 2 2 2 2 1 1 1 Output -1 1 1 2 2 -1 -1 -1 1 1 2 2 Input 4 3 9 2 2 3 4 1 2 2 1 3 3 2 2 3 1 3 1 2 2 4 2 3 1 1 3 3 1 3 Output -1 2 1 4 3 -1 2 1 3 2 3 2 4 3 1 1 2 2 1 1 2 2 -1 2 1 3 2
2 2 6 1 1 1 2 2 2 2 1 1 1 2 2 2 2 2 1 1 1
-1 1 1 2 2 -1 -1 -1 1 1 2 2
3 seconds
512 megabytes
['bitmasks', 'data structures', '*3200']
F. Employmenttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputTwo large companies "Cecsi" and "Poca Pola" are fighting against each other for a long time. In order to overcome their competitor, "Poca Pola" started a super secret project, for which it has total n vacancies in all of their offices. After many tests and interviews n candidates were selected and the only thing left was their employment.Because all candidates have the same skills, it doesn't matter where each of them will work. That is why the company decided to distribute candidates between workplaces so that the total distance between home and workplace over all candidates is minimal.It is well known that Earth is round, so it can be described as a circle, and all m cities on Earth can be described as points on this circle. All cities are enumerated from 1 to m so that for each i (1 \le i \le m - 1) cities with indexes i and i + 1 are neighbors and cities with indexes 1 and m are neighbors as well. People can move only along the circle. The distance between any two cities equals to minimal number of transitions between neighboring cities you have to perform to get from one city to another. In particular, the distance between the city and itself equals 0.The "Poca Pola" vacancies are located at offices in cities a_1, a_2, \ldots, a_n. The candidates live in cities b_1, b_2, \ldots, b_n. It is possible that some vacancies are located in the same cities and some candidates live in the same cities. The "Poca Pola" managers are too busy with super secret project, so you were asked to help "Poca Pola" to distribute candidates between workplaces, so that the sum of the distance between home and workplace over all candidates is minimum possible.InputThe first line contains two integers m and n (1 \le m \le 10^9, 1 \le n \le 200\,000) — the number of cities on Earth and the number of vacancies.The second line contains n integers a_1, a_2, a_3, \ldots, a_n (1 \le a_i \le m) — the cities where vacancies are located.The third line contains n integers b_1, b_2, b_3, \ldots, b_n (1 \le b_i \le m) — the cities where the candidates live.OutputThe first line should contain the minimum total distance between home and workplace over all candidates.The second line should contain n different integers from 1 to n. The i-th of them should be the index of candidate that should work at i-th workplace.ExamplesInput 10 3 1 5 5 10 4 6 Output 3 1 2 3 Input 10 3 1 4 8 8 3 6 Output 4 2 3 1 NoteIn the first example, the distance between each candidate and his workplace equals to 1 (from 1 to 10, from 4 to 5 and from 6 to 5).In the second example: The second candidate works at first workplace, the distance between cities 3 and 1 equals to 2. The third candidate works at second workplace, the distance between cities 6 and 4 equals to 2. The first candidate works at third workplace, the distance between cities 8 and 8 equals to 0.
10 3 1 5 5 10 4 6
3 1 2 3
2 seconds
512 megabytes
['greedy', 'sortings', '*2700']
E. Petya and Construction Settime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputIt's Petya's birthday party and his friends have presented him a brand new "Electrician-n" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him.Construction set "Electrician-n" consists of 2n - 1 wires and 2n light bulbs. Each bulb has its own unique index that is an integer from 1 to 2n, while all wires look the same and are indistinguishable. In order to complete this construction set one has to use each of the wires to connect two distinct bulbs. We define a chain in a completed construction set as a sequence of distinct bulbs of length at least two, such that every two consecutive bulbs in this sequence are directly connected by a wire. Completed construction set configuration is said to be correct if a resulting network of bulbs and wires has a tree structure, i.e. any two distinct bulbs are the endpoints of some chain.Petya was assembling different configurations for several days, and he noticed that sometimes some of the bulbs turn on. After a series of experiments he came up with a conclusion that bulbs indexed 2i and 2i - 1 turn on if the chain connecting them consists of exactly d_i wires. Moreover, the following important condition holds: the value of d_i is never greater than n.Petya did his best but was not able to find a configuration that makes all bulbs to turn on, so he seeks your assistance. Please, find out a configuration that makes all bulbs shine. It is guaranteed that such configuration always exists.InputThe first line of the input contains a single integer n (1 \leq n \leq 100\,000) — the parameter of a construction set that defines the number of bulbs and the number of wires.Next line contains n integers d_1, d_2, \ldots, d_n (1 \leq d_i \leq n), where d_i stands for the number of wires the chain between bulbs 2i and 2i - 1 should consist of.OutputPrint 2n - 1 lines. The i-th of them should contain two distinct integers a_i and b_i (1 \leq a_i, b_i \leq 2n, a_i \ne b_i) — indices of bulbs connected by a wire.If there are several possible valid answer you can print any of them.ExamplesInput 3 2 2 2 Output 1 6 2 6 3 5 3 6 4 5 Input 4 2 2 2 1 Output 1 6 1 7 2 6 3 5 3 6 4 5 7 8 Input 6 2 2 2 2 2 2 Output 1 3 2 3 3 5 4 5 5 7 6 7 7 12 8 12 9 11 9 12 10 11 Input 2 1 1 Output 1 2 1 4 3 4 Note Answer for the first sample test. Answer for the second sample test.
3 2 2 2
1 6 2 6 3 5 3 6 4 5
1 second
512 megabytes
['constructive algorithms', 'graphs', 'math', 'sortings', 'trees', '*2000']
D. Treasure Islandtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputAll of us love treasures, right? That's why young Vasya is heading for a Treasure Island.Treasure Island may be represented as a rectangular table n \times m which is surrounded by the ocean. Let us number rows of the field with consecutive integers from 1 to n from top to bottom and columns with consecutive integers from 1 to m from left to right. Denote the cell in r-th row and c-th column as (r, c). Some of the island cells contain impassable forests, and some cells are free and passable. Treasure is hidden in cell (n, m).Vasya got off the ship in cell (1, 1). Now he wants to reach the treasure. He is hurrying up, so he can move only from cell to the cell in next row (downwards) or next column (rightwards), i.e. from cell (x, y) he can move only to cells (x+1, y) and (x, y+1). Of course Vasya can't move through cells with impassable forests.Evil Witch is aware of Vasya's journey and she is going to prevent him from reaching the treasure. Before Vasya's first move she is able to grow using her evil magic impassable forests in previously free cells. Witch is able to grow a forest in any number of any free cells except cells (1, 1) where Vasya got off his ship and (n, m) where the treasure is hidden.Help Evil Witch by finding out the minimum number of cells she has to turn into impassable forests so that Vasya is no longer able to reach the treasure.InputFirst line of input contains two positive integers n, m (3 \le n \cdot m \le 1\,000\,000), sizes of the island.Following n lines contains strings s_i of length m describing the island, j-th character of string s_i equals "#" if cell (i, j) contains an impassable forest and "." if the cell is free and passable. Let us remind you that Vasya gets of his ship at the cell (1, 1), i.e. the first cell of the first row, and he wants to reach cell (n, m), i.e. the last cell of the last row.It's guaranteed, that cells (1, 1) and (n, m) are empty.OutputPrint the only integer k, which is the minimum number of cells Evil Witch has to turn into impassable forest in order to prevent Vasya from reaching the treasure.ExamplesInput 2 2 .. .. Output 2 Input 4 4 .... #.#. .... .#.. Output 1 Input 3 4 .... .##. .... Output 2 NoteThe following picture illustrates the island in the third example. Blue arrows show possible paths Vasya may use to go from (1, 1) to (n, m). Red illustrates one possible set of cells for the Witch to turn into impassable forest to make Vasya's trip from (1, 1) to (n, m) impossible.
2 2 .. ..
2
1 second
512 megabytes
['dfs and similar', 'dp', 'flows', 'hashing', '*1900']
C. Bad Sequencetime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputPetya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence s is called correct if: s is empty; s is equal to "(t)", where t is correct bracket sequence; s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.InputFirst of line of input contains a single number n (1 \leq n \leq 200\,000) — length of the sequence which Petya received for his birthday.Second line of the input contains bracket sequence of length n, containing symbols "(" and ")".OutputPrint "Yes" if Petya can make his sequence correct moving at most one bracket. Otherwise print "No".ExamplesInput 2 )( Output Yes Input 3 (() Output No Input 2 () Output Yes Input 10 )))))((((( Output No NoteIn the first example, Petya can move first bracket to the end, thus turning the sequence into "()", which is correct bracket sequence.In the second example, there is no way to move at most one bracket so that the sequence becomes correct.In the third example, the sequence is already correct and there's no need to move brackets.
2 )(
Yes
1 second
512 megabytes
['data structures', 'greedy', '*1200']
B. Badgestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are b boys and g girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and n participants have accepted the invitation. The organizers do not know how many boys and girls are among them.Organizers are preparing red badges for girls and blue ones for boys.Vasya prepared n+1 decks of badges. The i-th (where i is from 0 to n, inclusive) deck contains i blue badges and n-i red ones. The total number of badges in any deck is exactly n.Determine the minimum number of decks among these n+1 that Vasya should take, so that there will be a suitable deck no matter how many girls and boys there will be among the participants of the tournament.InputThe first line contains an integer b (1 \le b \le 300), the number of boys. The second line contains an integer g (1 \le g \le 300), the number of girls. The third line contains an integer n (1 \le n \le b + g), the number of the board games tournament participants.OutputOutput the only integer, the minimum number of badge decks that Vasya could take.ExamplesInput 5 6 3 Output 4 Input 5 3 5 Output 4 NoteIn the first example, each of 4 decks should be taken: (0 blue, 3 red), (1 blue, 2 red), (2 blue, 1 red), (3 blue, 0 red).In the second example, 4 decks should be taken: (2 blue, 3 red), (3 blue, 2 red), (4 blue, 1 red), (5 blue, 0 red). Piles (0 blue, 5 red) and (1 blue, 4 red) can not be used.
5 6 3
4
1 second
512 megabytes
['brute force', 'math', '*1100']
A. Optimal Currency Exchangetime limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAndrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has n rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is d rubles, and one euro costs e rubles.Recall that there exist the following dollar bills: 1, 2, 5, 10, 20, 50, 100, and the following euro bills — 5, 10, 20, 50, 100, 200 (note that, in this problem we do not consider the 500 euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange.Help him — write a program that given integers n, e and d, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.InputThe first line of the input contains one integer n (1 \leq n \leq 10^8) — the initial sum in rubles Andrew has. The second line of the input contains one integer d (30 \leq d \leq 100) — the price of one dollar in rubles. The third line of the input contains integer e (30 \leq e \leq 100) — the price of one euro in rubles.OutputOutput one integer — the minimum number of rubles Andrew can have after buying dollar and euro bills optimally.ExamplesInput 100 60 70 Output 40 Input 410 55 70 Output 5 Input 600 60 70 Output 0 NoteIn the first example, we can buy just 1 dollar because there is no 1 euro bill.In the second example, optimal exchange is to buy 5 euro and 1 dollar.In the third example, optimal exchange is to buy 10 dollars in one bill.
100 60 70
40
1.5 seconds
512 megabytes
['brute force', 'math', '*1400']
G. Path Queriestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i.You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i.InputThe first line of the input contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the number of vertices in the tree and the number of queries.Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i — the labels of vertices it connects (1 \le u_i, v_i \le n, u_i \ne v_i) and the weight of the edge (1 \le w_i \le 2 \cdot 10^5). It is guaranteed that the given edges form a tree.The last line of the input contains m integers q_1, q_2, \dots, q_m (1 \le q_i \le 2 \cdot 10^5), where q_i is the maximum weight of an edge in the i-th query.OutputPrint m integers — the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i.Queries are numbered from 1 to m in the order of the input.ExamplesInput 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 NoteThe picture shows the tree from the first example:
7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1
21 7 15 21 3
3 seconds
256 megabytes
['divide and conquer', 'dsu', 'graphs', 'sortings', 'trees', '*1800']
F. Unstable String Sorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAuthors have come up with the string s consisting of n lowercase Latin letters.You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.For all i from 1 to n-1 the following properties hold: s[p_i] \le s[p_{i + 1}] and s[q_i] \le s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.If there are multiple answers, you can print any of them.InputThe first line of the input contains two integers n and k (1 \le n \le 2 \cdot 10^5, 1 \le k \le 26) — the length of the string and the number of distinct characters required.The second line of the input contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n, all p_i are distinct integers from 1 to n) — the permutation p.The third line of the input contains n integers q_1, q_2, \dots, q_n (1 \le q_i \le n, all q_i are distinct integers from 1 to n) — the permutation q.OutputIf it is impossible to find the suitable string, print "NO" on the first line.Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.If there are multiple answers, you can print any of them.ExampleInput 3 2 1 2 3 1 3 2 Output YES abb
3 2 1 2 3 1 3 2
YES abb
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'implementation', 'strings', '*2100']
E. Two Small Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t both of length 2 and both consisting only of characters 'a', 'b' and 'c'.Possible examples of strings s and t: "ab", "ca", "bb".You have to find a string res consisting of 3n characters, n characters should be 'a', n characters should be 'b' and n characters should be 'c' and s and t should not occur in res as substrings.A substring of a string is a contiguous subsequence of that string. So, the strings "ab", "ac" and "cc" are substrings of the string "abacc", but the strings "bc", "aa" and "cb" are not substrings of the string "abacc".If there are multiple answers, you can print any of them.InputThe first line of the input contains one integer n (1 \le n \le 10^5) — the number of characters 'a', 'b' and 'c' in the resulting string.The second line of the input contains one string s of length 2 consisting of characters 'a', 'b' and 'c'.The third line of the input contains one string t of length 2 consisting of characters 'a', 'b' and 'c'.OutputIf it is impossible to find the suitable string, print "NO" on the first line. Otherwise print "YES" on the first line and string res on the second line. res should consist of 3n characters, n characters should be 'a', n characters should be 'b' and n characters should be 'c' and s and t should not occur in res as substrings.If there are multiple answers, you can print any of them.ExamplesInput 2 ab bc Output YES acbbac Input 3 aa bc Output YES cacbacbab Input 1 cb ac Output YES abc
2 ab bc
YES acbbac
2 seconds
256 megabytes
['brute force', 'constructive algorithms', '*1900']
D2. Equalizing by Division (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the number of elements in the array.You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := \lfloor\frac{a_i}{2}\rfloor).You can perform such an operation any (possibly, zero) number of times with any a_i.Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.InputThe first line of the input contains two integers n and k (1 \le k \le n \le 2 \cdot 10^5) — the number of elements in the array and the number of equal numbers required.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 2 \cdot 10^5), where a_i is the i-th element of a.OutputPrint one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.ExamplesInput 5 3 1 2 2 4 5 Output 1 Input 5 3 1 2 3 4 5 Output 2 Input 5 3 1 2 3 3 3 Output 0
5 3 1 2 2 4 5
1
2 seconds
256 megabytes
['brute force', 'math', 'sortings', '*1600']
D1. Equalizing by Division (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the number of elements in the array.You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := \lfloor\frac{a_i}{2}\rfloor).You can perform such an operation any (possibly, zero) number of times with any a_i.Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.InputThe first line of the input contains two integers n and k (1 \le k \le n \le 50) — the number of elements in the array and the number of equal numbers required.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 2 \cdot 10^5), where a_i is the i-th element of a.OutputPrint one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.ExamplesInput 5 3 1 2 2 4 5 Output 1 Input 5 3 1 2 3 4 5 Output 2 Input 5 3 1 2 3 3 3 Output 0
5 3 1 2 2 4 5
1
2 seconds
256 megabytes
['brute force', 'implementation', '*1500']
C. Book Readingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is reading a book consisting of n pages numbered from 1 to n. Every time he finishes the page with the number divisible by m, he writes down the last digit of this page number. For example, if n=15 and m=5, pages divisible by m are 5, 10, 15. Their last digits are 5, 0, 5 correspondingly, their sum is 10.Your task is to calculate the sum of all digits Polycarp has written down.You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 1000) — the number of queries.The following q lines contain queries, one per line. Each query is given as two integers n and m (1 \le n, m \le 10^{16}) — the number of pages in the book and required divisor, respectively.OutputFor each query print the answer for it — the sum of digits written down by Polycarp.ExampleInput 7 1 1 10 1 100 3 1024 14 998244353 1337 123 144 1234312817382646 13 Output 1 45 153 294 3359835 0 427262129093995
7 1 1 10 1 100 3 1024 14 998244353 1337 123 144 1234312817382646 13
1 45 153 294 3359835 0 427262129093995
1 second
256 megabytes
['math', '*1200']
B. Bad Pricestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, \dots, a_n, where a_i is the price of berPhone on the day i.Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if n=6 and a=[3, 9, 4, 6, 7, 5], then the number of days with a bad price is 3 — these are days 2 (a_2=9), 4 (a_4=6) and 5 (a_5=7).Print the number of days with a bad price.You have to answer t independent data sets.InputThe first line contains an integer t (1 \le t \le 10000) — the number of sets of input data in the test. Input data sets must be processed independently, one after another.Each input data set consists of two lines. The first line contains an integer n (1 \le n \le 150000) — the number of days. The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6), where a_i is the price on the i-th day.It is guaranteed that the sum of n over all data sets in the test does not exceed 150000.OutputPrint t integers, the j-th of which should be equal to the number of days with a bad price in the j-th input data set.ExampleInput 5 6 3 9 4 6 7 5 1 1000000 2 2 1 10 31 41 59 26 53 58 97 93 23 84 7 3 2 1 2 3 4 5 Output 3 0 1 8 2
5 6 3 9 4 6 7 5 1 1000000 2 2 1 10 31 41 59 26 53 58 97 93 23 84 7 3 2 1 2 3 4 5
3 0 1 8 2
1 second
256 megabytes
['data structures', 'implementation', '*1100']
A. Chips Movingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n chips on a number line. The i-th chip is placed at the integer coordinate x_i. Some chips can have equal coordinates.You can perform each of the two following types of moves any (possibly, zero) number of times on any chip: Move the chip i by 2 to the left or 2 to the right for free (i.e. replace the current coordinate x_i with x_i - 2 or with x_i + 2); move the chip i by 1 to the left or 1 to the right and pay one coin for this move (i.e. replace the current coordinate x_i with x_i - 1 or with x_i + 1). Note that it's allowed to move chips to any integer coordinate, including negative and zero.Your task is to find the minimum total number of coins required to move all n chips to the same coordinate (i.e. all x_i should be equal after some sequence of moves).InputThe first line of the input contains one integer n (1 \le n \le 100) — the number of chips.The second line of the input contains n integers x_1, x_2, \dots, x_n (1 \le x_i \le 10^9), where x_i is the coordinate of the i-th chip.OutputPrint one integer — the minimum total number of coins required to move all n chips to the same coordinate.ExamplesInput 3 1 2 3 Output 1 Input 5 2 2 2 3 3 Output 2 NoteIn the first example you need to move the first chip by 2 to the right and the second chip by 1 to the right or move the third chip by 2 to the left and the second chip by 1 to the left so the answer is 1.In the second example you need to move two chips with coordinate 3 by 1 to the left so the answer is 2.
3 1 2 3
1
1 second
256 megabytes
['math', '*900']
I. Unusual Graphtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan on his birthday was presented with array of non-negative integers a_1, a_2, \ldots, a_n. He immediately noted that all a_i satisfy the condition 0 \leq a_i \leq 15.Ivan likes graph theory very much, so he decided to transform his sequence to the graph.There will be n vertices in his graph, and vertices u and v will present in the graph if and only if binary notations of integers a_u and a_v are differ in exactly one bit (in other words, a_u \oplus a_v = 2^k for some integer k \geq 0. Where \oplus is Bitwise XOR).A terrible thing happened in a couple of days, Ivan forgot his sequence a, and all that he remembers is constructed graph!Can you help him, and find any sequence a_1, a_2, \ldots, a_n, such that graph constructed by the same rules that Ivan used will be the same as his graph?InputThe first line of input contain two integers n,m (1 \leq n \leq 500, 0 \leq m \leq \frac{n(n-1)}{2}): number of vertices and edges in Ivan's graph.Next m lines contain the description of edges: i-th line contain two integers u_i, v_i (1 \leq u_i, v_i \leq n; u_i \neq v_i), describing undirected edge connecting vertices u_i and v_i in the graph.It is guaranteed that there are no multiple edges in the graph. It is guaranteed that there exists some solution for the given graph.OutputOutput n space-separated integers, a_1, a_2, \ldots, a_n (0 \leq a_i \leq 15). Printed numbers should satisfy the constraints: edge between vertices u and v present in the graph if and only if a_u \oplus a_v = 2^k for some integer k \geq 0.It is guaranteed that there exists some solution for the given graph. If there are multiple possible solutions, you can output any.ExamplesInput 4 4 1 2 2 3 3 4 4 1 Output 0 1 0 1 Input 3 0 Output 0 0 0
4 4 1 2 2 3 3 4 4 1
0 1 0 1
5 seconds
256 megabytes
['*special problem', 'graphs', '*3000']
H. Road Repair in Treelandtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities and n-1 two-way roads in Treeland. Each road connects a pair of different cities. From any city you can drive to any other, moving only along the roads. Cities are numbered from 1 to n. Yes, of course, you recognized an undirected tree in this description.The government plans to repair all the roads. Each road will be repaired by some private company. In total, the country has 10^6 private companies that are numbered from 1 to 10^6. It is possible that some companies will not repair roads at all, and some will repair many roads.To simplify the control over the work of private companies, the following restriction was introduced: for each city, we calculate the number of different companies that repair roads that have this city at one end. This number for each city should not exceed 2. In other words, for each city, there should be no more than two different companies that repair roads related to this city.The National Anti-Corruption Committee of Treeland raises concerns that all (or almost all) of the work will go to one private company. For this reason, the committee requires that roads be distributed among companies in such a way as to minimize the value of r. For each company, we calculate the number of roads assigned to it, the maximum among all companies is called the number r.Help the government find such a way to distribute all roads among companies in the required way.InputThe first line contains an integer t (1 \le t \le 1000) — the number of input cases in the input. Next, the input cases themselves are given. The first line of each test case set contains an integer n (2 \le n \le 3000) — the number of cities in Treeland. Next, in the n-1 lines the roads are written: a line contains two integers x_i, y_i (1 \le x_i, y_i \le n), indicating that the i-th road connects the cities x_i and y_i.It is guaranteed that the sum of all values n ​​for all test cases in the input does not exceed 3000.OutputPrint the answers for all t test cases in the input. Each test case must begin with a line that contains r — the minimum possible number of roads assigned to the most used company. Next, in the next line print n-1 the number c_1, c_2, \dots, c_{n-1} (1 \le c_i \le 10^6), where c_i indicates the company to repair the i-th road. If there are several optimal assignments, print any of them.ExampleInput 3 3 1 2 2 3 6 1 2 1 3 1 4 1 5 1 6 7 3 1 1 4 4 6 5 1 2 4 1 7 Output 1 10 20 3 1 1 1 2 2 2 11 11 12 13 12 13
3 3 1 2 2 3 6 1 2 1 3 1 4 1 5 1 6 7 3 1 1 4 4 6 5 1 2 4 1 7
1 10 20 3 1 1 1 2 2 2 11 11 12 13 12 13
3 seconds
256 megabytes
['*special problem', 'binary search', 'dp', 'trees', '*3100']
G. King's Pathtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities and n-1 two-way roads in Treeland. Each road connects a pair of different cities. From any city you can drive to any other, moving only along the roads. Cities are numbered from 1 to n. Yes, of course, you recognized an undirected tree in this description.There is exactly one flag in each city, in the i-th city the flag color is c_i. The colors of the flags in different cities may be the same.If the King travels along the route [u_1, u_2, u_3, \dots, u_k], then this means that he starts in the city u_1, then moves to the city u_2 (u_2 is connected by road with u_1), then from u_2 to u_3 (u_3 is connected by road to u_2), and so on until he arrives in the city of u_k. It is possible that during this route the King will visit the same city more than once. In other words, the route [u_1, u_2, u_3, \dots, u_k] does not necessarily consist of different cities. In terms of graph theory — the King moves from u_1 to u_k along some path [u_1, u_2, u_3, \dots, u_k], which is not necessarily simple (for all j from 1 to k-1 of the city u_j and u_{j+1} are connected by road).When the King moves from one city to another, city heads exchange flags as a sign of their friendship. Example of moving the King along the route [1, 4, 2, 6]. The color of the vertex matches the color of the flag at that vertex. For aesthetic reasons, the King wants the flag color in the city i to be equal to d_i for all i from 1 to n. Determine whether the King can choose some route and drive along it so that for each city the flag color in it turns out to be equal to the desired color d_i. Note that the King can choose (and drive) exactly one route. If yes, find the shortest possible route for the King.If the initial colors of the flags already match the King's requirements (i.e. c_i=d_i for all i), then consider that the King makes a route of length k=0.InputThe first line contains an integer t (1 \le t \le 10^5) — the number of test cases to solve. The following are the cases.Each case begins with a line containing an integer n (2 \le n \le 2\cdot10^5) — the number of cities in Treeland.The following is a line of n integers c_1, c_2, \dots, c_n (1 \le c_i \le 10^6), where c_i denotes the color of the flag at the i-th vertex before the King's journey.The following is a line of n integers d_1, d_2, \dots, d_n (1 \le d_i \le 10^6), where d_i denotes the required flag color at the i-th vertex after the completion of the King's journey.Further, in the n-1 line, the Treeland's roads are listed. Each road is given by a line containing two integers x_j, y_j (1 \le x_j, y_j \le n) — numbers of cities that are connected by the j th road.It is guaranteed that from every city you can get to any other by road (in other words, the system of cities and roads forms an undirected tree).The sum of all n values ​​for all cases in one test does not exceed 2\cdot10^5.OutputPrint the answers to all cases in the order of their appearance in the input data.Each answer must begin with a line containing "Yes" (in the case of a positive answer) or "No" (in the case that the required route does not exist). In the case of a positive answer, the following line must contain an integer k — the number of cities in the shortest possible route of the King. The next line should contain the required route u_1, u_2, \dots, u_k (1 \le u_i \le n). You can skip the line if k=0.ExamplesInput 1 7 2 3 2 7 1 1 3 7 1 2 3 1 2 3 1 7 4 1 2 6 2 3 2 4 5 4 Output Yes 4 1 4 2 6 Input 1 5 1 2 2 2 2 2 2 2 2 1 1 2 2 3 3 4 4 5 Output Yes 5 1 2 3 4 5 Input 3 4 10 20 10 20 20 10 20 10 1 2 1 3 1 4 2 1000000 1000000 1000000 1000000 1 2 10 4 2 2 4 2 4 1 2 3 4 4 2 4 4 3 2 1 2 4 2 5 8 6 9 10 5 1 10 7 10 3 4 5 9 3 10 2 4 Output No Yes 0 Yes 5 3 10 5 9 6
1 7 2 3 2 7 1 1 3 7 1 2 3 1 2 3 1 7 4 1 2 6 2 3 2 4 5 4
Yes 4 1 4 2 6
5 seconds
256 megabytes
['*special problem', 'math', 'trees', '*2500']
F. kotlinkotlinkotlinkotlin...time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp really likes writing the word "kotlin". He wrote this word several times in a row without spaces. For example, he could write the string like "kotlinkotlinkotlinkotlin".Polycarp sliced (cut) the written string into n pieces and mixed them. As a result, he has n strings s_1, s_2, \dots, s_n and he can arrange them in the right order, concatenate (join) all of them and get a string like "kotlinkotlin...kotlin".Help Polycarp to find the right order of strings s_1, s_2, \dots, s_n, so that if he writes the strings in this order, he will get the word "kotlin" or the sequence of this word.Pay attention that you must use all given strings and you must use each string only once.InputThe first line of the input contains one integer n (1 \le n \le 10^5) — the number of Polycarp's strings. Next lines of the input contain n Polycarp's strings.Total sum of their lengths doesn't exceed 3\cdot10^5. It's guaranteed that there is the right order of arrangement the strings that if you concatenate them into one string, you will get some non-empty sequence of the word "kotlin".OutputPrint n different integers p_1, p_2, \dots, p_n (1 \le p_i \le n), where p_i is an index of the string that should be the i-th in a required concatenation. In other words, the result of concatenation s_{p_1}+s_{p_2}+\dots+s_{p_n} must be in the form "kotlinkotlin...kotlin". If there are many solutions, print any of them.ExamplesInput 2 lin kot Output 2 1 Input 4 linkotlinkotlinkotl kotlin in kot Output 2 4 1 3 Input 8 i n tlin o ko t k l Output 7 4 3 5 6 8 1 2
2 lin kot
2 1
3 seconds
256 megabytes
['*special problem', 'graphs', 'implementation', 'strings', '*2300']
E. Double Permutation Inc.time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp recently became an employee of the company "Double Permutation Inc." Now he is a fan of permutations and is looking for them everywhere!A permutation in this problem is a sequence of integers p_1, p_2, \dots, p_k such that every integer from 1 to k occurs exactly once in it. For example, the following sequences are permutations of [3, 1, 4, 2], [1] and [6, 1, 2, 3, 5, 4]. The following sequences are not permutations: [0, 1], [1, 2, 2], [1, 2, 4] and [2, 3].In the lobby of the company's headquarter statistics on visits to the company's website for the last n days are published — the sequence a_1, a_2, \dots, a_n. Polycarp wants to color all the elements of this sequence in one of three colors (red, green or blue) so that: all red numbers, being written out of a_1, a_2, \dots, a_n from left to right (that is, without changing their relative order), must form some permutation (let's call it P); all green numbers, being written out of a_1, a_2, \dots, a_n from left to right (that is, without changing their relative order), must form the same permutation P; among blue numbers there should not be elements that are equal to some element of the permutation P. Help Polycarp to color all n numbers so that the total number of red and green elements is maximum.InputThe first line contains an integer n (1 \le n \le 2\cdot10^5) — the length of the sequence a. The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 2\cdot10^5).OutputPrint a string s of length n such that: s_i='R', if the element a_i must be colored in red; s_i='G', if the element a_i must be colored in green; s_i='B', if the element a_i must be colored in blue. The string s should maximize the total number of red and green elements when fulfilling the requirements from the main part of the problem statement. If there are several optimal answers, print any of them.ExamplesInput 5 1 2 3 2 1 Output RBBBG Input 3 1 1 1 Output BBB Input 10 3 3 2 2 5 4 1 5 4 1 Output RGRGRRRGGG Input 10 3 9 3 1 2 1 2 4 4 4 Output RBGRRGGBBB
5 1 2 3 2 1
RBBBG
5 seconds
256 megabytes
['*special problem', 'binary search', 'greedy', '*2000']
D. Teamstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n table bowling players, the rating of the i-th player equals r_i. Compose a maximum number of teams in a such way that: each player belongs to at most one team; each team contains exactly a+b players; each team contains a group of a players with the same rating and a group of b players with another same rating, which must be k times larger than the rating of the players in the first group. For example, if n=12, r=[1, 1, 2, 2, 2, 2, 2, 3, 3, 4, 6, 6], a=1, b=2, k=2, you can compose two teams with ratings [1, 2, 2] and one team with ratings [3, 6, 6]. So, the maximum number of teams is 3.Find the maximum number of teams by given n, r_1 \dots r_n, a, b and k to compose in respect to the given requirements.InputThe first line of the input contains four integers n, a, b and k (1 \le n,a,b \le 3\cdot10^5, 2 \le k \le 1000). The second line contains the sequence of player's ratings — integers r_1, r_2, \dots, r_n (1 \le r_i \le 10^6).OutputPrint only one integer — the maximum number of teams that can be composed from n given players.ExamplesInput 12 1 2 2 1 1 2 2 2 2 2 3 3 4 6 6 Output 3 Input 14 1 1 3 3 3 1 1 9 9 2 3 6 6 3 18 3 18 Output 6 Input 1 2 3 10 1000000 Output 0
12 1 2 2 1 1 2 2 2 2 2 3 3 4 6 6
3
3 seconds
256 megabytes
['*special problem', 'binary search', 'greedy', 'math', '*2000']
C. Ice Creamtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSummer in Berland lasts n days, the price of one portion of ice cream on the i-th day is c_i. Over the summer, Tanya wants to eat exactly k portions of ice cream. At the same time, on the i-th day, she decided that she would eat at least a_i portions, but not more than b_i (a_i \le b_i) portions. In other words, let d_i be equal to the number of portions that she eats on the i-th day. Then d_1+d_2+\dots+d_n=k and a_i \le d_i \le b_i for each i.Given that portions of ice cream can only be eaten on the day of purchase, find the minimum amount of money that Tanya can spend on ice cream in the summer.InputThe first line contains two integers n and k (1 \le n \le 2\cdot10^5, 0 \le k \le 10^9) — the number of days and the total number of servings of ice cream that Tanya will eat in the summer.The following n lines contain descriptions of the days, one description per line. Each description consists of three integers a_i, b_i, c_i (0 \le a_i \le b_i \le 10^9, 1 \le c_i \le 10^6).OutputPrint the minimum amount of money that Tanya can spend on ice cream in the summer. If there is no way for Tanya to buy and satisfy all the requirements, then print -1.ExamplesInput 3 7 3 5 6 0 3 4 3 3 3 Output 31 Input 1 45000 40000 50000 100000 Output 4500000000 Input 3 100 2 10 50 50 60 16 20 21 25 Output -1 Input 4 12 2 5 1 1 2 2 2 3 7 3 10 4 Output 35 NoteIn the first example, Tanya needs to eat 3 portions of ice cream on the first day, 1 portions of ice cream on the second day and 3 portions of ice cream on the third day. In this case, the amount of money spent is 3\cdot6+1\cdot4+3\cdot3=31. It can be shown that any other valid way to eat exactly 7 portions of ice cream costs more.
3 7 3 5 6 0 3 4 3 3 3
31
3 seconds
256 megabytes
['*special problem', 'greedy', 'sortings', '*1700']
B. Traveling Around the Golden Ring of Berlandtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Golden Ring is the special tourist route in Berland. This route consists of n cities and the cyclic railway route. Cities are numbered from 1 to n so that: the next city for 1 is the city 2, the next city for 2 is the city 3, ... the next city for n is the city 1. Thus, the route is a cycle, cities are numbered in the direction of travel (the route is directed in one way).Blogger Polycarp wants to start his journey in the city 1. For each city he knows the value a_i — how many selfies he wants to do in i-th city. He can take no more than one selfie in one visit to each city. Since he is traveling by train, he can't skip the city (he always moves from the city i to the city i+1 for 1 \le i < n and from n to 1). Thus, when the train stops in the city, Polycarp must visit this city. If Polycarp visits the city multiple times, all visits are counted separately.What is the least number of city visits Polycarp will have to complete to fulfill his plan for the number of selfies for each city? Note that he always visits the city 1, since it is this city that his journey begins in.InputThe first line contains an integer n (3 \le n \le 2\cdot10^5) — the number of cities in the Golden Ring of Berland.The next line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^9), where a_i is equal to the required number of selfies in the i-th city.It is guaranteed that at least one of the numbers a_i is strictly greater than zero.OutputPrint a single integer — the required minimum number of visits.ExamplesInput 3 1 0 0 Output 1 Input 3 2 0 2 Output 6 Input 5 0 3 1 3 2 Output 14 Input 5 1000000000 1000000000 1000000000 1000000000 0 Output 4999999999
3 1 0 0
1
3 seconds
256 megabytes
['*special problem', 'implementation', '*1500']
A. Three Problemstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is choosing three problems for creating a programming test. Totally he has n problems in his list. The complexity of the i-th problem equals r_i. All problems are numerated from 1 to n.Help Polycarp to choose such three problems a, b and c, so that the complexity of the first problem strictly less than the complexity of second problem and the complexity of the second problem is strictly less than the complexity of the third problem. So, for chosen problems a, b and c it should be true that r_a < r_b < r_c.If Polycarp can choose three problems in different ways, you can print any of them.InputThe first line of the input contains one integer n (3 \le n \le 3000) — the number of problems in Polycarp's list.The second line of the input contains n integers r_1, r_2, \dots, r_n (1 \le r_i \le 10^9), where r_i is the complexity of the i-th problem.OutputIf Polycarp has no ways to choose three problems, you should print three numbers -1. Ih there is a way to choose them, you should print three different integers a, b, c (1 \le a, b, c \le n), where a is the number of the first chosen problem, b is the number of the second chosen problem and c is the number of the third chosen problem.ExamplesInput 6 3 1 4 1 5 9 Output 4 1 3 Input 5 1 1000000000 1 1000000000 1 Output -1 -1 -1 Input 9 10 10 11 10 10 10 10 10 1 Output 9 8 3
6 3 1 4 1 5 9
4 1 3
3 seconds
256 megabytes
['*special problem', 'implementation', '*1000']
G. Mateusz and Escape Roomtime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMateusz likes to travel! However, on his 42nd visit to Saint Computersburg there is not much left to sightsee. That's why he decided to go to an escape room with his friends!The team has solved all riddles flawlessly. There is only one riddle remaining — a huge circular table! There are n weighing scales lying on top of the table, distributed along the circle. Each scale is adjacent to exactly two other scales: for each i \in \{1, 2, \dots, n-1\}, the i-th and the (i+1)-th scales are adjacent to each other, as well as the first and the n-th scale.The i-th scale initially contains a_i heavy coins. Mateusz can perform moves — each move consists of fetching a single coin from one scale and putting it on any adjacent scale.It turns out that the riddle will be solved when there is a specific amount of coins on each of the scales. Specifically, each scale has parameters l_i and r_i. If each coin lies on a single scale and for each i, the i-th scale contains at least l_i and at most r_i coins, the riddle will be solved and Mateusz's team will win!Mateusz is aiming for the best possible time. Therefore, he wants to solved the riddle as quickly as possible. What is the minimum possible number of moves required to fulfill all the conditions?InputThe first line contains an integer n (3 \le n \le 35\,000) — the number of weighing scales in the circle.The following n lines describe the scales. The i-th of these lines describes the i-th scale and consists of three integers a_i, l_i, r_i (0 \le a_i \le 35\,000, 0 \le l_i \le r_i \le 35\,000).It's guaranteed that the riddle is solvable, that is, \sum_{i=1}^n l_i \le \sum_{i=1}^n a_i \le \sum_{i=1}^n r_i.OutputOutput one integer — the minimum number of operations required to solve the riddle.ExamplesInput 5 0 2 3 1 2 3 4 3 3 4 3 3 4 3 3 Output 4 Input 3 0 1 2 3 0 3 1 0 0 Output 1 Input 4 1 0 2 3 3 3 4 0 4 5 3 5 Output 0
5 0 2 3 1 2 3 4 3 3 4 3 3 4 3 3
4
7 seconds
256 megabytes
['dp', '*3500']