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
B. Digits Sequence (Hard Edition)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536...Your task is to print the k-th digit of this sequence.InputThe first and only line contains integer k (1 \le k \le 10^{12}) — the position to process (1-based index).OutputPrint the k-th digit of the resulting infinite sequence.ExamplesInput 7 Output 7 Input 21 Output 5
7
7
1 second
256 megabytes
['binary search', 'divide and conquer', 'implementation', '*1800']
A. Digits Sequence (Easy Edition)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536...Your task is to print the k-th digit of this sequence.InputThe first and only line contains integer k (1 \le k \le 10000) — the position to process (1-based index).OutputPrint the k-th digit of the resulting infinite sequence.ExamplesInput 7 Output 7 Input 21 Output 5
7
7
1 second
256 megabytes
['implementation', '*1000']
F. Destroy it!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game.The boss battle consists of n turns. During each turn, you will get several cards. Each card has two parameters: its cost c_i and damage d_i. You may play some of your cards during each turn in some sequence (you choose the cards and the exact order they are played), as long as the total cost of the cards you play during the turn does not exceed 3. After playing some (possibly zero) cards, you end your turn, and all cards you didn't play are discarded. Note that you can use each card at most once.Your character has also found an artifact that boosts the damage of some of your actions: every 10-th card you play deals double damage.What is the maximum possible damage you can deal during n turns?InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of turns.Then n blocks of input follow, the i-th block representing the cards you get during the i-th turn.Each block begins with a line containing one integer k_i (1 \le k_i \le 2 \cdot 10^5) — the number of cards you get during i-th turn. Then k_i lines follow, each containing two integers c_j and d_j (1 \le c_j \le 3, 1 \le d_j \le 10^9) — the parameters of the corresponding card.It is guaranteed that \sum \limits_{i = 1}^{n} k_i \le 2 \cdot 10^5.OutputPrint one integer — the maximum damage you may deal.ExampleInput 5 3 1 6 1 7 1 5 2 1 4 1 3 3 1 10 3 5 2 3 3 1 15 2 4 1 10 1 1 100 Output 263 NoteIn the example test the best course of action is as follows:During the first turn, play all three cards in any order and deal 18 damage.During the second turn, play both cards and deal 7 damage.During the third turn, play the first and the third card and deal 13 damage.During the fourth turn, play the first and the third card and deal 25 damage.During the fifth turn, play the only card, which will deal double damage (200).
5 3 1 6 1 7 1 5 2 1 4 1 3 3 1 10 3 5 2 3 3 1 15 2 4 1 10 1 1 100
263
2 seconds
256 megabytes
['dp', 'implementation', 'sortings', '*2100']
E. Cover it!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most \lfloor\frac{n}{2}\rfloor vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer.InputThe first line contains a single integer t (1 \le t \le 2 \cdot 10^5) — the number of queries.Then t queries follow.The first line of each query contains two integers n and m (2 \le n \le 2 \cdot 10^5, n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})) — the number of vertices and the number of edges, respectively.The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 \le v_i, u_i \le n, u_i \ne v_i), which are the indices of vertices connected by the edge.There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i \ne u_i is satisfied. It is guaranteed that the given graph is connected.It is guaranteed that \sum m \le 2 \cdot 10^5 over all queries.OutputFor each query print two lines.In the first line print k (1 \le \lfloor\frac{n}{2}\rfloor) — the number of chosen vertices.In the second line print k distinct integers c_1, c_2, \dots, c_k in any order, where c_i is the index of the i-th chosen vertex.It is guaranteed that the answer exists. If there are multiple answers, you can print any.ExampleInput 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 6 8 2 5 5 4 4 3 4 1 1 3 2 3 2 6 5 6 Output 2 1 3 3 4 3 6 NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 6 8 2 5 5 4 4 3 4 1 1 3 2 3 2 6 5 6
2 1 3 3 4 3 6
2 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', 'shortest paths', 'trees', '*1700']
D. Recover it!time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAuthors guessed an array a consisting of n integers; each integer is not less than 2 and not greater than 2 \cdot 10^5. You don't know the array a, but you know the array b which is formed from it with the following sequence of operations: Firstly, let the array b be equal to the array a; Secondly, for each i from 1 to n: if a_i is a prime number, then one integer p_{a_i} is appended to array b, where p is an infinite sequence of prime numbers (2, 3, 5, \dots); otherwise (if a_i is not a prime number), the greatest divisor of a_i which is not equal to a_i is appended to b; Then the obtained array of length 2n is shuffled and given to you in the input. Here p_{a_i} means the a_i-th prime number. The first prime p_1 = 2, the second one is p_2 = 3, and so on.Your task is to recover any suitable array a that forms the given array b. It is guaranteed that the answer exists (so the array b is obtained from some suitable array a). If there are multiple answers, you can print any.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in a.The second line of the input contains 2n integers b_1, b_2, \dots, b_{2n} (2 \le b_i \le 2750131), where b_i is the i-th element of b. 2750131 is the 199999-th prime number.OutputIn the only line of the output print n integers a_1, a_2, \dots, a_n (2 \le a_i \le 2 \cdot 10^5) in any order — the array a from which the array b can be obtained using the sequence of moves given in the problem statement. If there are multiple answers, you can print any.ExamplesInput 3 3 5 2 3 2 4 Output 3 4 2 Input 1 2750131 199999 Output 199999 Input 1 3 6 Output 6
3 3 5 2 3 2 4
3 4 2
4 seconds
256 megabytes
['dfs and similar', 'graphs', 'greedy', 'number theory', 'sortings', '*1800']
C. Lose it!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. Each a_i is one of the six following numbers: 4, 8, 15, 16, 23, 42.Your task is to remove the minimum number of elements to make this array good.An array of length k is called good if k is divisible by 6 and it is possible to split it into \frac{k}{6} subsequences 4, 8, 15, 16, 23, 42.Examples of good arrays: [4, 8, 15, 16, 23, 42] (the whole array is a required sequence); [4, 8, 4, 15, 16, 8, 23, 15, 16, 42, 23, 42] (the first sequence is formed from first, second, fourth, fifth, seventh and tenth elements and the second one is formed from remaining elements); [] (the empty array is good). Examples of bad arrays: [4, 8, 15, 16, 42, 23] (the order of elements should be exactly 4, 8, 15, 16, 23, 42); [4, 8, 15, 16, 23, 42, 4] (the length of the array is not divisible by 6); [4, 8, 15, 16, 23, 42, 4, 8, 15, 16, 23, 23] (the first sequence can be formed from first six elements but the remaining array cannot form the required sequence). InputThe first line of the input contains one integer n (1 \le n \le 5 \cdot 10^5) — the number of elements in a.The second line of the input contains n integers a_1, a_2, \dots, a_n (each a_i is one of the following numbers: 4, 8, 15, 16, 23, 42), where a_i is the i-th element of a.OutputPrint one integer — the minimum number of elements you have to remove to obtain a good array.ExamplesInput 5 4 8 15 16 23 Output 5 Input 12 4 8 4 15 16 8 23 15 16 42 23 42 Output 0 Input 15 4 8 4 8 15 16 8 16 23 15 16 4 42 23 42 Output 3
5 4 8 15 16 23
5
2 seconds
256 megabytes
['dp', 'greedy', 'implementation', '*1300']
B. Merge it!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers a_1, a_2, \dots , a_n.In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array [2, 1, 4] you can obtain the following arrays: [3, 4], [1, 6] and [2, 5].Your task is to find the maximum possible number of elements divisible by 3 that are in the array after performing this operation an arbitrary (possibly, zero) number of times.You have to answer t independent queries.InputThe first line contains one integer t (1 \le t \le 1000) — the number of queries.The first line of each query contains one integer n (1 \le n \le 100).The second line of each query contains n integers a_1, a_2, \dots , a_n (1 \le a_i \le 10^9). OutputFor each query print one integer in a single line — the maximum possible number of elements divisible by 3 that are in the array after performing described operation an arbitrary (possibly, zero) number of times.ExampleInput 2 5 3 1 2 3 1 7 1 1 1 1 1 2 2 Output 3 3 NoteIn the first query of the example you can apply the following sequence of operations to obtain 3 elements divisible by 3: [3, 1, 2, 3, 1] \rightarrow [3, 3, 3, 1].In the second query you can obtain 3 elements divisible by 3 with the following sequence of operations: [1, 1, 1, 1, 1, 2, 2] \rightarrow [1, 1, 1, 1, 2, 3] \rightarrow [1, 1, 1, 3, 3] \rightarrow [2, 1, 3, 3] \rightarrow [3, 3, 3].
2 5 3 1 2 3 1 7 1 1 1 1 1 2 2
3 3
1 second
256 megabytes
['math', '*1100']
A. Divide it!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace n with \frac{n}{2} if n is divisible by 2; Replace n with \frac{2n}{3} if n is divisible by 3; Replace n with \frac{4n}{5} if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation.Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it.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 next q lines contain the queries. For each query you are given the integer number n (1 \le n \le 10^{18}).OutputPrint the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it.ExampleInput 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72
7 1 10 25 30 14 27 1000000000000000000
0 4 6 6 -1 6 72
1 second
256 megabytes
['brute force', 'greedy', 'implementation', '*800']
G. Yet Another Partiton Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given array a_1, a_2, \dots, a_n. You need to split it into k subsegments (so every element is included in exactly one subsegment).The weight of a subsegment a_l, a_{l+1}, \dots, a_r is equal to (r - l + 1) \cdot \max\limits_{l \le i \le r}(a_i). The weight of a partition is a total weight of all its segments.Find the partition of minimal weight.InputThe first line contains two integers n and k (1 \le n \le 2 \cdot 10^4, 1 \le k \le \min(100, n)) — the length of the array a and the number of subsegments in the partition.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 2 \cdot 10^4) — the array a.OutputPrint single integer — the minimal weight among all possible partitions.ExamplesInput 4 2 6 1 7 4 Output 25 Input 4 3 6 1 7 4 Output 21 Input 5 4 5 1 5 1 5 Output 21 NoteThe optimal partition in the first example is next: 6 1 7 \bigg| 4.The optimal partition in the second example is next: 6 \bigg| 1 \bigg| 7 4.One of the optimal partitions in the third example is next: 5 \bigg| 1 5 \bigg| 1 \bigg| 5.
4 2 6 1 7 4
25
5 seconds
512 megabytes
['data structures', 'divide and conquer', 'dp', 'geometry', 'two pointers', '*3000']
F. The Number of Subpermutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a_1, a_2, \dots, a_n. Let's call some subarray a_l, a_{l + 1}, \dots , a_r of this array a subpermutation if it contains all integers from 1 to r-l+1 exactly once. For example, array a = [2, 2, 1, 3, 2, 3, 1] contains 6 subarrays which are subpermutations: [a_2 \dots a_3], [a_2 \dots a_4], [a_3 \dots a_3], [a_3 \dots a_5], [a_5 \dots a_7], [a_7 \dots a_7].You are asked to calculate the number of subpermutations.InputThe first line contains one integer n (1 \le n \le 3 \cdot 10^5).The second line contains n integers a_1, a_2, \dots , a_n (1 \le a_i \le n). This array can contain the same integers.OutputPrint the number of subpermutations of the array a.ExamplesInput 8 2 4 1 3 4 2 1 2 Output 7 Input 5 1 1 2 1 2 Output 6 NoteThere are 7 subpermutations in the first test case. Their segments of indices are [1, 4], [3, 3], [3, 6], [4, 7], [6, 7], [7, 7] and [7, 8].In the second test case 6 subpermutations exist: [1, 1], [2, 2], [2, 3], [3, 4], [4, 4] and [4, 5].
8 2 4 1 3 4 2 1 2
7
2 seconds
256 megabytes
['brute force', 'data structures', 'divide and conquer', 'hashing', 'math', '*2500']
E. Minimal Segment Covertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n intervals in form [l; r] on a number line.You are also given m queries in form [x; y]. What is the minimal number of intervals you have to take so that every point (not necessarily integer) from x to y is covered by at least one of them? If you can't choose intervals so that every point from x to y is covered, then print -1 for that query.InputThe first line contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the number of intervals and the number of queries, respectively.Each of the next n lines contains two integer numbers l_i and r_i (0 \le l_i < r_i \le 5 \cdot 10^5) — the given intervals.Each of the next m lines contains two integer numbers x_i and y_i (0 \le x_i < y_i \le 5 \cdot 10^5) — the queries.OutputPrint m integer numbers. The i-th number should be the answer to the i-th query: either the minimal number of intervals you have to take so that every point (not necessarily integer) from x_i to y_i is covered by at least one of them or -1 if you can't choose intervals so that every point from x_i to y_i is covered.ExamplesInput 2 3 1 3 2 4 1 3 1 4 3 4 Output 1 2 1 Input 3 4 1 3 1 3 4 5 1 2 1 3 1 4 1 5 Output 1 1 -1 -1 NoteIn the first example there are three queries: query [1; 3] can be covered by interval [1; 3]; query [1; 4] can be covered by intervals [1; 3] and [2; 4]. There is no way to cover [1; 4] by a single interval; query [3; 4] can be covered by interval [2; 4]. It doesn't matter that the other points are covered besides the given query. In the second example there are four queries: query [1; 2] can be covered by interval [1; 3]. Note that you can choose any of the two given intervals [1; 3]; query [1; 3] can be covered by interval [1; 3]; query [1; 4] can't be covered by any set of intervals; query [1; 5] can't be covered by any set of intervals. Note that intervals [1; 3] and [4; 5] together don't cover [1; 5] because even non-integer points should be covered. Here 3.5, for example, isn't covered.
2 3 1 3 2 4 1 3 1 4 3 4
1 2 1
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'divide and conquer', 'dp', 'greedy', 'implementation', 'trees', '*2200']
D. Array Splittingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots, a_n and an integer k.You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let f(i) be the index of subarray the i-th element belongs to. Subarrays are numbered from left to right and from 1 to k.Let the cost of division be equal to \sum\limits_{i=1}^{n} (a_i \cdot f(i)). For example, if a = [1, -2, -3, 4, -5, 6, -7] and we divide it into 3 subbarays in the following way: [1, -2, -3], [4, -5], [6, -7], then the cost of division is equal to 1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9.Calculate the maximum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. InputThe first line contains two integers n and k (1 \le k \le n \le 3 \cdot 10^5).The second line contains n integers a_1, a_2, \dots, a_n ( |a_i| \le 10^6). OutputPrint the maximum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. ExamplesInput 5 2 -1 -2 5 -4 8 Output 15 Input 7 6 -3 0 -1 -2 -2 -4 -1 Output -45 Input 4 1 3 -1 6 0 Output 8
5 2 -1 -2 5 -4 8
15
2 seconds
256 megabytes
['greedy', 'sortings', '*1900']
C. Electrificationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt first, there was a legend related to the name of the problem, but now it's just a formal statement.You are given n points a_1, a_2, \dots, a_n on the OX axis. Now you are asked to find such an integer point x on OX axis that f_k(x) is minimal possible.The function f_k(x) can be described in the following way: form a list of distances d_1, d_2, \dots, d_n where d_i = |a_i - x| (distance between a_i and x); sort list d in non-descending order; take d_{k + 1} as a result. If there are multiple optimal answers you can print any of them.InputThe first line contains single integer T ( 1 \le T \le 2 \cdot 10^5) — number of queries. Next 2 \cdot T lines contain descriptions of queries. All queries are independent. The first line of each query contains two integers n, k (1 \le n \le 2 \cdot 10^5, 0 \le k < n) — the number of points and constant k.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_1 < a_2 < \dots < a_n \le 10^9) — points in ascending order.It's guaranteed that \sum{n} doesn't exceed 2 \cdot 10^5.OutputPrint T integers — corresponding points x which have minimal possible value of f_k(x). If there are multiple answers you can print any of them.ExampleInput 3 3 2 1 2 5 2 1 1 1000000000 1 0 4 Output 3 500000000 4
3 3 2 1 2 5 2 1 1 1000000000 1 0 4
3 500000000 4
2 seconds
256 megabytes
['binary search', 'brute force', 'greedy', '*1600']
B. Catch Overflow!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands: for n — for loop; end — every command between "for n" and corresponding "end" is executed n times; add — adds 1 to x. After the execution of these commands, value of x is returned.Every "for n" is matched with "end", thus the function is guaranteed to be valid. "for n" can be immediately followed by "end"."add" command can be outside of any for loops.Notice that "add" commands might overflow the value of x! It means that the value of x becomes greater than 2^{32}-1 after some "add" command. Now you run f(0) and wonder if the resulting value of x is correct or some overflow made it incorrect.If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of x.InputThe first line contains a single integer l (1 \le l \le 10^5) — the number of lines in the function.Each of the next l lines contains a single command of one of three types: for n (1 \le n \le 100) — for loop; end — every command between "for n" and corresponding "end" is executed n times; add — adds 1 to x. OutputIf overflow happened during execution of f(0), then output "OVERFLOW!!!", otherwise print the resulting value of x.ExamplesInput 9 add for 43 end for 10 for 15 add end add end Output 161 Input 2 for 62 end Output 0 Input 11 for 100 for 100 for 100 for 100 for 100 add end end end end end Output OVERFLOW!!! NoteIn the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for n" can be immediately followed by "end" and that "add" can be outside of any for loops.In the second example there are no commands "add", thus the returning value is 0.In the third example "add" command is executed too many times, which causes x to go over 2^{32}-1.
9 add for 43 end for 10 for 15 add end add end
161
1 second
256 megabytes
['data structures', 'expression parsing', 'implementation', '*1600']
A. From Hero to Zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n and an integer k.In one step you can do one of the following moves: decrease n by 1; divide n by k if n is divisible by k. For example, if n = 27 and k = 3 you can do the following steps: 27 \rightarrow 26 \rightarrow 25 \rightarrow 24 \rightarrow 8 \rightarrow 7 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0.You are asked to calculate the minimum number of steps to reach 0 from n. InputThe first line contains one integer t (1 \le t \le 100) — the number of queries.The only line of each query contains two integers n and k (1 \le n \le 10^{18}, 2 \le k \le 10^{18}).OutputFor each query print the minimum number of steps to reach 0 from n in single line. ExampleInput 2 59 3 1000000000000000000 10 Output 8 19 NoteSteps for the first test case are: 59 \rightarrow 58 \rightarrow 57 \rightarrow 19 \rightarrow 18 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0.In the second test case you have to divide n by k 18 times and then decrease n by 1.
2 59 3 1000000000000000000 10
8 19
1 second
256 megabytes
['implementation', 'math', '*900']
F. Ehab and the Big Finaletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.You're given a tree consisting of n nodes, rooted at node 1. A tree is a connected graph with no cycles.We chose a hidden node x. In order to find this node, you can ask queries of two types: d u (1 \le u \le n). We will answer with the distance between nodes u and x. The distance between two nodes is the number of edges in the shortest path between them. s u (1 \le u \le n). We will answer with the second node on the path from u to x. However, there's a plot twist. If u is not an ancestor of x, you'll receive "Wrong answer" verdict! Node a is called an ancestor of node b if a \ne b and the shortest path from node 1 to node b passes through node a. Note that in this problem a node is not an ancestor of itself.Can you find x in no more than 36 queries? The hidden node is fixed in each test beforehand and does not depend on your queries.InputThe first line contains the integer n (2 \le n \le 2 \cdot 10^5) — the number of nodes in the tree.Each of the next n-1 lines contains two space-separated integers u and v (1 \le u,v \le n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.OutputTo print the answer, print "! x" (without quotes).InteractionTo ask a question, print it in one of the formats above: d u (1 \le u \le n), or s u (1 \le u \le n). After each question, you should read the answer: either the distance or the second vertex on the path, as mentioned in the legend. If we answer with -1 instead of a valid answer, that means you exceeded the number of queries, made an invalid query, or violated the condition in the second type of queries. Exit immediately after receiving -1 and you will see Wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.After printing a query, do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; See the documentation for other languages.Hacks:The first line should contain two integers n and x (2 \le n \le 2 \cdot 10^5, 1 \le x \le n).Each of the next n-1 lines should contain two integers u and v (1 \le u,v \le n) that mean there is an edge between nodes u and v. The edges must form a tree.ExampleInput 5 1 2 1 3 3 4 3 5 3 5Output d 2 s 3 ! 5NoteIn the first example, the hidden node is node 5. We first ask about the distance between node x and node 2. The answer is 3, so node x is either 4 or 5. We then ask about the second node in the path from node 3 to node x. Note here that node 3 is an ancestor of node 5. We receive node 5 as the answer. Finally, we report that the hidden node is node 5.
5 1 2 1 3 3 4 3 5 3 5
d 2 s 3 ! 5
2 seconds
256 megabytes
['constructive algorithms', 'divide and conquer', 'graphs', 'implementation', 'interactive', 'trees', '*2400']
E. Ehab and the Expected GCD Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a function f(p) on a permutation p as follows. Let g_i be the greatest common divisor (GCD) of elements p_1, p_2, ..., p_i (in other words, it is the GCD of the prefix of length i). Then f(p) is the number of distinct elements among g_1, g_2, ..., g_n.Let f_{max}(n) be the maximum value of f(p) among all permutations p of integers 1, 2, ..., n.Given an integers n, count the number of permutations p of integers 1, 2, ..., n, such that f(p) is equal to f_{max}(n). Since the answer may be large, print the remainder of its division by 1000\,000\,007 = 10^9 + 7.InputThe only line contains the integer n (2 \le n \le 10^6) — the length of the permutations.OutputThe only line should contain your answer modulo 10^9+7.ExamplesInput 2 Output 1Input 3 Output 4Input 6 Output 120NoteConsider the second example: these are the permutations of length 3: [1,2,3], f(p)=1. [1,3,2], f(p)=1. [2,1,3], f(p)=2. [2,3,1], f(p)=2. [3,1,2], f(p)=2. [3,2,1], f(p)=2. The maximum value f_{max}(3) = 2, and there are 4 permutations p such that f(p)=2.
2
1
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'number theory', '*2500']
D. Ehab and the Expected XOR Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven two integers n and x, construct an array that satisfies the following conditions: for any element a_i in the array, 1 \le a_i<2^n; there is no non-empty subsegment with bitwise XOR equal to 0 or x, its length l should be maximized. A sequence b is a subsegment of a sequence a if b can be obtained from a by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputThe only line contains two integers n and x (1 \le n \le 18, 1 \le x<2^{18}).OutputThe first line should contain the length of the array l.If l is positive, the second line should contain l space-separated integers a_1, a_2, \dots, a_l (1 \le a_i < 2^n) — the elements of the array a.If there are multiple solutions, print any of them.ExamplesInput 3 5 Output 3 6 1 3Input 2 4 Output 3 1 3 1 Input 1 1 Output 0 NoteIn the first example, the bitwise XOR of the subsegments are \{6,7,4,1,2,3\}.
3 5
3 6 1 3
1 second
256 megabytes
['bitmasks', 'constructive algorithms', '*1900']
C. Ehab and a Special Coloring Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an integer n. For every integer i from 2 to n, assign a positive integer a_i such that the following conditions hold: For any pair of integers (i,j), if i and j are coprime, a_i \neq a_j. The maximal value of all a_i should be minimized (that is, as small as possible). A pair of integers is called coprime if their greatest common divisor is 1.InputThe only line contains the integer n (2 \le n \le 10^5).OutputPrint n-1 integers, a_2, a_3, \ldots, a_n (1 \leq a_i \leq n). If there are multiple solutions, print any of them.ExamplesInput 4 Output 1 2 1 Input 3 Output 2 1NoteIn the first example, notice that 3 and 4 are coprime, so a_3 \neq a_4. Also, notice that a=[1,2,3] satisfies the first condition, but it's not a correct answer because its maximal value is 3.
4
1 2 1
1 second
256 megabytes
['constructive algorithms', 'number theory', '*1300']
B. Ehab Is an Odd Persontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a of length n. You can perform the following operation on it as many times as you want: Pick two integers i and j (1 \le i,j \le n) such that a_i+a_j is odd, then swap a_i and a_j. What is lexicographically the smallest array you can obtain?An array x is lexicographically smaller than an array y if there exists an index i such that x_i<y_i, and x_j=y_j for all 1 \le j < i. Less formally, at the first index i in which they differ, x_i<y_iInputThe first line contains an integer n (1 \le n \le 10^5) — the number of elements in the array a.The second line contains n space-separated integers a_1, a_2, \ldots, a_{n} (1 \le a_i \le 10^9) — the elements of the array a.OutputThe only line contains n space-separated integers, the lexicographically smallest array you can obtain.ExamplesInput 3 4 1 7 Output 1 4 7 Input 2 1 1 Output 1 1 NoteIn the first example, we can swap 1 and 4 since 1+4=5, which is odd.
3 4 1 7
1 4 7
1 second
256 megabytes
['sortings', '*1200']
A. Ehab Fails to Be Thanostime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements?InputThe first line contains an integer n (1 \le n \le 1000), where 2n is the number of elements in the array a.The second line contains 2n space-separated integers a_1, a_2, \ldots, a_{2n} (1 \le a_i \le 10^6) — the elements of the array a.OutputIf there's no solution, print "-1" (without quotes). Otherwise, print a single line containing 2n space-separated integers. They must form a reordering of a. You are allowed to not change the order.ExamplesInput 3 1 2 2 1 3 1 Output 2 1 3 1 1 2Input 1 1 1 Output -1NoteIn the first example, the first n elements have sum 2+1+3=6 while the last n elements have sum 1+1+2=4. The sums aren't equal.In the second example, there's no solution.
3 1 2 2 1 3 1
2 1 3 1 1 2
1 second
256 megabytes
['constructive algorithms', 'greedy', 'sortings', '*1000']
B. Nauuo and Chesstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNauuo is a girl who loves playing chess.One day she invented a game by herself which needs n chess pieces to play on a m\times m chessboard. The rows and columns are numbered from 1 to m. We denote a cell on the intersection of the r-th row and c-th column as (r,c).The game's goal is to place n chess pieces numbered from 1 to n on the chessboard, the i-th piece lies on (r_i,\,c_i), while the following rule is satisfied: for all pairs of pieces i and j, |r_i-r_j|+|c_i-c_j|\ge|i-j|. Here |x| means the absolute value of x.However, Nauuo discovered that sometimes she couldn't find a solution because the chessboard was too small.She wants to find the smallest chessboard on which she can put n pieces according to the rules.She also wonders how to place the pieces on such a chessboard. Can you help her?InputThe only line contains a single integer n (1\le n\le 1000) — the number of chess pieces for the game.OutputThe first line contains a single integer — the minimum value of m, where m is the length of sides of the suitable chessboard.The i-th of the next n lines contains two integers r_i and c_i (1\le r_i,c_i\le m) — the coordinates of the i-th chess piece.If there are multiple answers, print any.ExamplesInput 2 Output 2 1 1 1 2Input 4 Output 3 1 1 1 3 3 1 3 3NoteIn the first example, you can't place the two pieces on a 1\times1 chessboard without breaking the rule. But you can place two pieces on a 2\times2 chessboard like this:In the second example, you can't place four pieces on a 2\times2 chessboard without breaking the rule. For example, if you place the pieces like this:then |r_1-r_3|+|c_1-c_3|=|1-2|+|1-1|=1, |1-3|=2, 1<2; and |r_1-r_4|+|c_1-c_4|=|1-2|+|1-2|=2, |1-4|=3, 2<3. It doesn't satisfy the rule.However, on a 3\times3 chessboard, you can place four pieces like this:
2
2 1 1 1 2
1 second
256 megabytes
['constructive algorithms', 'greedy', '*1100']
A. Nauuo and Votestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNauuo is a girl who loves writing comments.One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes.It's known that there were x persons who would upvote, y persons who would downvote, and there were also another z persons who would vote, but you don't know whether they would upvote or downvote. Note that each of the x+y+z people would vote exactly one time.There are three different results: if there are more people upvote than downvote, the result will be "+"; if there are more people downvote than upvote, the result will be "-"; otherwise the result will be "0".Because of the z unknown persons, the result may be uncertain (i.e. there are more than one possible results). More formally, the result is uncertain if and only if there exist two different situations of how the z persons vote, that the results are different in the two situations.Tell Nauuo the result or report that the result is uncertain.InputThe only line contains three integers x, y, z (0\le x,y,z\le100), corresponding to the number of persons who would upvote, downvote or unknown.OutputIf there is only one possible result, print the result : "+", "-" or "0".Otherwise, print "?" to report that the result is uncertain.ExamplesInput 3 7 0 Output -Input 2 0 1 Output +Input 1 1 0 Output 0Input 0 0 1 Output ?NoteIn the first example, Nauuo would definitely get three upvotes and seven downvotes, so the only possible result is "-".In the second example, no matter the person unknown downvotes or upvotes, Nauuo would get more upvotes than downvotes. So the only possible result is "+".In the third example, Nauuo would definitely get one upvote and one downvote, so the only possible result is "0".In the fourth example, if the only one person upvoted, the result would be "+", otherwise, the result would be "-". There are two possible results, so the result is uncertain.
3 7 0
-
1 second
256 megabytes
['greedy', '*800']
F. Nauuo and Bugtime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputNauuo is a girl who loves coding.One day she was solving a problem which requires to calculate a sum of some numbers modulo p.She wrote the following code and got the verdict "Wrong answer".She soon discovered the bug — the ModAdd function only worked for numbers in the range [0,p), but the numbers in the problem may be out of the range. She was curious about the wrong function, so she wanted to know the result of it.However, the original code worked too slow, so she asked you to help her.You are given an array a_1,a_2,\ldots,a_n and a number p. Nauuo will make m queries, in each query, you are given l and r, and you have to calculate the results of Sum(a,l,r,p). You can see the definition of the Sum function in the pseudocode above.Note that the integers won't overflow in the code above.InputThe first line contains three integers n, m, p (1 \le n \le 10^6, 1 \le m \le 2 \cdot 10^5, 1 \le p \le 10^9) — the length of the given array, the number of queries and the modulus. Note that the modulus is used only in the ModAdd function.The second line contains n integers a_1,a_2,\ldots,a_n (-10^9\le a_i\le10^9) — the given array.In the following m lines, each line contains two integers l, r (1\le l\le r\le n) — you have to calculate the result of Sum(a,l,r,p).OutputThe output contains m integers to answer the queries in the given order.ExampleInput 4 5 6 7 2 -3 17 2 3 1 3 1 2 2 4 4 4 Output -1 0 3 10 11
4 5 6 7 2 -3 17 2 3 1 3 1 2 2 4 4 4
-1 0 3 10 11
4 seconds
1024 megabytes
['data structures', '*3300']
E. Nauuo and ODTtime limit per test7.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputNauuo is a girl who loves traveling.One day she went to a tree, Old Driver Tree, literally, a tree with an old driver on it.The tree is a connected graph consisting of n nodes and n-1 edges. Each node has a color, and Nauuo will visit the ODT through a simple path on the tree in the old driver's car.Nauuo wants to visit see more different colors in her journey, but she doesn't know which simple path she will be traveling on. So, she wants to calculate the sum of the numbers of different colors on all different paths. Can you help her?What's more, the ODT is being redecorated, so there will be m modifications, each modification will change a single node's color. Nauuo wants to know the answer after each modification too.Note that in this problem, we consider the simple path from u to v and the simple path from v to u as two different simple paths if and only if u\ne v.InputThe first line contains two integers n and m (2\le n\le 4\cdot 10^5, 1\le m\le 4\cdot 10^5) — the number of nodes and the number of modifications.The second line contains n integers c_1,c_2,\ldots,c_n (1\le c_i\le n), where c_i is the initial color of node i.Each of the next n-1 lines contains two integers u and v (1\le u,v\le n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree.Each of the next m lines contains two integers u and x (1\le u,x\le n), which means a modification that changes the color of node u into x.OutputThe output contains m+1 integers — the first integer is the answer at the beginning, the rest integers are the answers after every modification in the given order.ExamplesInput 5 3 1 2 1 2 3 1 2 1 3 3 4 3 5 3 3 4 1 4 3 Output 47 51 49 45 Input 6 1 1 1 1 1 1 1 1 2 2 3 3 4 4 5 5 6 1 2 Output 36 46 NoteExample 1The number of colors on each simple path at the beginning:
5 3 1 2 1 2 3 1 2 1 3 3 4 3 5 3 3 4 1 4 3
47 51 49 45
7.5 seconds
512 megabytes
['data structures', '*3300']
D. Nauuo and Portalstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNauuo is a girl who loves playing games related to portals.One day she was playing a game as follows.In an n\times n grid, the rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. We denote a cell on the intersection of the r-th row and c-th column as (r,c).A portal is a pair of doors. You can travel from one of them to another without changing your direction. More formally, if you walk into a cell with a door, you will teleport to the cell with the other door of the same portal and then walk into the next cell facing the original direction. There can not be more than one doors in a single cell.The "next cell" is the nearest cell in the direction you are facing. For example, if you are facing bottom, the next cell of (2,5) is (3,5).If you walk into a cell without a door, you must walk into the next cell after that without changing the direction. If the next cell does not exist, you must exit the grid.You have to set some (possibly zero) portals in the grid, so that if you walk into (i,1) facing right, you will eventually exit the grid from (r_i,n), if you walk into (1, i) facing bottom, you will exit the grid from (n,c_i).It is guaranteed that both r_{1..n} and c_{1..n} are permutations of n elements. A permutation of n elements is a sequence of numbers p_1,p_2,\ldots,p_n in which every integer from 1 to n appears exactly once.She got confused while playing the game, can you help her to find a solution?InputThe first line contains a single integer n (1\le n\le 1000) — the side length of the grid.The second line contains n integers r_1,r_2,\ldots,r_n (1\le r_i\le n) — if you walk into (i,1) facing right, you should exit the grid from (r_i,n). It is guaranteed that r_{1..n} is a permutation of n elements.The third line contains n integers c_1,c_2,\ldots,c_n (1\le c_i\le n) — if you walk into (1,i) facing bottom, you should exit the grid from (n,c_i). It is guaranteed that c_{1..n} is a permutation of n elements.OutputIf it is impossible to satisfy the rule, print the only number -1.Otherwise the first line should contain a single integer m (0\le m\le\frac{n^2}2) — the number of portals you set.In the following m lines, each line should contain four integers x_1,y_1,x_2,y_2, represents that you set a portal consisting of two doors in (x_1,y_1) and (x_2,y_2).If there are multiple answers, print any. You do not have to minimize m.ExamplesInput 3 1 3 2 3 1 2 Output 2 1 1 1 3 2 2 3 1Input 5 3 1 5 4 2 4 2 1 3 5 Output 3 1 1 3 4 2 2 3 2 2 3 5 1 NoteExample 1The cells with the same letter are a portal. You can set portals in this way:It satisfies the rule, because:Example 2You can set portals in this way:
3 1 3 2 3 1 2
2 1 1 1 3 2 2 3 1
2 seconds
256 megabytes
['constructive algorithms', '*2900']
C2. Nauuo and Pictures (hard version)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.Nauuo is a girl who loves random picture websites.One day she made a random picture website by herself which includes n pictures.When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The i-th picture has a non-negative weight w_i, and the probability of the i-th picture being displayed is \frac{w_i}{\sum_{j=1}^nw_j}. That is to say, the probability of a picture to be displayed is proportional to its weight.However, Nauuo discovered that some pictures she does not like were displayed too often. To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add 1 to its weight; otherwise, she would subtract 1 from its weight.Nauuo will visit the website m times. She wants to know the expected weight of each picture after all the m visits modulo 998244353. Can you help her?The expected weight of the i-th picture can be denoted by \frac {q_i} {p_i} where \gcd(p_i,q_i)=1, you need to print an integer r_i satisfying 0\le r_i<998244353 and r_i\cdot p_i\equiv q_i\pmod{998244353}. It can be proved that such r_i exists and is unique.InputThe first line contains two integers n and m (1\le n\le 2\cdot 10^5, 1\le m\le 3000) — the number of pictures and the number of visits to the website.The second line contains n integers a_1,a_2,\ldots,a_n (a_i is either 0 or 1) — if a_i=0 , Nauuo does not like the i-th picture; otherwise Nauuo likes the i-th picture. It is guaranteed that there is at least one picture which Nauuo likes.The third line contains n positive integers w_1,w_2,\ldots,w_n (w_i \geq 1) — the initial weights of the pictures. It is guaranteed that the sum of all the initial weights does not exceed 998244352-m.OutputThe output contains n integers r_1,r_2,\ldots,r_n — the expected weights modulo 998244353.ExamplesInput 2 1 0 1 2 1 Output 332748119 332748119 Input 1 2 1 1 Output 3 Input 3 3 0 1 1 4 3 5 Output 160955686 185138929 974061117 NoteIn the first example, if the only visit shows the first picture with a probability of \frac 2 3, the final weights are (1,1); if the only visit shows the second picture with a probability of \frac1 3, the final weights are (2,2).So, both expected weights are \frac2 3\cdot 1+\frac 1 3\cdot 2=\frac4 3 .Because 332748119\cdot 3\equiv 4\pmod{998244353}, you need to print 332748119 instead of \frac4 3 or 1.3333333333.In the second example, there is only one picture which Nauuo likes, so every time Nauuo visits the website, w_1 will be increased by 1.So, the expected weight is 1+2=3.Nauuo is very naughty so she didn't give you any hint of the third example.
2 1 0 1 2 1
332748119 332748119
4 seconds
256 megabytes
['dp', 'probabilities', '*2600']
C1. Nauuo and Pictures (easy version)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.Nauuo is a girl who loves random picture websites.One day she made a random picture website by herself which includes n pictures.When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The i-th picture has a non-negative weight w_i, and the probability of the i-th picture being displayed is \frac{w_i}{\sum_{j=1}^nw_j}. That is to say, the probability of a picture to be displayed is proportional to its weight.However, Nauuo discovered that some pictures she does not like were displayed too often. To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add 1 to its weight; otherwise, she would subtract 1 from its weight.Nauuo will visit the website m times. She wants to know the expected weight of each picture after all the m visits modulo 998244353. Can you help her?The expected weight of the i-th picture can be denoted by \frac {q_i} {p_i} where \gcd(p_i,q_i)=1, you need to print an integer r_i satisfying 0\le r_i<998244353 and r_i\cdot p_i\equiv q_i\pmod{998244353}. It can be proved that such r_i exists and is unique.InputThe first line contains two integers n and m (1\le n\le 50, 1\le m\le 50) — the number of pictures and the number of visits to the website.The second line contains n integers a_1,a_2,\ldots,a_n (a_i is either 0 or 1) — if a_i=0 , Nauuo does not like the i-th picture; otherwise Nauuo likes the i-th picture. It is guaranteed that there is at least one picture which Nauuo likes.The third line contains n integers w_1,w_2,\ldots,w_n (1\le w_i\le50) — the initial weights of the pictures.OutputThe output contains n integers r_1,r_2,\ldots,r_n — the expected weights modulo 998244353.ExamplesInput 2 1 0 1 2 1 Output 332748119 332748119 Input 1 2 1 1 Output 3 Input 3 3 0 1 1 4 3 5 Output 160955686 185138929 974061117 NoteIn the first example, if the only visit shows the first picture with a probability of \frac 2 3, the final weights are (1,1); if the only visit shows the second picture with a probability of \frac1 3, the final weights are (2,2).So, both expected weights are \frac2 3\cdot 1+\frac 1 3\cdot 2=\frac4 3 .Because 332748119\cdot 3\equiv 4\pmod{998244353}, you need to print 332748119 instead of \frac4 3 or 1.3333333333.In the second example, there is only one picture which Nauuo likes, so every time Nauuo visits the website, w_1 will be increased by 1.So, the expected weight is 1+2=3.Nauuo is very naughty so she didn't give you any hint of the third example.
2 1 0 1 2 1
332748119 332748119
4 seconds
256 megabytes
['dp', 'probabilities', '*2300']
B. Nauuo and Circletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNauuo is a girl who loves drawing circles.One day she has drawn a circle and wanted to draw a tree on it.The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other."Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,\ldots,p_n in which every integer from 1 to n appears exactly once.After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.InputThe first line contains a single integer n (2\le n\le 2\cdot 10^5) — the number of nodes in the tree.Each of the next n-1 lines contains two integers u and v (1\le u,v\le n), denoting there is an edge between u and v.It is guaranteed that the given edges form a tree.OutputThe output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.ExamplesInput 4 1 2 1 3 2 4 Output 16Input 4 1 2 1 3 1 4 Output 24NoteExample 1All valid permutations and their spanning trees are as follows.Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.Example 2Every permutation leads to a valid tree, so the answer is 4! = 24.
4 1 2 1 3 2 4
16
2 seconds
256 megabytes
['combinatorics', 'dfs and similar', 'dp', 'trees', '*1900']
A. Nauuo and Cardstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNauuo is a girl who loves playing cards.One day she was playing cards but found that the cards were mixed with some empty ones.There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n cards in the pile are also given in the order from top to bottom.In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile.Nauuo wants to make the n numbered cards piled up in increasing order (the i-th card in the pile from top to bottom is the card i) as quickly as possible. Can you tell her the minimum number of operations?InputThe first line contains a single integer n (1\le n\le 2\cdot 10^5) — the number of numbered cards.The second line contains n integers a_1,a_2,\ldots,a_n (0\le a_i\le n) — the initial cards in Nauuo's hands. 0 represents an empty card.The third line contains n integers b_1,b_2,\ldots,b_n (0\le b_i\le n) — the initial cards in the pile, given in order from top to bottom. 0 represents an empty card.It is guaranteed that each number from 1 to n appears exactly once, either in a_{1..n} or b_{1..n}.OutputThe output contains a single integer — the minimum number of operations to make the n numbered cards piled up in increasing order.ExamplesInput 3 0 2 0 3 0 1 Output 2Input 3 0 2 0 1 0 3 Output 4Input 11 0 0 0 5 0 0 0 4 0 0 11 9 2 6 0 8 1 7 0 3 0 10 Output 18NoteExample 1We can play the card 2 and draw the card 3 in the first operation. After that, we have [0,3,0] in hands and the cards in the pile are [0,1,2] from top to bottom.Then, we play the card 3 in the second operation. The cards in the pile are [1,2,3], in which the cards are piled up in increasing order.Example 2Play an empty card and draw the card 1, then play 1, 2, 3 in order.
3 0 2 0 3 0 1
2
1.5 seconds
256 megabytes
['greedy', 'implementation', '*1800']
I. Good Subsetstime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n segments on the Ox axis. The i-th segment is given as a pair l_i, r_i, where l_i is the position of the left end of the i-th segment and r_i is the position of the right end of the i-th segment. Segments may intersect, overlap, or even coincide. A segment is a set of numbers (including floating-point numbers) lying between the segment ends or coinciding with them. Formally, the segment [l, r]=\{x~|~x \in \Bbb{R},~l \le x \le r\}.Let the union of segments be the set of all axis points covered by the set of segments. Let's call a subset of the given segments good if its union equals the union of all n segments.Your task is to calculate the number of good subsets of the given n segments. Since the answer may be very large, print it modulo 998244353.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of segments.The next n lines contain segments. The i-th segment is given as a pair l_i, r_i (1 \le l_i \le r_i \le 10^9), where l_i is the left border of the segment and r_i is the right border of the segment. Segments may intersect, overlap, or even coincide.OutputPrint the number of good subsets of the given set of segments. Since the answer may be very large, print it modulo 998244353.ExamplesInput 3 1 1 2 6 1 6 Output 4 Input 2 3 4 2 5 Output 2 Input 4 1 2 5 5 2 3 1 3 Output 5
3 1 1 2 6 1 6
4
6 seconds
256 megabytes
['*special problem', 'dp']
H. Longest Sawtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given the sequence a_1, a_2, \dots, a_n. You can choose any subset of elements and then reorder them to create a "saw".The sequence b_1, b_2, \dots, b_m is called a "saw" if the elements satisfy one of the following series of inequalities: b_1>b_2<b_3>b_4<\dots or b_1<b_2>b_3<b_4>\dots.Find the longest saw which can be obtained from a given array.Note that both the given sequence a and the required saw b can contain duplicated (non-unique) values.InputThe first line contains an integer t (1 \le t \le 10^5) — the number of test cases in the input. Then the descriptions of the t test cases follow. Each test case begins with a line containing integer n (1 \le n \le 2\cdot10^5). Then a line containing n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) follows.It's guaranteed that \sum{n} doesn't exceed 2 \cdot 10^5.OutputFor each test case, print two lines: print the length of the longest saw in the first line, and the saw itself in the second line. If there are several solutions, print any of them.ExampleInput 3 10 10 9 8 7 6 5 4 3 2 1 7 1 2 2 2 3 2 2 3 100 100 100 Output 10 1 6 2 7 3 8 4 9 5 10 4 2 1 3 2 1 100
3 10 10 9 8 7 6 5 4 3 2 1 7 1 2 2 2 3 2 2 3 100 100 100
10 1 6 2 7 3 8 4 9 5 10 4 2 1 3 2 1 100
3 seconds
256 megabytes
['*special problem', 'constructive algorithms']
G. Graph Decompositiontime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph consisting of n vertices and m edges.Recall that a cycle is a path that starts and ends in the same vertex. A cycle in a graph is called simple if it contains each vertex (except the starting and ending one) no more than once (the starting and the ending one is contained always twice). Note that loops are considered to be simple cycles.In one move you can choose any simple cycle in this graph and erase the edges corresponding to this cycle (corresponding vertices remain in the graph). It is allowed to erase the loop or two copies of the same edge (take a look at examples).Your problem is to apply some sequence of moves to obtain the graph without edges. It is not necessary to minimize the number of cycles. If it is impossible, print "NO".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 and the number of edges in the graph.The next m lines contain edges of the graph. The i-th line contains the i-th edge x_i, y_i (1 \le x_i, y_i \le n), where x_i and y_i are vertices connected by the i-th edge. The graph can contain loops or multiple edges.OutputIf it is impossible to decompose the given graph into simple cycles, print "NO" in the first line.Otherwise print "YES" in the first line. In the second line print k — the number of simple cycles in the graph decomposition.In the next k lines print cycles themselves. The j-th line should contain the j-th cycle. First, print c_j — the number of vertices in the j-th cycle. Then print the cycle as a sequence of vertices. All neighbouring (adjacent) vertices in the printed path should be connected by an edge that isn't contained in other cycles.ExamplesInput 6 9 1 2 2 3 1 3 2 4 2 5 4 5 3 5 3 6 5 6 Output YES 3 4 2 5 4 2 4 3 6 5 3 4 1 3 2 1 Input 4 7 1 1 1 2 2 3 3 4 4 1 1 3 1 3 Output YES 3 2 1 1 5 1 4 3 2 1 3 1 3 1 Input 4 8 1 1 1 2 2 3 3 4 4 1 2 4 1 3 1 3 Output NO NoteThe picture corresponding to the first example:
6 9 1 2 2 3 1 3 2 4 2 5 4 5 3 5 3 6 5 6
YES 3 4 2 5 4 2 4 3 6 5 3 4 1 3 2 1
6 seconds
256 megabytes
['*special problem', 'graphs']
F. Wheelstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has n wheels and a car with m slots for wheels. The initial pressure in the i-th wheel is a_i.Polycarp's goal is to take exactly m wheels among the given n wheels and equalize the pressure in them (then he can put these wheels in a car and use it for driving). In one minute he can decrease or increase the pressure in any (single) wheel by 1. He can increase the pressure no more than k times in total because it is hard to pump up wheels.Help Polycarp and say what is the minimum number of minutes he needs to spend to equalize the pressure of at least m wheels among the given n wheels.InputThe first line of the input contains three integers n, m and k (1 \le m \le n \le 2 \cdot 10^5, 0 \le k \le 10^9) — the number of wheels, the number of slots for wheels in a car and the number of times Polycarp can increase by 1 the pressure in a wheel.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the pressure in the i-th wheel.OutputPrint one integer — the minimum number of minutes Polycarp needs to spend to equalize the pressure in at least m wheels among the given n wheels.ExamplesInput 6 6 7 6 15 16 20 1 5 Output 39 Input 6 3 1 4 8 15 16 23 42 Output 8 Input 5 4 0 5 5 5 4 5 Output 0
6 6 7 6 15 16 20 1 5
39
3 seconds
256 megabytes
['*special problem', 'binary search', 'greedy']
E. Sliding Doorstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputImagine that you are the CEO of a big old-fashioned company. Unlike any modern and progressive company (such as JetBrains), your company has a dress code. That's why you have already allocated a spacious room for your employees where they can change their clothes. Moreover, you've already purchased an m-compartment wardrobe, so the i-th employee can keep his/her belongings in the i-th cell (of course, all compartments have equal widths).The issue has occurred: the wardrobe has sliding doors! More specifically, the wardrobe has n doors (numbered from left to right) and the j-th door has width equal to a_j wardrobe's cells. The wardrobe has single rails so that no two doors can slide past each other. Extremely schematic example of a wardrobe: m=9, n=2, a_1=2, a_2=3. The problem is as follows: sometimes to open some cells you must close some other cells (since all doors are placed on the single track). For example, if you have a 4-compartment wardrobe (i.e. m=4) with n=2 one-cell doors (i.e. a_1=a_2=1) and you need to open the 1-st and the 3-rd cells, you have to close the 2-nd and the 4-th cells.As CEO, you have a complete schedule for the next q days. Now you are wondering: is it possible that all employees who will come on the k-th day can access their cells simultaneously?InputThe first line contains two integers n and m (1 \le n \le 2 \cdot 10^5, 1 \le m \le 4 \cdot 10^5) — the number of doors and compartments respectively.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le m, \sum{a_i} \le m) — the corresponding widths of the doors.The third line contains a single integer q (1 \le q \le 2 \cdot 10^5) — the number of days you have to process.The next q lines describe schedule of each day. Each schedule is represented as an integer c_k followed by c_k integers w_1, w_2, \dots, w_{c_k} (1 \le c_k \le 2 \cdot 10^5, 1 \le w_1 < w_2 < \dots < w_{c_k} \le m) — the number of employees who will come on the k-th day, and their indices in ascending order.It's guaranteed that \sum{c_k} doesn't exceed 2 \cdot 10^5.OutputPrint q answers. Each answer is "YES" or "NO" (case insensitive). Print "YES" if it is possible, that all employees on the corresponding day can access their compartments simultaneously.ExampleInput 3 10 2 3 2 6 1 5 2 1 10 2 2 9 2 5 6 3 1 7 8 4 1 2 3 4 Output YES YES NO NO YES NO
3 10 2 3 2 6 1 5 2 1 10 2 2 9 2 5 6 3 1 7 8 4 1 2 3 4
YES YES NO NO YES NO
3 seconds
256 megabytes
['*special problem', 'binary search']
D. Decoding of Integer Sequencestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is developing a method for transmitting n integer sequences over a network. This method should support the transmission of an arbitrary number of integer sequences; sequences can have different lengths. The sequences contain arbitrary non-negative integers.Polycarp developed the following encoding procedure: We assume that the sequences are numbered from 1 to n. We add a special terminating marker to each sequence at the end, an element equal to -1. The encoding result is a new single sequence that contains all the elements of the specified n in a special order: first, add to the result of coding all the first elements of the sequences (in the order from the 1-st to the n-th), then all the second elements (in the order from the 1-st to the n-th) and so on, if the sequence does not have the corresponding element, then it is simply skipped. The process ends when all elements of all sequences are added. For example, if you want to encode three sequences [3, 1, 4], [2, 7] and [1, 2, 3, 4], then the sequence of actions will be as follows: we modify all three sequences by appending -1: [3, 1, 4, -1], [2, 7, -1] and [1, 2, 3, 4, -1]; we write out all the first elements, we get [3, 2, 1]; then write down all the second elements, we get [3, 2, 1, 1, 7, 2]; then write down all the third elements, we get [3, 2, 1, 1, 7, 2, 4, -1, 3]; then write down all fourth elements, get [3, 2, 1, 1, 7, 2, 4, -1, 3, -1, 4] (note that the second sequence has already ended); then write down all the fifth elements, we get [3, 2, 1, 1, 7, 2, 4, -1, 3, -1, 4, -1] (note that the first and second sequences have already ended); all the sequences are ended now, and the encoding process is finished; the encoding result is: [3, 2, 1, 1, 7, 2, 4, -1, 3, -1, 4, -1]. Your task is to implement decoding by a given encoding result.InputThe first line contains integer number m (1 \le m \le 3\cdot10^5), denoting the length of the encoding result. The second line contains the result of encoding as a sequence of integers b_1, b_2, \dots, b_m (-1 \le b_i \le 100).It is guaranteed that in the initial sequences before encoding contains only non-negative integers from 0 to 100, that you are in fact given the result of correct encoding (in other words, it is guaranteed that the answer exists). It is possible that one or more initial sequences were empty before encoding.OutputPrint n, where n is the number of encoded sequences. Then print n lines in the format k_i, a_{i1}, a_{i2}, \dots, a_{ik_i}, where k_i is the length of the i-th sequence, and a_{i1}, a_{i2}, \dots, a_{ik_i} are its elements. Separate the numbers in the lines with spaces. Please note that the encoding procedure is such that every possible encoding result can be decoded in only one way.ExamplesInput 12 3 2 1 1 7 2 4 -1 3 -1 4 -1 Output 3 3 3 1 4 2 2 7 4 1 2 3 4 Input 6 2 -1 2 -1 3 -1 Output 3 1 2 0 2 2 3
12 3 2 1 1 7 2 4 -1 3 -1 4 -1
3 3 3 1 4 2 2 7 4 1 2 3 4
3 seconds
256 megabytes
['*special problem', 'data structures', 'implementation']
C. Minus and Minus Give Plustime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEveryone knows that two consecutive (adjacent) "minus" signs can be replaced with a single "plus" sign.You are given the string s, consisting of "plus" and "minus" signs only. Zero or more operations can be performed with it. In each operation you can choose any two adjacent "minus" signs, and replace them with a single "plus" sign. Thus, in one operation, the length of the string is reduced by exactly 1.You are given two strings s and t. Determine if you can use 0 or more operations to get the string t from the string s.InputThe first line of the input contains an integer k (1 \le k \le 10^5), denoting the number of test cases in the input. The following lines contain descriptions of the test sets, each set consists of two lines. First comes the line containing s (the length of the line s does not exceed 2\cdot10^5), then comes the line containing t (the length of the line t does not exceed 2\cdot10^5). The lines s and t are non-empty, and they contain only "plus" and "minus" signs.The sum of the lengths of lines s over all test cases in the input does not exceed 2\cdot10^5. Similarly, the sum of the lengths of lines t over all test cases in the input does not exceed 2\cdot10^5.OutputPrint k lines: the i-th line must contain YES if the answer to the i-th test case is positive, otherwise NO. Print YES and NO using uppercase letters only.ExampleInput 5 -+--+ -+++ -------- -+--+- - + -- --- +++ +++ Output YES YES NO NO YES
5 -+--+ -+++ -------- -+--+- - + -- --- +++ +++
YES YES NO NO YES
3 seconds
256 megabytes
['*special problem', 'implementation', 'strings']
B. Bad Daystime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvery day Kotlin heroes analyze the statistics of their website. For n days, they wrote out n numbers a_1, a_2, \dots, a_n, where a_i is the number of visits on the i-th day.They believe that a day is bad if there are at least 2 days before it with a strictly greater number of visits. For example, if n=8 and a=[3, 1, 4, 1, 5, 9, 2, 6], then the day 4 is bad (because a_4=1, but there are a_1=3 and a_3=4). Also, the day with the number 7 is bad too.Write a program that finds the number of bad days.InputThe first line contains an integer n (1 \le n \le 2\cdot10^5), where n is the number of days. The second line contains n positive integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the number of website visits on the i-th day.OutputPrint the number of bad days, i.e. such days that there are at least two days before it with a strictly greater number of visits.ExamplesInput 8 3 1 4 1 5 9 2 6 Output 2 Input 5 1 1 1 1 1 Output 0 Input 13 2 7 1 8 2 8 1 8 2 8 4 5 9 Output 6
8 3 1 4 1 5 9 2 6
2
3 seconds
256 megabytes
['*special problem', 'implementation']
A. Three Integers Againtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe have three positive integers a, b and c. You don't know their values, but you know some information about them. Consider all three pairwise sums, i.e. the numbers a+b, a+c and b+c. You know exactly two (any) of three pairwise sums.Your task is to find such three positive integers a, b and c which match the given information. It means that if you consider a+b, a+c and b+c, two out of all three of them are given in the input. Among all such triples, you must choose one with the minimum possible sum a+b+c, and among all triples with the minimum sum, you can print any.You have to process q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 1000) — the number of queries.The next q lines contain queries. Each query is given as two integers x and y (2 \le x, y \le 2 \cdot 10^9), where x and y are any two out of the three numbers a+b, a+c and b+c.OutputFor each query print the answer to it: three positive integers a, b and c consistent with the given information. Among all such triples, you have to choose one with the minimum possible sum a+b+c. Among all triples with the minimum sum, you can print any.ExampleInput 3 123 13 2 2 2000000000 2000000000 Output 111 1 12 1 1 1 1999999999 1 1
3 123 13 2 2 2000000000 2000000000
111 1 12 1 1 1 1999999999 1 1
1 second
256 megabytes
['*special problem', 'math']
B. Pairstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToad Ivan has m pairs of integers, each integer is between 1 and n, inclusive. The pairs are (a_1, b_1), (a_2, b_2), \ldots, (a_m, b_m). He asks you to check if there exist two integers x and y (1 \leq x < y \leq n) such that in each given pair at least one integer is equal to x or y.InputThe first line contains two space-separated integers n and m (2 \leq n \leq 300\,000, 1 \leq m \leq 300\,000) — the upper bound on the values of integers in the pairs, and the number of given pairs.The next m lines contain two integers each, the i-th of them contains two space-separated integers a_i and b_i (1 \leq a_i, b_i \leq n, a_i \neq b_i) — the integers in the i-th pair.OutputOutput "YES" if there exist two integers x and y (1 \leq x < y \leq n) such that in each given pair at least one integer is equal to x or y. Otherwise, print "NO". You can print each letter in any case (upper or lower).ExamplesInput 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output NO Input 5 4 1 2 2 3 3 4 4 5 Output YES Input 300000 5 1 2 1 2 1 2 1 2 1 2 Output YES NoteIn the first example, you can't choose any x, y because for each such pair you can find a given pair where both numbers are different from chosen integers.In the second example, you can choose x=2 and y=4.In the third example, you can choose x=1 and y=2.
4 6 1 2 1 3 1 4 2 3 2 4 3 4
NO
2 seconds
256 megabytes
['graphs', 'implementation', '*1500']
A. Circle Metrotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe circle line of the Roflanpolis subway has n stations.There are two parallel routes in the subway. The first one visits stations in order 1 \to 2 \to \ldots \to n \to 1 \to 2 \to \ldots (so the next stop after station x is equal to (x+1) if x < n and 1 otherwise). The second route visits stations in order n \to (n-1) \to \ldots \to 1 \to n \to (n-1) \to \ldots (so the next stop after station x is equal to (x-1) if x>1 and n otherwise). All trains depart their stations simultaneously, and it takes exactly 1 minute to arrive at the next station.Two toads live in this city, their names are Daniel and Vlad.Daniel is currently in a train of the first route at station a and will exit the subway when his train reaches station x.Coincidentally, Vlad is currently in a train of the second route at station b and he will exit the subway when his train reaches station y.Surprisingly, all numbers a,x,b,y are distinct.Toad Ilya asks you to check if Daniel and Vlad will ever be at the same station at the same time during their journey. In other words, check if there is a moment when their trains stop at the same station. Note that this includes the moments when Daniel or Vlad enter or leave the subway.InputThe first line contains five space-separated integers n, a, x, b, y (4 \leq n \leq 100, 1 \leq a, x, b, y \leq n, all numbers among a, x, b, y are distinct) — the number of stations in Roflanpolis, Daniel's start station, Daniel's finish station, Vlad's start station and Vlad's finish station, respectively.OutputOutput "YES" if there is a time moment when Vlad and Daniel are at the same station, and "NO" otherwise. You can print each letter in any case (upper or lower).ExamplesInput 5 1 4 3 2 Output YES Input 10 2 1 9 10 Output NO NoteIn the first example, Daniel and Vlad start at the stations (1, 3). One minute later they are at stations (2, 2). They are at the same station at this moment. Note that Vlad leaves the subway right after that.Consider the second example, let's look at the stations Vlad and Daniel are at. They are: initially (2, 9), after 1 minute (3, 8), after 2 minutes (4, 7), after 3 minutes (5, 6), after 4 minutes (6, 5), after 5 minutes (7, 4), after 6 minutes (8, 3), after 7 minutes (9, 2), after 8 minutes (10, 1), after 9 minutes (1, 10). After that, they both leave the subway because they are at their finish stations, so there is no moment when they both are at the same station.
5 1 4 3 2
YES
1 second
256 megabytes
['implementation', 'math', '*900']
E. Xor Permutationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToad Mikhail has an array of 2^k integers a_1, a_2, \ldots, a_{2^k}.Find two permutations p and q of integers 0, 1, \ldots, 2^k-1, such that a_i is equal to p_i \oplus q_i for all possible i, or determine there are no such permutations. Here \oplus denotes the bitwise XOR operation.InputThe first line contains one integer k (2 \leq k \leq 12), denoting that the size of the array is 2^k.The next line contains 2^k space-separated integers a_1, a_2, \ldots, a_{2^k} (0 \leq a_i < 2^k) — the elements of the given array.OutputIf the given array can't be represented as element-wise XOR of two permutations of integers 0, 1, \ldots, 2^k-1, print "Fou".Otherwise, print "Shi" in the first line.The next two lines should contain the description of two suitable permutations. The first of these lines should contain 2^k space-separated distinct integers p_{1}, p_{2}, \ldots, p_{2^k}, and the second line should contain 2^k space-separated distinct integers q_{1}, q_{2}, \ldots, q_{2^k}.All elements of p and q should be between 0 and 2^k - 1, inclusive; p_i \oplus q_i should be equal to a_i for all i such that 1 \leq i \leq 2^k. If there are several possible solutions, you can print any.ExamplesInput 2 0 1 2 3 Output Shi 2 0 1 3 2 1 3 0 Input 2 0 0 0 0 Output Shi 0 1 2 3 0 1 2 3 Input 2 0 1 2 2 Output Fou
2 0 1 2 3
Shi 2 0 1 3 2 1 3 0
1 second
256 megabytes
['constructive algorithms', 'math', '*3100']
D. Anagram Pathstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToad Ilya has a rooted binary tree with vertex 1 being the root. A tree is a connected graph without cycles. A tree is rooted if one vertex is selected and called the root. A vertex u is a child of a vertex v if u and v are connected by an edge and v is closer to the root than u. A leaf is a non-root vertex that has no children.In the tree Ilya has each vertex has at most two children, and each edge has some character written on it. The character can be a lowercase English letter or the question mark '?'.Ilya will q times update the tree a bit. Each update will replace exactly one character on some edge. After each update Ilya needs to find if the tree is anagrammable and if yes, find its anagramnity for each letter. Well, that's difficult to explain, but we'll try.To start with, a string a is an anagram of a string b if it is possible to rearrange letters in a (without changing the letters itself) so that it becomes b. For example, the string "fortyfive" is an anagram of the string "overfifty", but the string "aabb" is not an anagram of the string "bbba".Consider a path from the root of the tree to a leaf. The characters on the edges on this path form a string, we say that this string is associated with this leaf. The tree is anagrammable if and only if it is possible to replace each question mark with a lowercase English letter so that for all pair of leaves the associated strings for these leaves are anagrams of each other.If the tree is anagrammable, then its anagramnity for the letter c is the maximum possible number of letters c in a string associated with some leaf in a valid replacement of all question marks.Please after each update find if the tree is anagrammable and if yes, find the \sum{f(c) \cdot ind(c)} for all letters c, where f(c) is the anagramnity for the letter c, and ind(x) is the index of this letter in the alphabet (ind("a") = 1, ind("b") = 2, ..., ind("z") = 26).InputThe first line of input contains two integers n and q (2 \leq n \leq 150\,000, 1 \leq q \leq 150\,000) — the number of vertices in the tree and the number of queries.The next n-1 lines describe the initial tree. The i-th of them contains an integer p_i and a character c_i (1 \leq p_i \leq i, c_i is a lowercase English letter or the question mark '?') describing an edge between vertices p_i and i+1 with character c_i written on it.The root of this tree is the vertex 1, and each vertex has at most two children.The next q lines describe the queries. The i-th of them contains two integers v and c (2 \leq v \leq n, c is a lowercase English letter or the question mark '?'), meaning that updated character on the edge between p_{v-1} to v is c. The updated character can be the same as was written before.OutputOutput q lines. In the i-th of them print "Fou" if the tree is not anagrammable after the first i updates.Otherwise output "Shi" and the \sum{f(c) \cdot ind(c)} for all letters c.ExamplesInput 3 4 1 ? 1 ? 2 ? 2 a 3 b 2 b Output Shi 351 Shi 1 Fou Shi 2 Input 5 2 1 ? 1 ? 2 ? 3 ? 4 a 5 b Output Shi 352 Shi 3 NoteIn the first example after the first query, for each character, you can set all edges equal to that character, and you will get 1 such character on each path, so the answer is 1 \cdot (1+2+\ldots+26) = 351.In the first example after the second query, you know that all paths should be an anagram of "a", so all paths should be "a", so the answer is 1 \cdot 1 = 1.In the first example after the third query, you have two paths with strings "a" and "b", but these strings are not anagrams, so the answer is "Fou".In the first example after the fourth query, you know that all paths should be "b", so the answer is 1 \cdot 2 = 2.In the second example after the first query, you know that f('a') = 2 and f(c) = 1 for all other characters, so the answer is 1 \cdot (2 + 3 + \ldots + 26) + 2 = 352.In the second example after the second query, you know that each path should contain one 'a' and one 'b', so the answer is 1 \cdot 1 + 1 \cdot 2 = 3.
3 4 1 ? 1 ? 2 ? 2 a 3 b 2 b
Shi 351 Shi 1 Fou Shi 2
4 seconds
256 megabytes
['dp', 'implementation', 'trees', '*3000']
C. And Reachabilitytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToad Pimple has an array of integers a_1, a_2, \ldots, a_n.We say that y is reachable from x if x<y and there exists an integer array p such that x = p_1 < p_2 < \ldots < p_k=y, and a_{p_i}\, \&\, a_{p_{i+1}} > 0 for all integers i such that 1 \leq i < k.Here \& denotes the bitwise AND operation.You are given q pairs of indices, check reachability for each of them.InputThe first line contains two integers n and q (2 \leq n \leq 300\,000, 1 \leq q \leq 300\,000) — the number of integers in the array and the number of queries you need to answer.The second line contains n space-separated integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 300\,000) — the given array.The next q lines contain two integers each. The i-th of them contains two space-separated integers x_i and y_i (1 \leq x_i < y_i \leq n). You need to check if y_i is reachable from x_i. OutputOutput q lines. In the i-th of them print "Shi" if y_i is reachable from x_i, otherwise, print "Fou".ExampleInput 5 3 1 3 0 2 1 1 3 2 4 1 4 Output Fou Shi Shi NoteIn the first example, a_3 = 0. You can't reach it, because AND with it is always zero. a_2\, \&\, a_4 > 0, so 4 is reachable from 2, and to go from 1 to 4 you can use p = [1, 2, 4].
5 3 1 3 0 2 1 1 3 2 4 1 4
Fou Shi Shi
3 seconds
256 megabytes
['bitmasks', 'dp', '*2200']
B. Good Tripletime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToad Rash has a binary string s. A binary string consists only of zeros and ones.Let n be the length of s.Rash needs to find the number of such pairs of integers l, r that 1 \leq l \leq r \leq n and there is at least one pair of integers x, k such that 1 \leq x, k \leq n, l \leq x < x + 2k \leq r, and s_x = s_{x+k} = s_{x+2k}.Find this number of pairs for Rash.InputThe first line contains the string s (1 \leq |s| \leq 300\,000), consisting of zeros and ones.OutputOutput one integer: the number of such pairs of integers l, r that 1 \leq l \leq r \leq n and there is at least one pair of integers x, k such that 1 \leq x, k \leq n, l \leq x < x + 2k \leq r, and s_x = s_{x+k} = s_{x+2k}.ExamplesInput 010101 Output 3 Input 11001100 Output 0 NoteIn the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.In the second example, there are no values x, k for the initial string, so the answer is 0.
010101
3
4 seconds
256 megabytes
['brute force', 'two pointers', '*1900']
A. Increasing by Modulotime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, \ldots, a_n.In one operation Zitz can choose an integer k and k indices i_1, i_2, \ldots, i_k such that 1 \leq i_1 < i_2 < \ldots < i_k \leq n. He should then change a_{i_j} to ((a_{i_j}+1) \bmod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.Here x \bmod y denotes the remainder of the division of x by y.Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.InputThe first line contains two integers n and m (1 \leq n, m \leq 300\,000) — the number of integers in the array and the parameter m.The next line contains n space-separated integers a_1, a_2, \ldots, a_n (0 \leq a_i < m) — the given array.OutputOutput one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.It is easy to see that with enough operations Zitz can always make his array non-decreasing.ExamplesInput 5 3 0 0 0 1 2 Output 0 Input 5 7 0 6 1 3 2 Output 1 NoteIn the first example, the array is already non-decreasing, so the answer is 0.In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
5 3 0 0 0 1 2
0
2.5 seconds
256 megabytes
['binary search', 'greedy', '*1700']
G. Low Budget Inceptiontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSo we got bored and decided to take our own guess at how would "Inception" production go if the budget for the film had been terribly low.The first scene we remembered was the one that features the whole city bending onto itself: It feels like it will require high CGI expenses, doesn't it? Luckily, we came up with a similar-looking scene which was a tiny bit cheaper to make.Firstly, forget about 3D, that's hard and expensive! The city is now represented as a number line (infinite to make it easier, of course).Secondly, the city doesn't have to look natural at all. There are n buildings on the line. Each building is a square 1 \times 1. Buildings are numbered from 1 to n in ascending order of their positions. Lower corners of building i are at integer points a_i and a_i + 1 of the number line. Also the distance between any two neighbouring buildings i and i + 1 doesn't exceed d (really, this condition is here just to make the city look not that sparse). Distance between some neighbouring buildings i and i + 1 is calculated from the lower right corner of building i to the lower left corner of building i + 1.Finally, curvature of the bend is also really hard to simulate! Let the bend at some integer coordinate x be performed with the following algorithm. Take the ray from x to +\infty and all the buildings which are on this ray and start turning the ray and the buildings counter-clockwise around point x. At some angle some building will touch either another building or a part of the line. You have to stop bending there (implementing buildings crushing is also not worth its money). Let's call the angle between two rays in the final state the terminal angle \alpha_x.The only thing left is to decide what integer point x is the best to start bending around. Fortunately, we've already chosen m candidates to perform the bending.So, can you please help us to calculate terminal angle \alpha_x for each bend x from our list of candidates?InputThe first line contains two integer numbers n and d (1 \le n \le 2 \cdot 10^5, 0 \le d \le 7000) — the number of buildings and the maximum distance between any pair of neighbouring buildings, respectively.The second line contains n integers a_1, a_2, \dots, a_n (a_1 = 0, 0 < a_{i + 1} - a_i \le d + 1) — coordinates of left corners of corresponding buildings in ascending order.The third line contains single integer m (1 \le m \le 2 \cdot 10^5) — the number of candidates.The fourth line contains m integers x_1, x_2, \dots, x_m (0 \le x_i \le a_n + 1, x_i < x_{i + 1}) — the coordinates of bends you need to calculate terminal angles for in ascending order.OutputPrint m numbers. For each bend x_i print terminal angle \alpha_{x_i} (in radians).Your answer is considered correct if its absolute error does not exceed 10^{-9}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if |a - b| \le 10^{-9}.ExamplesInput 3 5 0 5 7 9 0 1 2 3 4 5 6 7 8 Output 1.570796326794897 1.570796326794897 0.785398163397448 0.927295218001612 0.785398163397448 1.570796326794897 1.570796326794897 1.570796326794897 1.570796326794897 Input 2 7 0 4 3 1 3 4 Output 1.570796326794897 0.927295218001612 1.570796326794897 Input 5 0 0 1 2 3 4 6 0 1 2 3 4 5 Output 1.570796326794897 3.141592653589793 3.141592653589793 3.141592653589793 3.141592653589793 1.570796326794897 NoteHere you can see the picture of the city for the first example and the bend at position 2 for it. The angle you need to measure is marked blue. You can see that it's equal to \frac \pi 4.You can see that no pair of neighbouring buildings have distance more than 4 between them. d = 4 would also suffice for that test.
3 5 0 5 7 9 0 1 2 3 4 5 6 7 8
1.570796326794897 1.570796326794897 0.785398163397448 0.927295218001612 0.785398163397448 1.570796326794897 1.570796326794897 1.570796326794897 1.570796326794897
3 seconds
256 megabytes
['brute force', 'geometry', '*3100']
F. Scalar Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots, a_n. All a_i are pairwise distinct.Let's define function f(l, r) as follows: let's define array b_1, b_2, \dots, b_{r - l + 1}, where b_i = a_{l - 1 + i}; sort array b in increasing order; result of the function f(l, r) is \sum\limits_{i = 1}^{r - l + 1}{b_i \cdot i}. Calculate \left(\sum\limits_{1 \le l \le r \le n}{f(l, r)}\right) \mod (10^9+7), i.e. total sum of f for all subsegments of a modulo 10^9+7.InputThe first line contains one integer n (1 \le n \le 5 \cdot 10^5) — the length of array a.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9, a_i \neq a_j for i \neq j) — array a.OutputPrint one integer — the total sum of f for all subsegments of a modulo 10^9+7ExamplesInput 4 5 2 4 7 Output 167 Input 3 123456789 214365879 987654321 Output 582491518 NoteDescription of the first example: f(1, 1) = 5 \cdot 1 = 5; f(1, 2) = 2 \cdot 1 + 5 \cdot 2 = 12; f(1, 3) = 2 \cdot 1 + 4 \cdot 2 + 5 \cdot 3 = 25; f(1, 4) = 2 \cdot 1 + 4 \cdot 2 + 5 \cdot 3 + 7 \cdot 4 = 53; f(2, 2) = 2 \cdot 1 = 2; f(2, 3) = 2 \cdot 1 + 4 \cdot 2 = 10; f(2, 4) = 2 \cdot 1 + 4 \cdot 2 + 7 \cdot 3 = 31; f(3, 3) = 4 \cdot 1 = 4; f(3, 4) = 4 \cdot 1 + 7 \cdot 2 = 18; f(4, 4) = 7 \cdot 1 = 7;
4 5 2 4 7
167
2 seconds
256 megabytes
['combinatorics', 'data structures', 'math', 'sortings', '*2300']
E. Range Deletingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array consisting of n integers a_1, a_2, \dots , a_n and an integer x. It is guaranteed that for every i, 1 \le a_i \le x.Let's denote a function f(l, r) which erases all values such that l \le a_i \le r from the array a and returns the resulting array. For example, if a = [4, 1, 1, 4, 5, 2, 4, 3], then f(2, 4) = [1, 1, 5].Your task is to calculate the number of pairs (l, r) such that 1 \le l \le r \le x and f(l, r) is sorted in non-descending order. Note that the empty array is also considered sorted.InputThe first line contains two integers n and x (1 \le n, x \le 10^6) — the length of array a and the upper limit for its elements, respectively.The second line contains n integers a_1, a_2, \dots a_n (1 \le a_i \le x).OutputPrint the number of pairs 1 \le l \le r \le x such that f(l, r) is sorted in non-descending order.ExamplesInput 3 3 2 3 1 Output 4 Input 7 4 1 3 1 2 2 4 3 Output 6 NoteIn the first test case correct pairs are (1, 1), (1, 2), (1, 3) and (2, 3).In the second test case correct pairs are (1, 3), (1, 4), (2, 3), (2, 4), (3, 3) and (3, 4).
3 3 2 3 1
4
2 seconds
256 megabytes
['binary search', 'combinatorics', 'data structures', 'two pointers', '*2100']
D. Bicolored RBStime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and "(()" are not.We can see that each opening bracket in RBS is paired with some closing bracket, and, using this fact, we can define nesting depth of the RBS as maximum number of bracket pairs, such that the 2-nd pair lies inside the 1-st one, the 3-rd one — inside the 2-nd one and so on. For example, nesting depth of "" is 0, "()()()" is 1 and "()((())())" is 3.Now, you are given RBS s of even length n. You should color each bracket of s into one of two colors: red or blue. Bracket sequence r, consisting only of red brackets, should be RBS, and bracket sequence, consisting only of blue brackets b, should be RBS. Any of them can be empty. You are not allowed to reorder characters in s, r or b. No brackets can be left uncolored.Among all possible variants you should choose one that minimizes maximum of r's and b's nesting depth. If there are multiple solutions you can print any of them.InputThe first line contains an even integer n (2 \le n \le 2 \cdot 10^5) — the length of RBS s.The second line contains regular bracket sequence s (|s| = n, s_i \in \{"(", ")"\}).OutputPrint single string t of length n consisting of "0"-s and "1"-s. If t_i is equal to 0 then character s_i belongs to RBS r, otherwise s_i belongs to b.ExamplesInput 2 () Output 11 Input 4 (()) Output 0101 Input 10 ((()())()) Output 0110001111NoteIn the first example one of optimal solutions is s = "\color{blue}{()}". r is empty and b = "()". The answer is \max(0, 1) = 1.In the second example it's optimal to make s = "\color{red}{(}\color{blue}{(}\color{red}{)}\color{blue}{)}". r = b = "()" and the answer is 1.In the third example we can make s = "\color{red}{(}\color{blue}{((}\color{red}{)()}\color{blue}{)())}". r = "()()" and b = "(()())" and the answer is 2.
2 ()
11
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*1500']
C. News Distributiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn some social network, there are n users communicating with each other in m groups of friends. Let's analyze the process of distributing some news between users.Initially, some user x receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user x you have to determine what is the number of users that will know the news if initially only user x starts distributing it. InputThe first line contains two integers n and m (1 \le n, m \le 5 \cdot 10^5) — the number of users and the number of groups of friends, respectively.Then m lines follow, each describing a group of friends. The i-th line begins with integer k_i (0 \le k_i \le n) — the number of users in the i-th group. Then k_i distinct integers follow, denoting the users belonging to the i-th group.It is guaranteed that \sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5.OutputPrint n integers. The i-th integer should be equal to the number of users that will know the news if user i starts distributing it.ExampleInput 7 5 3 2 5 4 0 2 1 2 1 1 2 6 7 Output 4 4 1 4 4 2 2
7 5 3 2 5 4 0 2 1 2 1 1 2 6 7
4 4 1 4 4 2 2
2 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', '*1400']
B. Lost Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury guessed some array a consisting of 6 integers. There are 6 special numbers — 4, 8, 15, 16, 23, 42 — and each of these numbers occurs in a exactly once (so, a is some permutation of these numbers).You don't know anything about their order, but you are allowed to ask up to 4 queries. In each query, you may choose two indices i and j (1 \le i, j \le 6, i and j are not necessarily distinct), and you will get the value of a_i \cdot a_j in return.Can you guess the array a?The array a is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries.InteractionBefore submitting the answer, you may ask up to 4 queries. To ask a query, print one line in the following format: ? i j, where i and j should be two integers such that 1 \le i, j \le 6. The line should be ended with a line break character. After submitting a query, flush the output and read the answer to your query — one line containing one integer a_i \cdot a_j. If you submit an incorrect query (or ask more than 4 queries), the answer to it will be one string 0. After receiving such an answer, your program should terminate immediately — otherwise you may receive verdict "Runtime error", "Time limit exceeded" or some other verdict instead of "Wrong answer".To give the answer, your program should print one line ! a_1 a_2 a_3 a_4 a_5 a_6 with a line break in the end. After that, it should flush the output and terminate gracefully.ExampleInput 16 64 345 672Output ? 1 1 ? 2 2 ? 3 5 ? 4 6 ! 4 8 15 16 23 42NoteIf you want to submit a hack for this problem, your test should contain exactly six space-separated integers a_1, a_2, ..., a_6. Each of 6 special numbers should occur exactly once in the test. The test should be ended with a line break character.
16 64 345 672
? 1 1 ? 2 2 ? 3 5 ? 4 6 ! 4 8 15 16 23 42
1 second
256 megabytes
['brute force', 'divide and conquer', 'interactive', 'math', '*1400']
A. Telephone Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.You are given a string s of length n, consisting of digits.In one operation you can delete any character from string s. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.You need to determine whether there is such a sequence of operations (possibly empty), after which the string s becomes a telephone number.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains one integer n (1 \le n \le 100) — the length of string s.The second line of each test case contains the string s (|s| = n) consisting of digits.OutputFor each test print one line.If there is a sequence of operations, after which s becomes a telephone number, print YES.Otherwise, print NO.ExampleInput 2 13 7818005553535 11 31415926535 Output YES NO NoteIn the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.
2 13 7818005553535 11 31415926535
YES NO
1 second
256 megabytes
['brute force', 'greedy', 'strings', '*800']
F. Vicky's Delivery Servicetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a magical land there are n cities conveniently numbered 1, 2, \dots, n. Some pairs of these cities are connected by magical colored roads. Magic is unstable, so at any time, new roads may appear between two cities.Vicky the witch has been tasked with performing deliveries between some pairs of cities. However, Vicky is a beginner, so she can only complete a delivery if she can move from her starting city to her destination city through a double rainbow. A double rainbow is a sequence of cities c_1, c_2, \dots, c_k satisfying the following properties: For each i with 1 \le i \le k - 1, the cities c_i and c_{i + 1} are connected by a road. For each i with 1 \le i \le \frac{k - 1}{2}, the roads connecting c_{2i} with c_{2i - 1} and c_{2i + 1} have the same color. For example if k = 5, the road between c_1 and c_2 must be the same color as the road between c_2 and c_3, and the road between c_3 and c_4 must be the same color as the road between c_4 and c_5.Vicky has a list of events in chronological order, where each event is either a delivery she must perform, or appearance of a new road. Help her determine which of her deliveries she will be able to complete.InputThe first line contains four integers n, m, c, and q (2 \le n \le 10^5, 1 \le m, c, q \le 10^5), denoting respectively the number of cities, the number of roads initially present, the number of different colors the roads can take, and the number of events.Each of the following m lines contains three integers x, y, and z (1 \le x, y \le n, 1 \le z \le c), describing that there initially exists a bidirectional road with color z between cities x and y.Then q lines follow, describing the events. Each event is one of the following two types: + x y z (1 \le x, y \le n, 1 \le z \le c), meaning a road with color z appears between cities x and y; ? x y (1 \le x, y \le n), meaning you should determine whether Vicky can make a delivery starting at city x and ending at city y. It is guaranteed that x \neq y. It is guaranteed that at any moment, there is at most one road connecting any pair of cities, and that no road connects a city to itself. It is guaranteed that the input contains at least one event of the second type.OutputFor each event of the second type, print a single line containing "Yes" (without quotes) if the delivery can be made, or a single line containing "No" (without quotes) otherwise.ExampleInput 4 3 2 4 1 2 1 2 3 1 3 4 2 ? 1 4 ? 4 1 + 3 1 2 ? 4 1 Output Yes No Yes NoteThe following picture corresponds to the sample. For her first delivery, Vicky can use the sequence 1, 2, 3, 4 which is a double rainbow. However, she cannot complete the second delivery, as she can only reach city 3. After adding the road between cities 1 and 3, she can now complete a delivery from city 4 to city 1 by using the double rainbow 4, 3, 1.
4 3 2 4 1 2 1 2 3 1 3 4 2 ? 1 4 ? 4 1 + 3 1 2 ? 4 1
Yes No Yes
4 seconds
256 megabytes
['data structures', 'dsu', 'graphs', 'hashing', '*2400']
E. The LCMs Must be Largetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDora the explorer has decided to use her money after several years of juicy royalties to go shopping. What better place to shop than Nlogonia?There are n stores numbered from 1 to n in Nlogonia. The i-th of these stores offers a positive integer a_i.Each day among the last m days Dora bought a single integer from some of the stores. The same day, Swiper the fox bought a single integer from all the stores that Dora did not buy an integer from on that day.Dora considers Swiper to be her rival, and she considers that she beat Swiper on day i if and only if the least common multiple of the numbers she bought on day i is strictly greater than the least common multiple of the numbers that Swiper bought on day i.The least common multiple (LCM) of a collection of integers is the smallest positive integer that is divisible by all the integers in the collection.However, Dora forgot the values of a_i. Help Dora find out if there are positive integer values of a_i such that she beat Swiper on every day. You don't need to find what are the possible values of a_i though.Note that it is possible for some values of a_i to coincide in a solution.InputThe first line contains integers m and n (1\leq m \leq 50, 1\leq n \leq 10^4) — the number of days and the number of stores.After this m lines follow, the i-th line starts with an integer s_i (1\leq s_i \leq n-1), the number of integers Dora bought on day i, followed by s_i distinct integers, the indices of the stores where Dora bought an integer on the i-th day. The indices are between 1 and n.OutputOutput must consist of a single line containing "possible" if there exist positive integers a_i such that for each day the least common multiple of the integers bought by Dora is strictly greater than the least common multiple of the integers bought by Swiper on that day. Otherwise, print "impossible".Note that you don't have to restore the integers themselves.ExamplesInput 2 5 3 1 2 3 3 3 4 5 Output possible Input 10 10 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 Output impossible NoteIn the first sample, a possible choice for the values of the a_i is 3, 4, 3, 5, 2. On the first day, Dora buys the integers 3, 4 and 3, whose LCM is 12, while Swiper buys integers 5 and 2, whose LCM is 10. On the second day, Dora buys 3, 5 and 2, whose LCM is 30, and Swiper buys integers 3 and 4, whose LCM is 12.
2 5 3 1 2 3 3 3 4 5
possible
1 second
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'math', 'number theory', '*2100']
D. Cute Sequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a positive integer m, we say that a sequence x_1, x_2, \dots, x_n of positive integers is m-cute if for every index i such that 2 \le i \le n it holds that x_i = x_{i - 1} + x_{i - 2} + \dots + x_1 + r_i for some positive integer r_i satisfying 1 \le r_i \le m.You will be given q queries consisting of three positive integers a, b and m. For each query you must determine whether or not there exists an m-cute sequence whose first term is a and whose last term is b. If such a sequence exists, you must additionally find an example of it.InputThe first line contains an integer number q (1 \le q \le 10^3) — the number of queries.Each of the following q lines contains three integers a, b, and m (1 \le a, b, m \le 10^{14}, a \leq b), describing a single query.OutputFor each query, if no m-cute sequence whose first term is a and whose last term is b exists, print -1.Otherwise print an integer k (1 \le k \leq 50), followed by k integers x_1, x_2, \dots, x_k (1 \le x_i \le 10^{14}). These integers must satisfy x_1 = a, x_k = b, and that the sequence x_1, x_2, \dots, x_k is m-cute.It can be shown that under the problem constraints, for each query either no m-cute sequence exists, or there exists one with at most 50 terms.If there are multiple possible sequences, you may print any of them.ExampleInput 2 5 26 2 3 9 1 Output 4 5 6 13 26 -1 NoteConsider the sample. In the first query, the sequence 5, 6, 13, 26 is valid since 6 = 5 + \bf{\color{blue} 1}, 13 = 6 + 5 + {\bf\color{blue} 2} and 26 = 13 + 6 + 5 + {\bf\color{blue} 2} have the bold values all between 1 and 2, so the sequence is 2-cute. Other valid sequences, such as 5, 7, 13, 26 are also accepted.In the second query, the only possible 1-cute sequence starting at 3 is 3, 4, 8, 16, \dots, which does not contain 9.
2 5 26 2 3 9 1
4 5 6 13 26 -1
1 second
256 megabytes
['binary search', 'brute force', 'greedy', 'math', '*2200']
C. A Tale of Two Landstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe legend of the foundation of Vectorland talks of two integers x and y. Centuries ago, the array king placed two markers at points |x| and |y| on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers at points |x - y| and |x + y| and conquered all the land in between (including the endpoints), which he declared to be Vectorland. He did so in such a way that the land of Arrayland was completely inside (including the endpoints) the land of Vectorland.Here |z| denotes the absolute value of z.Now, Jose is stuck on a question of his history exam: "What are the values of x and y?" Jose doesn't know the answer, but he believes he has narrowed the possible answers down to n integers a_1, a_2, \dots, a_n. Now, he wants to know the number of unordered pairs formed by two different elements from these n integers such that the legend could be true if x and y were equal to these two values. Note that it is possible that Jose is wrong, and that no pairs could possibly make the legend true.InputThe first line contains a single integer n (2 \le n \le 2 \cdot 10^5)  — the number of choices.The second line contains n pairwise distinct integers a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9) — the choices Jose is considering.OutputPrint a single integer number — the number of unordered pairs \{x, y\} formed by different numbers from Jose's choices that could make the legend true.ExamplesInput 3 2 5 -3 Output 2 Input 2 3 6 Output 1 NoteConsider the first sample. For the pair \{2, 5\}, the situation looks as follows, with the Arrayland markers at |2| = 2 and |5| = 5, while the Vectorland markers are located at |2 - 5| = 3 and |2 + 5| = 7: The legend is not true in this case, because the interval [2, 3] is not conquered by Vectorland. For the pair \{5, -3\} the situation looks as follows, with Arrayland consisting of the interval [3, 5] and Vectorland consisting of the interval [2, 8]: As Vectorland completely contains Arrayland, the legend is true. It can also be shown that the legend is true for the pair \{2, -3\}, for a total of two pairs.In the second sample, the only pair is \{3, 6\}, and the situation looks as follows: Note that even though Arrayland and Vectorland share 3 as endpoint, we still consider Arrayland to be completely inside of Vectorland.
3 2 5 -3
2
1 second
256 megabytes
['binary search', 'sortings', 'two pointers', '*1500']
B. All the Vowels Pleasetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that n\cdot m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column.You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists.In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'.InputInput consists of a single line containing the integer k (1\leq k \leq 10^4) — the required length.OutputThe output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not.If there are multiple possible words, you may output any of them.ExamplesInput 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimaeNoteIn the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 \times 6 grid: It is easy to verify that every row and every column contain all the vowels.
7
-1
1 second
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1100']
A. Silent Classroomtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must have a lot in common). Let x be the number of such pairs of students in a split. Pairs (a, b) and (b, a) are the same and counted only once.For example, if there are 6 students: "olivia", "jacob", "tanya", "jack", "oliver" and "jessica", then: splitting into two classrooms ("jack", "jacob", "jessica", "tanya") and ("olivia", "oliver") will give x=4 (3 chatting pairs in the first classroom, 1 chatting pair in the second classroom), splitting into two classrooms ("jack", "tanya", "olivia") and ("jessica", "oliver", "jacob") will give x=1 (0 chatting pairs in the first classroom, 1 chatting pair in the second classroom). You are given the list of the n names. What is the minimum x we can obtain by splitting the students into classrooms?Note that it is valid to place all of the students in one of the classrooms, leaving the other one empty.InputThe first line contains a single integer n (1\leq n \leq 100) — the number of students.After this n lines follow.The i-th line contains the name of the i-th student.It is guaranteed each name is a string of lowercase English letters of length at most 20. Note that multiple students may share the same name.OutputThe output must consist of a single integer x — the minimum possible number of chatty pairs.ExamplesInput 4 jorge jose oscar jerry Output 1 Input 7 kambei gorobei shichiroji kyuzo heihachi katsushiro kikuchiyo Output 2 Input 5 mike mike mike mike mike Output 4 NoteIn the first sample the minimum number of pairs is 1. This can be achieved, for example, by putting everyone except jose in one classroom, and jose in the other, so jorge and jerry form the only chatty pair.In the second sample the minimum number of pairs is 2. This can be achieved, for example, by putting kambei, gorobei, shichiroji and kyuzo in one room and putting heihachi, katsushiro and kikuchiyo in the other room. In this case the two pairs are kambei and kyuzo, and katsushiro and kikuchiyo.In the third sample the minimum number of pairs is 4. This can be achieved by placing three of the students named mike in one classroom and the other two students in another classroom. Thus there will be three chatty pairs in one classroom and one chatty pair in the other classroom.
4 jorge jose oscar jerry
1
1 second
256 megabytes
['combinatorics', 'greedy', '*900']
F2. Microtransactions (hard version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them.Each day (during the morning) Ivan earns exactly one burle.There are n types of microtransactions in the game. Each microtransaction costs 2 burles usually and 1 burle if it is on sale. Ivan has to order exactly k_i microtransactions of the i-th type (he orders microtransactions during the evening).Ivan can order any (possibly zero) number of microtransactions of any types during any day (of course, if he has enough money to do it). If the microtransaction he wants to order is on sale then he can buy it for 1 burle and otherwise he can buy it for 2 burles.There are also m special offers in the game shop. The j-th offer (d_j, t_j) means that microtransactions of the t_j-th type are on sale during the d_j-th day.Ivan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing.InputThe first line of the input contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the number of types of microtransactions and the number of special offers in the game shop.The second line of the input contains n integers k_1, k_2, \dots, k_n (0 \le k_i \le 2 \cdot 10^5), where k_i is the number of copies of microtransaction of the i-th type Ivan has to order. It is guaranteed that sum of all k_i is not less than 1 and not greater than 2 \cdot 10^5.The next m lines contain special offers. The j-th of these lines contains the j-th special offer. It is given as a pair of integers (d_j, t_j) (1 \le d_j \le 2 \cdot 10^5, 1 \le t_j \le n) and means that microtransactions of the t_j-th type are on sale during the d_j-th day.OutputPrint one integer — the minimum day when Ivan can order all microtransactions he wants and actually start playing.ExamplesInput 5 6 1 2 0 2 0 2 4 3 3 1 5 1 2 1 5 2 3 Output 8 Input 5 3 4 2 1 3 2 3 5 4 2 2 5 Output 20
5 6 1 2 0 2 0 2 4 3 3 1 5 1 2 1 5 2 3
8
3 seconds
256 megabytes
['binary search', 'greedy', 'implementation', '*2000']
F1. Microtransactions (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them.Each day (during the morning) Ivan earns exactly one burle.There are n types of microtransactions in the game. Each microtransaction costs 2 burles usually and 1 burle if it is on sale. Ivan has to order exactly k_i microtransactions of the i-th type (he orders microtransactions during the evening).Ivan can order any (possibly zero) number of microtransactions of any types during any day (of course, if he has enough money to do it). If the microtransaction he wants to order is on sale then he can buy it for 1 burle and otherwise he can buy it for 2 burles.There are also m special offers in the game shop. The j-th offer (d_j, t_j) means that microtransactions of the t_j-th type are on sale during the d_j-th day.Ivan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing.InputThe first line of the input contains two integers n and m (1 \le n, m \le 1000) — the number of types of microtransactions and the number of special offers in the game shop.The second line of the input contains n integers k_1, k_2, \dots, k_n (0 \le k_i \le 1000), where k_i is the number of copies of microtransaction of the i-th type Ivan has to order. It is guaranteed that sum of all k_i is not less than 1 and not greater than 1000.The next m lines contain special offers. The j-th of these lines contains the j-th special offer. It is given as a pair of integers (d_j, t_j) (1 \le d_j \le 1000, 1 \le t_j \le n) and means that microtransactions of the t_j-th type are on sale during the d_j-th day.OutputPrint one integer — the minimum day when Ivan can order all microtransactions he wants and actually start playing.ExamplesInput 5 6 1 2 0 2 0 2 4 3 3 1 5 1 2 1 5 2 3 Output 8 Input 5 3 4 2 1 3 2 3 5 4 2 2 5 Output 20
5 6 1 2 0 2 0 2 4 3 3 1 5 1 2 1 5 2 3
8
2 seconds
256 megabytes
['binary search', 'greedy', '*2000']
E. Two Arrays and Sum of Functionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b, both of length n.Let's define a function f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i.Your task is to reorder the elements (choose an arbitrary order of elements) of the array b to minimize the value of \sum\limits_{1 \le l \le r \le n} f(l, r). Since the answer can be very large, you have to print it modulo 998244353. Note that you should minimize the answer but not its remainder.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in a and b.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6), where a_i is the i-th element of a.The third line of the input contains n integers b_1, b_2, \dots, b_n (1 \le b_j \le 10^6), where b_j is the j-th element of b.OutputPrint one integer — the minimum possible value of \sum\limits_{1 \le l \le r \le n} f(l, r) after rearranging elements of b, taken modulo 998244353. Note that you should minimize the answer but not its remainder.ExamplesInput 5 1 8 7 2 4 9 7 2 9 3 Output 646 Input 1 1000000 1000000 Output 757402647 Input 2 1 3 4 2 Output 20
5 1 8 7 2 4 9 7 2 9 3
646
2 seconds
256 megabytes
['greedy', 'math', 'sortings', '*1600']
D. Almost All Divisorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe guessed some integer number x. You are given a list of almost all its divisors. Almost all means that there are all divisors except 1 and x in the list.Your task is to find the minimum possible integer x that can be the guessed number, or say that the input data is contradictory and it is impossible to find such number.You have to answer t independent queries.InputThe first line of the input contains one integer t (1 \le t \le 25) — the number of queries. Then t queries follow.The first line of the query contains one integer n (1 \le n \le 300) — the number of divisors in the list.The second line of the query contains n integers d_1, d_2, \dots, d_n (2 \le d_i \le 10^6), where d_i is the i-th divisor of the guessed number. It is guaranteed that all values d_i are distinct.OutputFor each query print the answer to it.If the input data in the query is contradictory and it is impossible to find such number x that the given list of divisors is the list of almost all its divisors, print -1. Otherwise print the minimum possible x.ExampleInput 2 8 8 2 12 6 4 24 16 3 1 2 Output 48 4
2 8 8 2 12 6 4 24 16 3 1 2
48 4
2 seconds
256 megabytes
['math', 'number theory', '*1600']
C. Good Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. Note that the empty string is considered good.You are given a string s, you have to delete minimum number of characters from this string so that it becomes good.InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of characters in s.The second line contains the string s, consisting of exactly n lowercase Latin letters.OutputIn the first line, print one integer k (0 \le k \le n) — the minimum number of characters you have to delete from s to make it good.In the second line, print the resulting string s. If it is empty, you may leave the second line blank, or not print it at all.ExamplesInput 4 good Output 0 good Input 4 aabc Output 2 ab Input 3 aaa Output 3
4 good
0 good
1 second
256 megabytes
['greedy', '*1300']
B. Polycarp Trainingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to train before another programming competition. During the first day of his training he should solve exactly 1 problem, during the second day — exactly 2 problems, during the third day — exactly 3 problems, and so on. During the k-th day he should solve k problems.Polycarp has a list of n contests, the i-th contest consists of a_i problems. During each day Polycarp has to choose exactly one of the contests he didn't solve yet and solve it. He solves exactly k problems from this contest. Other problems are discarded from it. If there are no contests consisting of at least k problems that Polycarp didn't solve yet during the k-th day, then Polycarp stops his training.How many days Polycarp can train if he chooses the contests optimally?InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of contests.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) — the number of problems in the i-th contest.OutputPrint one integer — the maximum number of days Polycarp can train if he chooses the contests optimally.ExamplesInput 4 3 1 4 1 Output 3 Input 3 1 1 1 Output 1 Input 5 1 1 1 2 2 Output 2
4 3 1 4 1
3
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', '*1000']
A. Remaindertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a huge decimal number consisting of n digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem.You are also given two integers 0 \le y < x < n. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder 10^y modulo 10^x. In other words, the obtained number should have remainder 10^y when divided by 10^x.InputThe first line of the input contains three integers n, x, y (0 \le y < x < n \le 2 \cdot 10^5) — the length of the number and the integers x and y, respectively.The second line of the input contains one decimal number consisting of n digits, each digit of this number is either 0 or 1. It is guaranteed that the first digit of the number is 1.OutputPrint one integer — the minimum number of operations you should perform to obtain the number having remainder 10^y modulo 10^x. In other words, the obtained number should have remainder 10^y when divided by 10^x.ExamplesInput 11 5 2 11010100101 Output 1 Input 11 5 1 11010100101 Output 3 NoteIn the first example the number will be 11010100100 after performing one operation. It has remainder 100 modulo 100000.In the second example the number will be 11010100010 after performing three operations. It has remainder 10 modulo 100000.
11 5 2 11010100101
1
1 second
256 megabytes
['implementation', 'math', '*1100']
F. Indecisive Taxi Feetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn the city of Capypaland where Kuro and Shiro resides, there are n towns numbered from 1 to n and there are m bidirectional roads numbered from 1 to m connecting them. The i-th road connects towns u_i and v_i. Since traveling between the towns is quite difficult, the taxi industry is really popular here. To survive the harsh competition, each taxi company has to find a distinctive trait for their customers.Kuro is the owner of a taxi company. He has decided to introduce a new fee model for his taxi brand, where the fee for each ride is not calculated based on the trip length, but on the sum of the prices of the roads traveled. The price for each of the m roads has been decided by Kuro himself.As of now, the price for the road i is w_i and hence the fee for a taxi ride traveling through roads e_1, e_2, \ldots, e_k is \sum_{i=1}^k w_{e_i}.However, Kuro himself is an indecisive person, so he has drafted q plans to change the road price. Each of the plans will be based on the original prices w_i, except for a single road t_j, the price of which is changed to x_j. Note, that the plans are independent of each other.Shiro is a regular customer of the Kuro's taxi brand since she uses the taxi to travel from town 1 to town n every day. Since she's so a regular customer, Kuro decided to show her all his q plans before publishing them to the public. Now, Shiro wants to know the lowest fee she must pay to travel from the town 1 to the town n for each Kuro's plan.InputThe first line contains three integers n, m and q (2 \le n \le 2 \cdot 10^5, 1 \le m, q \le 2 \cdot 10^5) — the number of towns, the number of roads, and the number of plans that Kuro has drafted respectively.The i-th of the next m contains three integers u_i, v_i and w_i (1 \le u_i, v_i \le n, 1 \le w_i \le 10^9, u_i \ne v_i) — two endpoints and the original price of the i-th road.It is guaranteed, that there is at least one way to travel from town 1 to town n using these m bidirectional roads.Each of the next q lines contains two integers t_j and x_j (1 \leq t_j \leq m, 1 \leq x_j \leq 10^9) — the index of the road Kuro has planned to change and its new price respectively.OutputPrint q integers — the lowest fee Shiro must pay to get from town 1 to town n in each of those q plans.ExamplesInput 4 5 6 1 2 2 2 4 3 1 4 7 1 3 1 3 4 5 3 4 5 1 3 8 1 4 2 1 3 1 Output 4 2 5 6 3 1 Input 2 4 4 1 2 2 1 2 3 1 2 4 1 2 5 2 1 3 2 4 3 1 5 Output 1 2 2 3 Input 2 1 1 1 2 1 1 3 Output 3 NoteIn the first example, the original overview of Capypaland looks like this, where the number next to each road denotes the original prices of the roads, The overview of the first plan, The lowest fee Shiro must pay in this plan is 4, which corresponds to the path 1 \rightarrow 4.The overview of the second plan, The lowest fee Shiro must pay in this plan is 2, which corresponds to the path 1 \rightarrow 3 \rightarrow 4.The overview of the third plan, The lowest fee Shiro must pay in this plan is 5, which corresponds to the path 1 \rightarrow 2 \rightarrow 4.
4 5 6 1 2 2 2 4 3 1 4 7 1 3 1 3 4 5 3 4 5 1 3 8 1 4 2 1 3 1
4 2 5 6 3 1
2 seconds
512 megabytes
['data structures', 'graphs', 'shortest paths', '*3000']
E. Magical Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuro has just learned about permutations and he is really excited to create a new permutation type. He has chosen n distinct positive integers and put all of them in a set S. Now he defines a magical permutation to be: A permutation of integers from 0 to 2^x - 1, where x is a non-negative integer. The bitwise xor of any two consecutive elements in the permutation is an element in S.Since Kuro is really excited about magical permutations, he wants to create the longest magical permutation possible. In other words, he wants to find the largest non-negative integer x such that there is a magical permutation of integers from 0 to 2^x - 1. Since he is a newbie in the subject, he wants you to help him find this value of x and also the magical permutation for that x.InputThe first line contains the integer n (1 \leq n \leq 2 \cdot 10^5) — the number of elements in the set S.The next line contains n distinct integers S_1, S_2, \ldots, S_n (1 \leq S_i \leq 2 \cdot 10^5) — the elements in the set S.OutputIn the first line print the largest non-negative integer x, such that there is a magical permutation of integers from 0 to 2^x - 1.Then print 2^x integers describing a magical permutation of integers from 0 to 2^x - 1. If there are multiple such magical permutations, print any of them.ExamplesInput 3 1 2 3 Output 2 0 1 3 2 Input 2 2 3 Output 2 0 2 1 3 Input 4 1 2 3 4 Output 3 0 1 3 2 6 7 5 4 Input 2 2 4 Output 0 0 Input 1 20 Output 0 0 Input 1 1 Output 1 0 1 NoteIn the first example, 0, 1, 3, 2 is a magical permutation since: 0 \oplus 1 = 1 \in S 1 \oplus 3 = 2 \in S 3 \oplus 2 = 1 \in SWhere \oplus denotes bitwise xor operation.
3 1 2 3
2 0 1 3 2
1 second
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'data structures', 'graphs', 'math', '*2400']
D. Mysterious Codetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string c consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters).Katie has a favorite string s and a not-so-favorite string t and she would love to recover the mysterious code so that it has as many occurrences of s as possible and as little occurrences of t as possible. Formally, let's denote f(x, y) as the number of occurrences of y in x (for example, f(aababa, ab) = 2). Katie wants to recover the code c' conforming to the original c, such that f(c', s) - f(c', t) is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out.InputThe first line contains string c (1 \leq |c| \leq 1000) — the mysterious code . It is guaranteed that c consists of lowercase English characters and asterisks "*" only.The second and third line contain strings s and t respectively (1 \leq |s|, |t| \leq 50, s \neq t). It is guaranteed that s and t consist of lowercase English characters only.OutputPrint a single integer — the largest possible value of f(c', s) - f(c', t) of the recovered code.ExamplesInput ***** katie shiro Output 1 Input caat caat a Output -1 Input *a* bba b Output 0 Input *** cc z Output 2 NoteIn the first example, for c' equal to "katie" f(c', s) = 1 and f(c', t) = 0, which makes f(c', s) - f(c', t) = 1 which is the largest possible.In the second example, the only c' conforming to the given c is "caat". The corresponding f(c', s) - f(c', t) = 1 - 2 = -1.In the third example, there are multiple ways to recover the code such that f(c', s) - f(c', t) is largest possible, for example "aaa", "aac", or even "zaz". The value of f(c', s) - f(c', t) = 0 for all of these recovered codes.In the fourth example, the optimal recovered code c' would be "ccc". The corresponding f(c', s) - f(c', t) = 2.
***** katie shiro
1
2 seconds
256 megabytes
['dp', 'strings', '*2100']
C2. Power Transmission (Hard Edition)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is same as the previous one, but has larger constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates (x_i, y_i). Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?InputThe first line contains a single integer n (2 \le n \le 1000) — the number of electric poles.Each of the following n lines contains two integers x_i, y_i (-10^4 \le x_i, y_i \le 10^4) — the coordinates of the poles.It is guaranteed that all of these n points are distinct.OutputPrint a single integer — the number of pairs of wires that are intersecting.ExamplesInput 4 0 0 1 1 0 3 1 2 Output 14 Input 4 0 0 0 2 0 4 2 0 Output 6 Input 3 -1 -1 1 0 3 1 Output 0 NoteIn the first example: In the second example: Note that the three poles (0, 0), (0, 2) and (0, 4) are connected by a single wire.In the third example:
4 0 0 1 1 0 3 1 2
14
3 seconds
256 megabytes
['data structures', 'geometry', 'implementation', 'math', '*1900']
C1. Power Transmission (Easy Edition)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is same as the next one, but has smaller constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates (x_i, y_i). Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?InputThe first line contains a single integer n (2 \le n \le 50) — the number of electric poles.Each of the following n lines contains two integers x_i, y_i (-10^4 \le x_i, y_i \le 10^4) — the coordinates of the poles.It is guaranteed that all of these n points are distinct.OutputPrint a single integer — the number of pairs of wires that are intersecting.ExamplesInput 4 0 0 1 1 0 3 1 2 Output 14 Input 4 0 0 0 2 0 4 2 0 Output 6 Input 3 -1 -1 1 0 3 1 Output 0 NoteIn the first example: In the second example: Note that the three poles (0, 0), (0, 2) and (0, 4) are connected by a single wire.In the third example:
4 0 0 1 1 0 3 1 2
14
3 seconds
256 megabytes
['brute force', 'geometry', '*1900']
B2. Cat Party (Hard Edition)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is same as the previous one, but has larger constraints.Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.For each of the n days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the i-th day has a ribbon with color u_i. Shiro wants to know the largest number x, such that if we consider the streak of the first x days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining x - 1 will have the same number of occurrences.For example, consider the following sequence of u_i: [2, 2, 1, 1, 5, 4, 4, 5]. Then x = 7 makes a streak, since if we remove the leftmost u_i = 5, each ribbon color will appear exactly twice in the prefix of x - 1 days. Note that x = 8 doesn't form a streak, since you must remove exactly one day. Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the total number of days.The second line contains n integers u_1, u_2, \ldots, u_n (1 \leq u_i \leq 10^5) — the colors of the ribbons the cats wear. OutputPrint a single integer x — the largest possible streak of days.ExamplesInput 13 1 1 1 2 2 2 3 3 3 4 4 4 5 Output 13Input 5 10 100 20 200 1 Output 5Input 1 100000 Output 1Input 7 3 2 1 1 4 5 1 Output 6Input 6 1 1 1 2 2 2 Output 5NoteIn the first example, we can choose the longest streak of 13 days, since upon removing the last day out of the streak, all of the remaining colors 1, 2, 3, and 4 will have the same number of occurrences of 3. Note that the streak can also be 10 days (by removing the 10-th day from this streak) but we are interested in the longest streak.In the fourth example, if we take the streak of the first 6 days, we can remove the third day from this streak then all of the remaining colors 1, 2, 3, 4 and 5 will occur exactly once.
13 1 1 1 2 2 2 3 3 3 4 4 4 5
13
1 second
256 megabytes
['data structures', 'implementation', '*1600']
B1. Cat Party (Easy Edition)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is same as the next one, but has smaller constraints.Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.For each of the n days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the i-th day has a ribbon with color u_i. Shiro wants to know the largest number x, such that if we consider the streak of the first x days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining x - 1 will have the same number of occurrences.For example, consider the following sequence of u_i: [2, 2, 1, 1, 5, 4, 4, 5]. Then x = 7 makes a streak, since if we remove the leftmost u_i = 5, each ribbon color will appear exactly twice in the prefix of x - 1 days. Note that x = 8 doesn't form a streak, since you must remove exactly one day. Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the total number of days.The second line contains n integers u_1, u_2, \ldots, u_n (1 \leq u_i \leq 10) — the colors of the ribbons the cats wear. OutputPrint a single integer x — the largest possible streak of days.ExamplesInput 13 1 1 1 2 2 2 3 3 3 4 4 4 5 Output 13Input 5 10 2 5 4 1 Output 5Input 1 10 Output 1Input 7 3 2 1 1 4 5 1 Output 6Input 6 1 1 1 2 2 2 Output 5NoteIn the first example, we can choose the longest streak of 13 days, since upon removing the last day out of the streak, all of the remaining colors 1, 2, 3, and 4 will have the same number of occurrences of 3. Note that the streak can also be 10 days (by removing the 10-th day from this streak) but we are interested in the longest streak.In the fourth example, if we take the streak of the first 6 days, we can remove the third day from this streak then all of the remaining colors 1, 2, 3, 4 and 5 will occur exactly once.
13 1 1 1 2 2 2 3 3 3 4 4 4 5
13
1 second
256 megabytes
['data structures', 'implementation', '*1500']
A. Eating Souptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe three friends, Kuro, Shiro, and Katie, met up again! It's time for a party...What the cats do when they unite? Right, they have a party. Since they wanted to have as much fun as possible, they invited all their friends. Now n cats are at the party, sitting in a circle and eating soup. The rules are simple: anyone having finished their soup leaves the circle.Katie suddenly notices that whenever a cat leaves, the place where she was sitting becomes an empty space, which means the circle is divided into smaller continuous groups of cats sitting next to each other. At the moment Katie observes, there are m cats who left the circle. This raises a question for Katie: what is the maximum possible number of groups the circle is divided into at the moment?Could you help her with this curiosity?You can see the examples and their descriptions with pictures in the "Note" section.InputThe only line contains two integers n and m (2 \leq n \leq 1000, 0 \leq m \leq n) — the initial number of cats at the party and the number of cats who left the circle at the moment Katie observes, respectively.OutputPrint a single integer — the maximum number of groups of cats at the moment Katie observes.ExamplesInput 7 4 Output 3 Input 6 2 Output 2 Input 3 0 Output 1 Input 2 2 Output 0 NoteIn the first example, originally there are 7 cats sitting as shown below, creating a single group: At the observed moment, 4 cats have left the table. Suppose the cats 2, 3, 5 and 7 have left, then there are 3 groups remaining. It is possible to show that it is the maximum possible number of groups remaining. In the second example, there are 6 cats sitting as shown below: At the observed moment, 2 cats have left the table. Suppose the cats numbered 3 and 6 left, then there will be 2 groups remaining (\{1, 2\} and \{4, 5\}). It is impossible to have more than 2 groups of cats remaining. In the third example, no cats have left, so there is 1 group consisting of all cats.In the fourth example, all cats have left the circle, so there are 0 groups.
7 4
3
1 second
256 megabytes
['greedy', 'math', '*900']
B. Double Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two n \times m matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly increasing. A matrix is increasing if all rows are strictly increasing and all columns are strictly increasing. For example, the matrix \begin{bmatrix} 9&10&11\\ 11&12&14\\ \end{bmatrix} is increasing because each individual row and column is strictly increasing. On the other hand, the matrix \begin{bmatrix} 1&1\\ 2&3\\ \end{bmatrix} is not increasing because the first row is not strictly increasing.Let a position in the i-th row (from top) and j-th column (from left) in a matrix be denoted as (i, j). In one operation, you can choose any two numbers i and j and swap the number located in (i, j) in the first matrix with the number in (i, j) in the second matrix. In other words, you can swap two numbers in different matrices if they are located in the corresponding positions.You would like to make both matrices increasing by performing some number of operations (possibly none). Determine if it is possible to do this. If it is, print "Possible", otherwise, print "Impossible".InputThe first line contains two integers n and m (1 \leq n,m \leq 50) — the dimensions of each matrix.Each of the next n lines contains m integers a_{i1}, a_{i2}, \ldots, a_{im} (1 \leq a_{ij} \leq 10^9) — the number located in position (i, j) in the first matrix.Each of the next n lines contains m integers b_{i1}, b_{i2}, \ldots, b_{im} (1 \leq b_{ij} \leq 10^9) — the number located in position (i, j) in the second matrix.OutputPrint a string "Impossible" or "Possible".ExamplesInput 2 2 2 10 11 5 9 4 3 12 Output Possible Input 2 3 2 4 5 4 5 6 3 6 7 8 10 11 Output Possible Input 3 2 1 3 2 4 5 10 3 1 3 6 4 8 Output Impossible NoteThe first example, we can do an operation on the top left and bottom right cells of the matrices. The resulting matrices will be \begin{bmatrix} 9&10\\ 11&12\\ \end{bmatrix} and \begin{bmatrix} 2&4\\ 3&5\\ \end{bmatrix}.In the second example, we don't need to do any operations.In the third example, no matter what we swap, we can't fix the first row to be strictly increasing in both matrices.
2 2 2 10 11 5 9 4 3 12
Possible
1 second
256 megabytes
['brute force', 'greedy', '*1400']
A. Zoning Restrictions Againtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are planning to build housing on a street. There are n spots available on the street on which you can build a house. The spots are labeled from 1 to n from left to right. In each spot, you can build a house with an integer height between 0 and h.In each spot, if a house has height a, you will gain a^2 dollars from it.The city has m zoning restrictions. The i-th restriction says that the tallest house from spots l_i to r_i (inclusive) must be at most x_i.You would like to build houses to maximize your profit. Determine the maximum profit possible.InputThe first line contains three integers n, h, and m (1 \leq n,h,m \leq 50) — the number of spots, the maximum height, and the number of restrictions.Each of the next m lines contains three integers l_i, r_i, and x_i (1 \leq l_i \leq r_i \leq n, 0 \leq x_i \leq h) — left and right limits (inclusive) of the i-th restriction and the maximum possible height in that range.OutputPrint a single integer, the maximum profit you can make.ExamplesInput 3 3 3 1 1 1 2 2 3 3 3 2 Output 14 Input 4 10 2 2 3 8 3 4 7 Output 262 NoteIn the first example, there are 3 houses, the maximum height of a house is 3, and there are 3 restrictions. The first restriction says the tallest house between 1 and 1 must be at most 1. The second restriction says the tallest house between 2 and 2 must be at most 3. The third restriction says the tallest house between 3 and 3 must be at most 2.In this case, it is optimal to build houses with heights [1, 3, 2]. This fits within all the restrictions. The total profit in this case is 1^2 + 3^2 + 2^2 = 14.In the second example, there are 4 houses, the maximum height of a house is 10, and there are 2 restrictions. The first restriction says the tallest house from 2 to 3 must be at most 8. The second restriction says the tallest house from 3 to 4 must be at most 7.In this case, it's optimal to build houses with heights [10, 8, 7, 7]. We get a profit of 10^2+8^2+7^2+7^2 = 262. Note that there are two restrictions on house 3 and both of them must be satisfied. Also, note that even though there isn't any explicit restrictions on house 1, we must still limit its height to be at most 10 (h=10).
3 3 3 1 1 1 2 2 3 3 3 2
14
1 second
256 megabytes
['implementation', '*800']
A2. Collaborationtime limit per test15 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputConsider several locations in integer points on the plane. One of the locations is the base where workers wait. Every other location contains one job.Each job has the following characteristics: work duration, the required number of workers, and also the earliest possible moment of starting the job and the latest possible moment of completing it. In order to complete the job, the required number of workers must simultaneously start working on it, and then be continuously present at the location for the duration of the job. Each job must either be fully done exactly once, or left untouched.Our task is to determine what should the workers do so that we have more profit. any worker can contribute to any job. We can use as many workers as we like, but each worker must take part in doing at least one job.Each worker starts at the base at a certain moment, then moves between locations and does the jobs, and finally gets back to the base and stops completely. A worker can move along coordinate axes, and spends one minute increasing or decreasing any one of his coordinates by 1. We have to pay the worker 240 credits for appearing in our solution, and additionally 1 credit per minute, up to the moment when the worker stops completely.We get rewarded for each job that is done. For a job with duration d and the required number of workers p, we get a reward of d \cdot p \cdot (p + 5) credits. The jobs which are not done don't contribute to this sum.InputThe first line contains an integer n from 500 to 2000: the number of locations. Each of the following n lines contains six integers and describes one location in the format x y d p l h. The coordinates x and y are integers from 0 to 100. The duration d is an integer from 5 to 30 minutes. The required number of workers p is an integer from 1 to 7 people. The earliest possible start moment l and the latest possible completion moment h are integers from 200 to 800 minutes, chosen so that 60 \le h - l \le 300.The first location is the base. It is an exclusion to the rules above and has the format x y 0 0 0 0. All given points (x, y) are distinct.In all tests, the number n, as well as all points, durations, numbers of required workers, and time spans are chosen randomly, independently, and uniformly from the available choices.OutputPrint instructions for each worker as a block of a few lines which look as follows: start (at-moment) (at-location)The first line of a block. Determines the moment when the worker starts at the base. The location must be the base, and so have the number 1. arrive (at-moment) (at-location)We want the worker to arrive at this moment to this location. If he can not make it in time after the previous command, the solution is considered incorrect. Locations are numbered from 1 to n in input order. work (start-moment) (end-moment) (at-location)We want the worker to do the job at this location in this exact time interval. The location must be equal to the location in the previous arrival command. If the worker can not make it in time after the previous command, or the given time interval has wrong length or exceeds the time span of the location, the solution is considered incorrect. This command must be present at least once in each block. Recall that each job must be either completed simultaneously by the required number of workers, or left untouched, otherwise, the solution will be considered incorrect. endThe last line of a block. The worker must be in the same position where he started. At each moment, there may be arbitrarily many workers in each location. All moments in the output must be integers from 0 to 1000, and all location numbers must be integers from 1 to n.Print consecutive blocks one under the other, with no gaps.ExampleInput45 15 0 0 0 02 13 30 2 200 4003 12 29 1 350 60039 21 9 4 671 757Outputstart 335 1arrive 340 2work 340 370 2arrive 372 3work 372 401 3arrive 406 1endstart 335 1arrive 340 2work 340 370 2arrive 375 1endExplanationThe reward for the job at location 2 is 30 \cdot 2 \cdot (2 + 5) = 420 credits.The reward for the job at location 3 is 29 \cdot 1 \cdot (1 + 5) = 174 credits.The job at location 4 is not completed.We have to pay 240 + 71 = 311 credits to the first worker.We also have to pay 240 + 40 = 280 credits to the second worker.Profit: 420 + 174 - 311 - 280 = 3.Note that this example is too short (n < 500) and so does not appear in the testing system. It is included for explanatory purposes only.ScoringEach test is scored independently. The score for a test is the profit divided by 1000. It the profit is negative, the score is equal to zero. If a solution did not output a valid answer on a certain test, the result for this test is also zero.TestingYour solution will be checked on sets of tests generated in advance. A solution's score is the sum of its results on all the tests. If a solution did not output a valid answer on a certain test, the result for this test is zero.During the main phase of the contest, there are two ways to submit a solution. The first one, problem A1, is to check on examples. There are 10 example tests which are also available for local testing. As soon as the solution is checked, you can see reports for all examples by clicking on the submission result. The tests for A1 are open, you can download them from the links https://assets.codeforces.com/rounds/1160/codeforces-vrt-2019.tar.gz (for Linux) and https://assets.codeforces.com/rounds/1160/codeforces-vrt-2019.zip (for Windows). After testing, you can click the verdict of your submission to see the result for each test. The second way, problem A2, is to check on preliminary tests. There are 100 preliminary tests which are generated in advance but kept secret. The score for preliminary tests (but not for example tests) is used in the preliminary scoreboard. This score does not affect the final results, but nevertheless allows to roughly compare a solution with others. After the main phase ends, for each participant, the system chooses the final solution: consider all solutions sent for preliminary testing; choose the ones which got a total score strictly greater than zero; define the final solution as the one of chosen solutions which has the latest submission time. Note that the solutions sent only to be checked on examples are not considered when choosing the final solution.During final testing, all final solutions will be checked on the same set of a large number (\approx 1000) of final tests. The score for final tests determines the final scoreboard. The winner is the contestant whose solution gets the highest total score. In case two or more participants have equal total score, the contestants with such score tie for the same place.
Input45 15 0 0 0 02 13 30 2 200 4003 12 29 1 350 60039 21 9 4 671 757
Outputstart 335 1arrive 340 2work 340 370 2arrive 372 3work 372 401 3arrive 406 1endstart 335 1arrive 340 2work 340 370 2arrive 375 1end
15 seconds
768 megabytes
['*special problem']
B. Expansion coefficient of the arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call an array of non-negative integers a_1, a_2, \ldots, a_n a k-extension for some non-negative integer k if for all possible pairs of indices 1 \leq i, j \leq n the inequality k \cdot |i - j| \leq min(a_i, a_j) is satisfied. The expansion coefficient of the array a is the maximal integer k such that the array a is a k-extension. Any array is a 0-expansion, so the expansion coefficient always exists.You are given an array of non-negative integers a_1, a_2, \ldots, a_n. Find its expansion coefficient.InputThe first line contains one positive integer n — the number of elements in the array a (2 \leq n \leq 300\,000). The next line contains n non-negative integers a_1, a_2, \ldots, a_n, separated by spaces (0 \leq a_i \leq 10^9).OutputPrint one non-negative integer — expansion coefficient of the array a_1, a_2, \ldots, a_n.ExamplesInput 4 6 4 5 5 Output 1Input 3 0 1 2 Output 0Input 4 821 500 479 717 Output 239NoteIn the first test, the expansion coefficient of the array [6, 4, 5, 5] is equal to 1 because |i-j| \leq min(a_i, a_j), because all elements of the array satisfy a_i \geq 3. On the other hand, this array isn't a 2-extension, because 6 = 2 \cdot |1 - 4| \leq min(a_1, a_4) = 5 is false.In the second test, the expansion coefficient of the array [0, 1, 2] is equal to 0 because this array is not a 1-extension, but it is 0-extension.
4 6 4 5 5
1
1 second
256 megabytes
['implementation', 'math', '*1300']
A. A pile of stonestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.InputThe first line contains one positive integer n — the number of operations, that have been made by Vasya (1 \leq n \leq 100).The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).OutputPrint one integer — the minimal possible number of stones that can be in the pile after these n operations.ExamplesInput 3 --- Output 0Input 4 ++++ Output 4Input 2 -+ Output 1Input 5 ++-++ Output 3NoteIn the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
3 ---
0
1 second
256 megabytes
['implementation', 'math', '*800']
F. Density of subarraystime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet c be some positive integer. Let's call an array a_1, a_2, \ldots, a_n of positive integers c-array, if for all i condition 1 \leq a_i \leq c is satisfied. Let's call c-array b_1, b_2, \ldots, b_k a subarray of c-array a_1, a_2, \ldots, a_n, if there exists such set of k indices 1 \leq i_1 < i_2 < \ldots < i_k \leq n that b_j = a_{i_j} for all 1 \leq j \leq k. Let's define density of c-array a_1, a_2, \ldots, a_n as maximal non-negative integer p, such that any c-array, that contains p numbers is a subarray of a_1, a_2, \ldots, a_n.You are given a number c and some c-array a_1, a_2, \ldots, a_n. For all 0 \leq p \leq n find the number of sequences of indices 1 \leq i_1 < i_2 < \ldots < i_k \leq n for all 1 \leq k \leq n, such that density of array a_{i_1}, a_{i_2}, \ldots, a_{i_k} is equal to p. Find these numbers by modulo 998\,244\,353, because they can be too large.InputThe first line contains two integers n and c, separated by spaces (1 \leq n, c \leq 3\,000). The second line contains n integers a_1, a_2, \ldots, a_n, separated by spaces (1 \leq a_i \leq c).OutputPrint n + 1 numbers s_0, s_1, \ldots, s_n. s_p should be equal to the number of sequences of indices 1 \leq i_1 < i_2 < \ldots < i_k \leq n for all 1 \leq k \leq n by modulo 998\,244\,353, such that the density of array a_{i_1}, a_{i_2}, \ldots, a_{i_k} is equal to p. ExamplesInput 4 1 1 1 1 1 Output 0 4 6 4 1 Input 3 3 1 2 3 Output 6 1 0 0 Input 5 2 1 2 1 2 1 Output 10 17 4 0 0 0 NoteIn the first example, it's easy to see that the density of array will always be equal to its length. There exists 4 sequences with one index, 6 with two indices, 4 with three and 1 with four.In the second example, the only sequence of indices, such that the array will have non-zero density is all indices because in other cases there won't be at least one number from 1 to 3 in the array, so it won't satisfy the condition of density for p \geq 1.
4 1 1 1 1 1
0 4 6 4 1
6 seconds
256 megabytes
['dp', 'math', '*3500']
E. Strange devicetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is an interactive problem.Vasya enjoys solving quizzes. He found a strange device and wants to know how it works.This device encrypted with the tree (connected undirected graph without cycles) with n vertices, numbered with integers from 1 to n. To solve this quiz you should guess this tree.Fortunately, this device can make one operation, using which you should guess the cipher. You can give the device an array d_1, d_2, \ldots, d_n of non-negative integers. On the device, there are n lamps, i-th of them is connected with i-th vertex of the tree. For all i the light will turn on the i-th lamp, if there exist such vertex of the tree with number j \neq i that dist(i, j) \leq d_j. Let's define dist(i, j) as the distance between vertices i and j in tree or number of edges on the simple path between vertices i and j.Vasya wants to solve this quiz using \leq 80 operations with the device and guess the tree. Help him! InteractionIn the beginning, your program should read one integer n — the number of vertices of the tree which encrypts the device (2 \leq n \leq 1000).After that, you can make several operations in the following format. To do operation print a symbol"?" (without quotes) and n integers d_1, d_2, \ldots, d_n, separated by spaces after it. Please note, that for all i you can only use the numbers, satisfying the inequality 0 \leq d_i < n. After that, you should read a string s with length n, consisting of symbols "0" and "1" (without quotes). For all i the symbol s_i is equal to "0", if the lamp on the device, connected with i-th vertex of the tree is switched off and "1" otherwise.After several operations, you should print guessed tree. To do it print the only symbol "!" (without quotes). In the next n-1 lines print 2 integers a_i, b_i — indexes of the vertices connected by i-th edge of the tree. This numbers should satisfy the conditions 1 \leq a_i, b_i \leq n and a_i \neq b_i. This edges should form a tree, which is equal to the hidden tree. After that, your program should terminate.It is guaranteed, that in each test the tree is fixed before and won't change depending on your program's operations.Your program can make from 0 to 80 operations with the device and after that guess the tree equal with the hidden.If your program will make more than 80 operations it can get any verdict, because it will continue reading from closed input. If your program will make operation or print the answer in the incorrect format, it can get any verdict too. Be careful.Don't forget to flush the output after printing questions and answers.To flush the output, you can use: fflush(stdout) in C++. System.out.flush() in Java. stdout.flush() in Python. flush(output) in Pascal. See the documentation for other languages. Hacks:The first line should contain one integer n — the number of vertices in the tree (2 \leq n \leq 1000). Next n-1 lines should contain 2 integers a_i, b_i — indexes of the vertices connected by i-th edge of the tree (1 \leq a_i, b_i \leq n, a_i \neq b_i). All edges should form a tree. Be careful, extra spaces or line breaks are not allowed.ExampleInput 5 00000 11011 11100 10010 Output ? 0 0 0 0 0 ? 1 1 2 0 2 ? 0 0 0 1 0 ? 0 1 0 0 1 ! 4 2 1 5 3 4 4 1 NoteIt is a picture of the tree which encrypt the device from the first test: It is a table of pairwise distances between vertices in this tree: If you make operation where d = [0, 0, 0, 0, 0], no lamp will switch on, because dist(i, j) > 0 for all i \neq j. If you make operation where d = [1, 1, 2, 0, 2], all lamps except the lamp connected with the 3-rd vertex will switch on. For example, lamp connected with the 1-st vertex will switch on, because dist(1, 5) = 1 \leq 2 = d_5. If you make operation where d = [0, 0, 0, 1, 0], all lamps except lamps connected with the 4-th and 5-th vertices will switch on. If you make operation where d = [0, 1, 0, 0, 1], only lamps connected with the 1-st and 4-th vertices will switch on.
5 00000 11011 11100 10010
? 0 0 0 0 0 ? 1 1 2 0 2 ? 0 0 0 1 0 ? 0 1 0 0 1 ! 4 2 1 5 3 4 4 1
1 second
256 megabytes
['binary search', 'interactive', 'math', 'trees', '*3400']
D. Winding polygonal linetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has n different points A_1, A_2, \ldots A_n on the plane. No three of them lie on the same line He wants to place them in some order A_{p_1}, A_{p_2}, \ldots, A_{p_n}, where p_1, p_2, \ldots, p_n — some permutation of integers from 1 to n.After doing so, he will draw oriented polygonal line on these points, drawing oriented segments from each point to the next in the chosen order. So, for all 1 \leq i \leq n-1 he will draw oriented segment from point A_{p_i} to point A_{p_{i+1}}. He wants to make this polygonal line satisfying 2 conditions: it will be non-self-intersecting, so any 2 segments which are not neighbors don't have common points. it will be winding. Vasya has a string s, consisting of (n-2) symbols "L" or "R". Let's call an oriented polygonal line winding, if its i-th turn left, if s_i = "L" and right, if s_i = "R". More formally: i-th turn will be in point A_{p_{i+1}}, where oriented segment from point A_{p_i} to point A_{p_{i+1}} changes to oriented segment from point A_{p_{i+1}} to point A_{p_{i+2}}. Let's define vectors \overrightarrow{v_1} = \overrightarrow{A_{p_i} A_{p_{i+1}}} and \overrightarrow{v_2} = \overrightarrow{A_{p_{i+1}} A_{p_{i+2}}}. Then if in order to rotate the vector \overrightarrow{v_1} by the smallest possible angle, so that its direction coincides with the direction of the vector \overrightarrow{v_2} we need to make a turn counterclockwise, then we say that i-th turn is to the left, and otherwise to the right. For better understanding look at this pictures with some examples of turns: There are left turns on this picture There are right turns on this picture You are given coordinates of the points A_1, A_2, \ldots A_n on the plane and string s. Find a permutation p_1, p_2, \ldots, p_n of the integers from 1 to n, such that the polygonal line, drawn by Vasya satisfy two necessary conditions.InputThe first line contains one integer n — the number of points (3 \leq n \leq 2000). Next n lines contains two integers x_i and y_i, divided by space — coordinates of the point A_i on the plane (-10^9 \leq x_i, y_i \leq 10^9). The last line contains a string s consisting of symbols "L" and "R" with length (n-2). It is guaranteed that all points are different and no three points lie at the same line.OutputIf the satisfying permutation doesn't exists, print -1. In the other case, print n numbers p_1, p_2, \ldots, p_n — the permutation which was found (1 \leq p_i \leq n and all p_1, p_2, \ldots, p_n are different). If there exists more than one solution, you can find any.ExamplesInput 3 1 1 3 1 1 3 L Output 1 2 3Input 6 1 0 0 1 0 2 -1 0 -1 -1 2 1 RLLR Output 6 1 3 4 2 5 NoteThis is the picture with the polygonal line from the 1 test: As we see, this polygonal line is non-self-intersecting and winding, because the turn in point 2 is left.This is the picture with the polygonal line from the 2 test:
3 1 1 3 1 1 3 L
1 2 3
1 second
256 megabytes
['constructive algorithms', 'geometry', 'greedy', 'math', '*2600']
C. Permutation recoverytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has written some permutation p_1, p_2, \ldots, p_n of integers from 1 to n, so for all 1 \leq i \leq n it is true that 1 \leq p_i \leq n and all p_1, p_2, \ldots, p_n are different. After that he wrote n numbers next_1, next_2, \ldots, next_n. The number next_i is equal to the minimal index i < j \leq n, such that p_j > p_i. If there is no such j let's let's define as next_i = n + 1.In the evening Vasya went home from school and due to rain, his notebook got wet. Now it is impossible to read some written numbers. Permutation and some values next_i are completely lost! If for some i the value next_i is lost, let's say that next_i = -1.You are given numbers next_1, next_2, \ldots, next_n (maybe some of them are equal to -1). Help Vasya to find such permutation p_1, p_2, \ldots, p_n of integers from 1 to n, that he can write it to the notebook and all numbers next_i, which are not equal to -1, will be correct. InputThe first line contains one integer t — the number of test cases (1 \leq t \leq 100\,000).Next 2 \cdot t lines contains the description of test cases,two lines for each. The first line contains one integer n — the length of the permutation, written by Vasya (1 \leq n \leq 500\,000). The second line contains n integers next_1, next_2, \ldots, next_n, separated by spaces (next_i = -1 or i < next_i \leq n + 1).It is guaranteed, that the sum of n in all test cases doesn't exceed 500\,000.In hacks you can only use one test case, so T = 1.OutputPrint T lines, in i-th of them answer to the i-th test case.If there is no such permutations p_1, p_2, \ldots, p_n of integers from 1 to n, that Vasya could write, print the only number -1.In the other case print n different integers p_1, p_2, \ldots, p_n, separated by spaces (1 \leq p_i \leq n). All defined values of next_i which are not equal to -1 should be computed correctly p_1, p_2, \ldots, p_n using defenition given in the statement of the problem. If there exists more than one solution you can find any of them.ExampleInput 6 3 2 3 4 2 3 3 3 -1 -1 -1 3 3 4 -1 1 2 4 4 -1 4 5 Output 1 2 3 2 1 2 1 3 -1 1 3 2 1 4 NoteIn the first test case for permutation p = [1, 2, 3] Vasya should write next = [2, 3, 4], because each number in permutation is less than next. It's easy to see, that it is the only satisfying permutation.In the third test case, any permutation can be the answer because all numbers next_i are lost.In the fourth test case, there is no satisfying permutation, so the answer is -1.
6 3 2 3 4 2 3 3 3 -1 -1 -1 3 3 4 -1 1 2 4 4 -1 4 5
1 2 3 2 1 2 1 3 -1 1 3 2 1 4
1 second
256 megabytes
['constructive algorithms', 'data structures', 'dfs and similar', 'graphs', 'greedy', 'math', 'sortings', '*2100']
B. The minimal unique substringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet s be some string consisting of symbols "0" or "1". Let's call a string t a substring of string s, if there exists such number 1 \leq l \leq |s| - |t| + 1 that t = s_l s_{l+1} \ldots s_{l + |t| - 1}. Let's call a substring t of string s unique, if there exist only one such l. For example, let s = "1010111". A string t = "010" is an unique substring of s, because l = 2 is the only one suitable number. But, for example t = "10" isn't a unique substring of s, because l = 1 and l = 3 are suitable. And for example t ="00" at all isn't a substring of s, because there is no suitable l.Today Vasya solved the following problem at the informatics lesson: given a string consisting of symbols "0" and "1", the task is to find the length of its minimal unique substring. He has written a solution to this problem and wants to test it. He is asking you to help him.You are given 2 positive integers n and k, such that (n \bmod 2) = (k \bmod 2), where (x \bmod 2) is operation of taking remainder of x by dividing on 2. Find any string s consisting of n symbols "0" or "1", such that the length of its minimal unique substring is equal to k.InputThe first line contains two integers n and k, separated by spaces (1 \leq k \leq n \leq 100\,000, (k \bmod 2) = (n \bmod 2)).OutputPrint a string s of length n, consisting of symbols "0" and "1". Minimal length of the unique substring of s should be equal to k. You can find any suitable string. It is guaranteed, that there exists at least one such string.ExamplesInput 4 4 Output 1111Input 5 3 Output 01010Input 7 3 Output 1011011 NoteIn the first test, it's easy to see, that the only unique substring of string s = "1111" is all string s, which has length 4.In the second test a string s = "01010" has minimal unique substring t ="101", which has length 3.In the third test a string s = "1011011" has minimal unique substring t ="110", which has length 3.
4 4
1111
1 second
256 megabytes
['constructive algorithms', 'math', 'strings', '*2200']
A. The Party and Sweetstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputn boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 \leq i \leq n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i and for all 1 \leq j \leq m the maximal number of sweets, which j-th girl received from some boy is equal to g_j.More formally, let a_{i,j} be the number of sweets which the i-th boy give to the j-th girl. Then b_i is equal exactly to the minimum among values a_{i,1}, a_{i,2}, \ldots, a_{i,m} and g_j is equal exactly to the maximum among values b_{1,j}, b_{2,j}, \ldots, b_{n,j}.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of a_{i,j} for all (i,j) such that 1 \leq i \leq n and 1 \leq j \leq m. You are given the numbers b_1, \ldots, b_n and g_1, \ldots, g_m, determine this number. InputThe first line contains two integers n and m, separated with space — the number of boys and girls, respectively (2 \leq n, m \leq 100\,000). The second line contains n integers b_1, \ldots, b_n, separated by spaces — b_i is equal to the minimal number of sweets, which i-th boy presented to some girl (0 \leq b_i \leq 10^8). The third line contains m integers g_1, \ldots, g_m, separated by spaces — g_j is equal to the maximal number of sweets, which j-th girl received from some boy (0 \leq g_j \leq 10^8).OutputIf the described situation is impossible, print -1. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.ExamplesInput 3 2 1 2 1 3 4 Output 12Input 2 2 0 1 1 0 Output -1Input 2 3 1 0 1 1 2 Output 4NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to 12. This can be possible, for example, if the first boy presented 1 and 4 sweets, the second boy presented 3 and 2 sweets and the third boy presented 1 and 1 sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 12.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to 4. This can be possible, for example, if the first boy presented 1, 1, 2 sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 4.
3 2 1 2 1 3 4
12
1 second
256 megabytes
['binary search', 'constructive algorithms', 'greedy', 'implementation', 'math', 'sortings', 'two pointers', '*1500']
G. Inverse of Rows and Columnstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary matrix a of size n \times m. A binary matrix is a matrix where each element is either 0 or 1.You may perform some (possibly zero) operations with this matrix. During each operation you can inverse the row of this matrix or a column of this matrix. Formally, inverting a row is changing all values in this row to the opposite (0 to 1, 1 to 0). Inverting a column is changing all values in this column to the opposite.Your task is to sort the initial matrix by some sequence of such operations. The matrix is considered sorted if the array [a_{1, 1}, a_{1, 2}, \dots, a_{1, m}, a_{2, 1}, a_{2, 2}, \dots, a_{2, m}, \dots, a_{n, m - 1}, a_{n, m}] is sorted in non-descending order.InputThe first line of the input contains two integers n and m (1 \le n, m \le 200) — the number of rows and the number of columns in the matrix.The next n lines contain m integers each. The j-th element in the i-th line is a_{i, j} (0 \le a_{i, j} \le 1) — the element of a at position (i, j).OutputIf it is impossible to obtain a sorted matrix, print "NO" in the first line.Otherwise print "YES" in the first line. In the second line print a string r of length n. The i-th character r_i of this string should be '1' if the i-th row of the matrix is inverted and '0' otherwise. In the third line print a string c of length m. The j-th character c_j of this string should be '1' if the j-th column of the matrix is inverted and '0' otherwise. If there are multiple answers, you can print any.ExamplesInput 2 2 1 1 0 1 Output YES 00 10 Input 3 4 0 0 0 1 0 0 0 0 1 1 1 1 Output YES 010 0000 Input 3 3 0 0 0 1 0 1 1 1 0 Output NO
2 2 1 1 0 1
YES 00 10
2 seconds
256 megabytes
['brute force', 'constructive algorithms', '*2200']
F. Maximum Balanced Circletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, \dots, a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| \le 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| \le 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of people.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 height of the i-th person.OutputIn the first line of the output print k — the number of people in the maximum balanced circle.In the second line print k integers res_1, res_2, \dots, res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| \le 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| \le 1 should be also satisfied.ExamplesInput 7 4 3 5 1 2 2 1 Output 5 2 1 1 2 3 Input 5 3 7 5 1 5 Output 2 5 5 Input 3 5 1 4 Output 2 4 5 Input 7 2 2 3 2 1 2 2 Output 7 1 2 2 2 2 3 2
7 4 3 5 1 2 2 1
5 2 1 1 2 3
2 seconds
256 megabytes
['constructive algorithms', 'dp', 'greedy', 'two pointers', '*2000']
E. Minimum Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.Array x of length n is lexicographically less than array y of length n, if there exists such i (1 \le i \le n), that x_i < y_i, and for any j (1 \le j < i) x_j = y_j.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in a, b and c.The second line of the input contains n integers a_1, a_2, \dots, a_n (0 \le a_i < n), where a_i is the i-th element of a.The third line of the input contains n integers b_1, b_2, \dots, b_n (0 \le b_i < n), where b_i is the i-th element of b.OutputPrint the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.ExamplesInput 4 0 1 2 1 3 2 1 1 Output 1 0 0 2 Input 7 2 5 1 5 3 4 3 2 4 3 5 6 5 1 Output 0 0 0 1 0 2 4
4 0 1 2 1 3 2 1 1
1 0 0 2
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', '*1700']
D. N Problems During K Daystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has to solve exactly n problems to improve his programming skill before an important programming competition. But this competition will be held very soon, most precisely, it will start in k days. It means that Polycarp has exactly k days for training!Polycarp doesn't want to procrastinate, so he wants to solve at least one problem during each of k days. He also doesn't want to overwork, so if he solves x problems during some day, he should solve no more than 2x problems during the next day. And, at last, he wants to improve his skill, so if he solves x problems during some day, he should solve at least x+1 problem during the next day.More formally: let [a_1, a_2, \dots, a_k] be the array of numbers of problems solved by Polycarp. The i-th element of this array is the number of problems Polycarp solves during the i-th day of his training. Then the following conditions must be satisfied: sum of all a_i for i from 1 to k should be n; a_i should be greater than zero for each i from 1 to k; the condition a_i < a_{i + 1} \le 2 a_i should be satisfied for each i from 1 to k-1. Your problem is to find any array a of length k satisfying the conditions above or say that it is impossible to do it.InputThe first line of the input contains two integers n and k (1 \le n \le 10^9, 1 \le k \le 10^5) — the number of problems Polycarp wants to solve and the number of days Polycarp wants to train.OutputIf it is impossible to find any array a of length k satisfying Polycarp's rules of training, print "NO" in the first line.Otherwise print "YES" in the first line, then print k integers a_1, a_2, \dots, a_k in the second line, where a_i should be the number of problems Polycarp should solve during the i-th day. If there are multiple answers, you can print any.ExamplesInput 26 6 Output YES 1 2 4 5 6 8 Input 8 3 Output NO Input 1 1 Output YES 1 Input 9 4 Output NO
26 6
YES 1 2 4 5 6 8
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*1900']
C2. Increasing Subsequence (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence a consisting of n integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence [1, 2, 4, 3, 2] the answer is 4 (you take 1 and the sequence becomes [2, 4, 3, 2], then you take the rightmost element 2 and the sequence becomes [2, 4, 3], then you take 3 and the sequence becomes [2, 4] and then you take 4 and the sequence becomes [2], the obtained increasing sequence is [1, 2, 3, 4]).InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in a.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.OutputIn the first line of the output print k — the maximum number of elements in a strictly increasing sequence you can obtain.In the second line print a string s of length k, where the j-th character of this string s_j should be 'L' if you take the leftmost element during the j-th move and 'R' otherwise. If there are multiple answers, you can print any.ExamplesInput 5 1 2 4 3 2 Output 4 LRRR Input 7 1 3 5 6 5 4 2 Output 6 LRLRRR Input 3 2 2 2 Output 1 R Input 4 1 2 4 3 Output 4 LLRR NoteThe first example is described in the problem statement.
5 1 2 4 3 2
4 LRRR
2 seconds
256 megabytes
['greedy', '*1700']
C1. Increasing Subsequence (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence a consisting of n integers. All these integers are distinct, each value from 1 to n appears in the sequence exactly once.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence [2, 1, 5, 4, 3] the answer is 4 (you take 2 and the sequence becomes [1, 5, 4, 3], then you take the rightmost element 3 and the sequence becomes [1, 5, 4], then you take 4 and the sequence becomes [1, 5] and then you take 5 and the sequence becomes [1], the obtained increasing sequence is [2, 3, 4, 5]).InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in a.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n), where a_i is the i-th element of a. All these integers are pairwise distinct.OutputIn the first line of the output print k — the maximum number of elements in a strictly increasing sequence you can obtain.In the second line print a string s of length k, where the j-th character of this string s_j should be 'L' if you take the leftmost element during the j-th move and 'R' otherwise. If there are multiple answers, you can print any.ExamplesInput 5 2 1 5 4 3 Output 4 LRRR Input 7 1 3 5 6 7 4 2 Output 7 LRLRLLL Input 3 1 2 3 Output 3 LLL Input 4 1 2 4 3 Output 4 LLRL NoteThe first example is described in the problem statement.
5 2 1 5 4 3
4 LRRR
2 seconds
256 megabytes
['greedy', '*1300']
B. Long Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a long decimal number a consisting of n digits from 1 to 9. You also have a function f that maps every digit from 1 to 9 to some (possibly the same) digit from 1 to 9.You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in a, and replace each digit x from this segment with f(x). For example, if a = 1337, f(1) = 1, f(3) = 5, f(7) = 3, and you choose the segment consisting of three rightmost digits, you get 1553 as the result.What is the maximum possible number you can obtain applying this operation no more than once?InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of digits in a.The second line contains a string of n characters, denoting the number a. Each character is a decimal digit from 1 to 9.The third line contains exactly 9 integers f(1), f(2), ..., f(9) (1 \le f(i) \le 9).OutputPrint the maximum number you can get after applying the operation described in the statement no more than once.ExamplesInput 4 1337 1 2 5 4 6 6 3 1 9 Output 1557 Input 5 11111 9 8 7 6 5 4 3 2 1 Output 99999 Input 2 33 1 1 1 1 1 1 1 1 1 Output 33
4 1337 1 2 5 4 6 6 3 1 9
1557
2 seconds
256 megabytes
['greedy', '*1300']
A. Reachable Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example, f(599) = 6: 599 + 1 = 600 \rightarrow 60 \rightarrow 6; f(7) = 8: 7 + 1 = 8; f(9) = 1: 9 + 1 = 10 \rightarrow 1; f(10099) = 101: 10099 + 1 = 10100 \rightarrow 1010 \rightarrow 101. We say that some number y is reachable from x if we can apply function f to x some (possibly zero) times so that we get y as a result. For example, 102 is reachable from 10098 because f(f(f(10098))) = f(f(10099)) = f(101) = 102; and any number is reachable from itself.You are given a number n; your task is to count how many different numbers are reachable from n.InputThe first line contains one integer n (1 \le n \le 10^9).OutputPrint one integer: the number of different numbers that are reachable from n.ExamplesInput 1098 Output 20 Input 10 Output 19 NoteThe numbers that are reachable from 1098 are:1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1098, 1099.
1098
20
1 second
256 megabytes
['implementation', '*1100']
G. Optimizertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's analyze a program written on some strange programming language. The variables in this language have names consisting of 1 to 4 characters, and each character is a lowercase or an uppercase Latin letter, or a digit. There is an extra constraint that the first character should not be a digit.There are four types of operations in the program, each denoted by one of the characters: $, ^, # or &.Each line of the program has one of the following formats: <lvalue>=<rvalue>, where <lvalue> and <rvalue> are valid variable names; <lvalue>=<arg1><op><arg2>, where <lvalue>, <arg1> and <arg2> are valid variable names, and <op> is an operation character. The program is executed line-by-line, and the result of execution is stored in a variable having the name res. If res is never assigned in the program, then the result will be equal to the value of res before running the program.Two programs are called equivalent if no matter which operations do characters $, ^, # and & denote (but, obviously, performing the same operation on the same arguments gives the same result) and which values do variables have before execution of program, the value of res after running the first program is equal to the value of res after running the second program (the programs are executed independently).You are given a program consisting of n lines. Your task is to write a program consisting of minimum possible number of lines that is equivalent to the program you are given.InputThe first line contains one integer n (1 \le n \le 1000) — the number of lines in the program.Then n lines follow — the program itself. Each line corresponds to the format described in the statement and has no extra whitespaces.OutputIn the first line print k — the minimum number of lines in the equivalent program.Then print k lines without any whitespaces — an equivalent program having exactly k lines, in the same format it is described in the statement.ExamplesInput 4 c=aa#bb d12=c res=c^d12 tmp=aa$c Output 2 aaaa=aa#bb res=aaaa^aaaa Input 2 max=aaaa$bbbb min=bbbb^aaaa Output 0
4 c=aa#bb d12=c res=c^d12 tmp=aa$c
2 aaaa=aa#bb res=aaaa^aaaa
1 second
256 megabytes
['graphs', 'greedy', 'hashing', 'implementation', '*2700']
F. Card Bagtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have a bag which contains n cards. There is a number written on each card; the number on i-th card is a_i.You are playing the following game. During each turn, you choose and remove a random card from the bag (all cards that are still left inside the bag are chosen equiprobably). Nothing else happens during the first turn — but during the next turns, after removing a card (let the number on it be x), you compare it with the card that was removed during the previous turn (let the number on it be y). Possible outcomes are: if x < y, the game ends and you lose; if x = y, the game ends and you win; if x > y, the game continues. If there are no cards left in the bag, you lose. Cards are not returned into the bag after you remove them.You have to calculate the probability of winning in this game. It can be shown that it is in the form of \frac{P}{Q} where P and Q are non-negative integers and Q \neq 0, P \le Q. Output the value of P \cdot Q^{−1} ~(mod ~~ 998244353).InputThe first line contains one integer n (2 \le n \le 5000) — the number of cards in the bag.The second live contains n integers a_1, a_2, \dots a_n (1 \le a_i \le n) — the i-th integer is the number written on the i-th card. OutputPrint one integer — the probability of winning in this game modulo 998244353.ExamplesInput 5 1 1 4 2 3 Output 299473306 Input 2 2 2 Output 1 Input 5 4 5 1 3 2 Output 0 Input 4 1 3 4 3 Output 748683265 NoteIn the first test case the probability of winning is \frac{1}{10}.In the second test case the probability of winning is 1.In the third test case the probability of winning is 0.In the fourth test case the probability of winning is \frac{1}{4}.
5 1 1 4 2 3
299473306
2 seconds
512 megabytes
['dp', 'math', 'probabilities', '*2300']
E. Special Segments of Permutationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a permutation p of n integers 1, 2, ..., n (a permutation is an array where each element from 1 to n occurs exactly once).Let's call some subsegment p[l, r] of this permutation special if p_l + p_r = \max \limits_{i = l}^{r} p_i. Please calculate the number of special subsegments.InputThe first line contains one integer n (3 \le n \le 2 \cdot 10^5).The second line contains n integers p_1, p_2, ..., p_n (1 \le p_i \le n). All these integers are pairwise distinct.OutputPrint the number of special subsegments of the given permutation.ExamplesInput 5 3 4 1 5 2 Output 2 Input 3 1 3 2 Output 1 NoteSpecial subsegments in the first example are [1, 5] and [1, 3].The only special subsegment in the second example is [1, 3].
5 3 4 1 5 2
2
2 seconds
512 megabytes
['data structures', 'divide and conquer', 'dsu', 'two pointers', '*2200']
D. 0-1-Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).Let's call an ordered pair of vertices (x, y) (x \ne y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.InputThe first line contains one integer n (2 \le n \le 200000) — the number of vertices in the tree.Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 \le x_i, y_i \le n, 0 \le c_i \le 1, x_i \ne y_i) — the vertices connected by this edge and the number written on it, respectively.It is guaranteed that the given edges form a tree.OutputPrint one integer — the number of valid pairs of vertices.ExampleInput 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 NoteThe picture corresponding to the first example:
7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1
34
2 seconds
256 megabytes
['dfs and similar', 'divide and conquer', 'dp', 'dsu', 'trees', '*2200']
C. Match Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of points x_1, x_2, ..., x_n on the number line.Two points i and j can be matched with each other if the following conditions hold: neither i nor j is matched with any other point; |x_i - x_j| \ge z. What is the maximum number of pairs of points you can match with each other?InputThe first line contains two integers n and z (2 \le n \le 2 \cdot 10^5, 1 \le z \le 10^9) — the number of points and the constraint on the distance between matched points, respectively.The second line contains n integers x_1, x_2, ..., x_n (1 \le x_i \le 10^9).OutputPrint one integer — the maximum number of pairs of points you can match with each other.ExamplesInput 4 2 1 3 3 7 Output 2 Input 5 5 10 9 5 8 7 Output 1 NoteIn the first example, you may match point 1 with point 2 (|3 - 1| \ge 2), and point 3 with point 4 (|7 - 3| \ge 2).In the second example, you may match point 1 with point 3 (|5 - 10| \ge 5).
4 2 1 3 3 7
2
2 seconds
256 megabytes
['binary search', 'greedy', 'sortings', 'ternary search', 'two pointers', '*2000']
B. Ugly Pairstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string, consisting of lowercase Latin letters.A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) — "ab" and (2, 3) — "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.If there are multiple answers, print any of them.You also have to answer T separate queries.InputThe first line contains a single integer T (1 \le T \le 100) — the number of queries.Each of the next T lines contains string s (1 \le |s| \le 100) — the string for the next query. It is guaranteed that it contains only lowercase Latin letters.Note that in hacks you have to set T = 1.OutputPrint T lines. The i-th line should contain the answer to the i-th query.If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.If there are multiple answers, print any of them.Otherwise print "No answer" for that query.ExampleInput 4 abcd gg codeforces abaca Output cadb gg codfoerces No answer NoteIn the first example answer "bdac" is also correct.The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.There are lots of valid answers for the third example.
4 abcd gg codeforces abaca
cadb gg codfoerces No answer
1 second
256 megabytes
['dfs and similar', 'greedy', 'implementation', 'sortings', 'strings', '*1800']
A. Inscribed Figurestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier.Future students will be asked just a single question. They are given a sequence of integer numbers a_1, a_2, \dots, a_n, each number is from 1 to 3 and a_i \ne a_{i + 1} for each valid i. The i-th number represents a type of the i-th figure: circle; isosceles triangle with the length of height equal to the length of base; square. The figures of the given sequence are placed somewhere on a Cartesian plane in such a way that: (i + 1)-th figure is inscribed into the i-th one; each triangle base is parallel to OX; the triangle is oriented in such a way that the vertex opposite to its base is at the top; each square sides are parallel to the axes; for each i from 2 to n figure i has the maximum possible length of side for triangle and square and maximum radius for circle. Note that the construction is unique for some fixed position and size of just the first figure.The task is to calculate the number of distinct points (not necessarily with integer coordinates) where figures touch. The trick is, however, that the number is sometimes infinite. But that won't make the task difficult for you, will it?So can you pass the math test and enroll into Berland State University?InputThe first line contains a single integer n (2 \le n \le 100) — the number of figures.The second line contains n integer numbers a_1, a_2, \dots, a_n (1 \le a_i \le 3, a_i \ne a_{i + 1}) — types of the figures.OutputThe first line should contain either the word "Infinite" if the number of distinct points where figures touch is infinite or "Finite" otherwise.If the number is finite than print it in the second line. It's guaranteed that the number fits into 32-bit integer type.ExamplesInput 3 2 1 3 Output Finite 7 Input 3 1 2 3 Output Infinite NoteHere are the glorious pictures for the examples. Note that the triangle is not equilateral but just isosceles with the length of height equal to the length of base. Thus it fits into a square in a unique way.The distinct points where figures touch are marked red.In the second example the triangle and the square touch each other for the whole segment, it contains infinite number of points.
3 2 1 3
Finite 7
1 second
256 megabytes
['geometry', '*1400']