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
C. Monster Invaderstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputZiota found a video game called "Monster Invaders".Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns.For the sake of simplicity, we only consider two different types of monsters and three different types of guns.Namely, the two types of monsters are: a normal monster with 1 hp. a boss with 2 hp. And the three types of guns are: Pistol, deals 1 hp in damage to one monster, r_1 reloading time Laser gun, deals 1 hp in damage to all the monsters in the current level (including the boss), r_2 reloading time AWP, instantly kills any monster, r_3 reloading time The guns are initially not loaded, and the Ziota can only reload 1 gun at a time.The levels of the game can be considered as an array a_1, a_2, \ldots, a_n, in which the i-th stage has a_i normal monsters and 1 boss. Due to the nature of the game, Ziota cannot use the Pistol (the first type of gun) or AWP (the third type of gun) to shoot the boss before killing all of the a_i normal monsters.If Ziota damages the boss but does not kill it immediately, he is forced to move out of the current level to an arbitrary adjacent level (adjacent levels of level i (1 < i < n) are levels i - 1 and i + 1, the only adjacent level of level 1 is level 2, the only adjacent level of level n is level n - 1). Ziota can also choose to move to an adjacent level at any time. Each move between adjacent levels are managed by portals with d teleportation time.In order not to disrupt the space-time continuum within the game, it is strictly forbidden to reload or shoot monsters during teleportation. Ziota starts the game at level 1. The objective of the game is rather simple, to kill all the bosses in all the levels. He is curious about the minimum time to finish the game (assuming it takes no time to shoot the monsters with a loaded gun and Ziota has infinite ammo on all the three guns). Please help him find this value.InputThe first line of the input contains five integers separated by single spaces: n (2 \le n \le 10^6) — the number of stages, r_1, r_2, r_3 (1 \le r_1 \le r_2 \le r_3 \le 10^9) — the reload time of the three guns respectively, d (1 \le d \le 10^9) — the time of moving between adjacent levels.The second line of the input contains n integers separated by single spaces a_1, a_2, \dots, a_n (1 \le a_i \le 10^6, 1 \le i \le n).OutputPrint one integer, the minimum time to finish the game.ExamplesInput 4 1 3 4 3 3 2 5 1 Output 34Input 4 2 4 4 1 4 5 1 2 Output 31NoteIn the first test case, the optimal strategy is: Use the pistol to kill three normal monsters and AWP to kill the boss (Total time 1\cdot3+4=7) Move to stage two (Total time 7+3=10) Use the pistol twice and AWP to kill the boss (Total time 10+1\cdot2+4=16) Move to stage three (Total time 16+3=19) Use the laser gun and forced to move to either stage four or two, here we move to stage four (Total time 19+3+3=25) Use the pistol once, use AWP to kill the boss (Total time 25+1\cdot1+4=30) Move back to stage three (Total time 30+3=33) Kill the boss at stage three with the pistol (Total time 33+1=34) Note that here, we do not finish at level n, but when all the bosses are killed.
4 1 3 4 3 3 2 5 1
34
2 seconds
512 megabytes
['dp', 'greedy', 'implementation', '*2300']
B. Stoned Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputT is playing a game with his friend, HL.There are n piles of stones, the i-th pile initially has a_i stones. T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in the previous turn (the pile that was chosen by the other player, or if the current turn is the first turn then the player can choose any non-empty pile). The player who cannot choose a pile in his turn loses, and the game ends.Assuming both players play optimally, given the starting configuration of t games, determine the winner of each game.InputThe first line of the input contains a single integer t (1 \le t \le 100) — the number of games. The description of the games follows. Each description contains two lines:The first line contains a single integer n (1 \le n \le 100) — the number of piles.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100).OutputFor each game, print on a single line the name of the winner, "T" or "HL" (without quotes)ExampleInput 2 1 2 2 1 1 Output T HL NoteIn the first game, T removes a single stone from the only pile in his first turn. After that, although the pile still contains 1 stone, HL cannot choose from this pile because it has been chosen by T in the previous turn. Therefore, T is the winner.
2 1 2 2 1 1
T HL
1 second
256 megabytes
['brute force', 'constructive algorithms', 'games', 'greedy', '*1800']
A. Multiples of Lengthtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers.You want to make all elements of a equal to zero by doing the following operation exactly three times: Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different). It can be proven that it is always possible to make all elements of a equal to zero.InputThe first line contains one integer n (1 \le n \le 100\,000): the number of elements of the array.The second line contains n elements of an array a separated by spaces: a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9).OutputThe output should contain six lines representing three operations.For each operation, print two lines: The first line contains two integers l, r (1 \le l \le r \le n): the bounds of the selected segment. The second line contains r-l+1 integers b_l, b_{l+1}, \dots, b_r (-10^{18} \le b_i \le 10^{18}): the numbers to add to a_l, a_{l+1}, \ldots, a_r, respectively; b_i should be divisible by r - l + 1. ExampleInput 4 1 3 2 4 Output 1 1 -1 3 4 4 2 2 4 -3 -6 -6
4 1 3 2 4
1 1 -1 3 4 4 2 2 4 -3 -6 -6
1 second
256 megabytes
['constructive algorithms', 'greedy', 'number theory', '*1600']
C. Boboniu and Bit Operationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBoboniu likes bit operations. He wants to play a game with you.Boboniu gives you two sequences of non-negative integers a_1,a_2,\ldots,a_n and b_1,b_2,\ldots,b_m.For each i (1\le i\le n), you're asked to choose a j (1\le j\le m) and let c_i=a_i\& b_j, where \& denotes the bitwise AND operation. Note that you can pick the same j for different i's.Find the minimum possible c_1 | c_2 | \ldots | c_n, where | denotes the bitwise OR operation.InputThe first line contains two integers n and m (1\le n,m\le 200).The next line contains n integers a_1,a_2,\ldots,a_n (0\le a_i < 2^9).The next line contains m integers b_1,b_2,\ldots,b_m (0\le b_i < 2^9).OutputPrint one integer: the minimum possible c_1 | c_2 | \ldots | c_n.ExamplesInput 4 2 2 6 4 0 2 4 Output 2Input 7 6 1 9 1 9 8 1 0 1 1 4 5 1 4 Output 0Input 8 5 179 261 432 162 82 43 10 38 379 357 202 184 197 Output 147NoteFor the first example, we have c_1=a_1\& b_2=0, c_2=a_2\& b_1=2, c_3=a_3\& b_1=0, c_4 = a_4\& b_1=0.Thus c_1 | c_2 | c_3 |c_4 =2, and this is the minimal answer we can get.
4 2 2 6 4 0 2 4
2
1 second
256 megabytes
['bitmasks', 'brute force', 'dp', 'greedy', '*1600']
B. Boboniu Plays Chesstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputBoboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.You are a new applicant for his company. Boboniu will test you with the following chess question:Consider a n\times m grid (rows are numbered from 1 to n, and columns are numbered from 1 to m). You have a chess piece, and it stands at some cell (S_x,S_y) which is not on the border (i.e. 2 \le S_x \le n-1 and 2 \le S_y \le m-1).From the cell (x,y), you can move your chess piece to (x,y') (1\le y'\le m, y' \neq y) or (x',y) (1\le x'\le n, x'\neq x). In other words, the chess piece moves as a rook. From the cell, you can move to any cell on the same row or column.Your goal is to visit each cell exactly once. Can you find a solution?Note that cells on the path between two adjacent cells in your route are not counted as visited, and it is not required to return to the starting point.InputThe only line of the input contains four integers n, m, S_x and S_y (3\le n,m\le 100, 2 \le S_x \le n-1, 2 \le S_y \le m-1) — the number of rows, the number of columns, and the initial position of your chess piece, respectively.OutputYou should print n\cdot m lines.The i-th line should contain two integers x_i and y_i (1 \leq x_i \leq n, 1 \leq y_i \leq m), denoting the i-th cell that you visited. You should print exactly nm pairs (x_i, y_i), they should cover all possible pairs (x_i, y_i), such that 1 \leq x_i \leq n, 1 \leq y_i \leq m.We can show that under these constraints there always exists a solution. If there are multiple answers, print any.ExamplesInput 3 3 2 2 Output 2 2 1 2 1 3 2 3 3 3 3 2 3 1 2 1 1 1 Input 3 4 2 2 Output 2 2 2 1 2 3 2 4 1 4 3 4 3 3 3 2 3 1 1 1 1 2 1 3 NotePossible routes for two examples:
3 3 2 2
2 2 1 2 1 3 2 3 3 3 3 2 3 1 2 1 1 1
1 second
512 megabytes
['constructive algorithms', '*1100']
A. Boboniu Likes to Color Ballstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBoboniu gives you r red balls, g green balls, b blue balls, w white balls. He allows you to do the following operation as many times as you want: Pick a red ball, a green ball, and a blue ball and then change their color to white. You should answer if it's possible to arrange all the balls into a palindrome after several (possibly zero) number of described operations. InputThe first line contains one integer T (1\le T\le 100) denoting the number of test cases.For each of the next T cases, the first line contains four integers r, g, b and w (0\le r,g,b,w\le 10^9).OutputFor each test case, print "Yes" if it's possible to arrange all the balls into a palindrome after doing several (possibly zero) number of described operations. Otherwise, print "No".ExampleInput 4 0 1 1 1 8 1 9 3 0 0 0 0 1000000000 1000000000 1000000000 1000000000 Output No Yes Yes Yes NoteIn the first test case, you're not able to do any operation and you can never arrange three balls of distinct colors into a palindrome.In the second test case, after doing one operation, changing (8,1,9,3) to (7,0,8,6), one of those possible palindromes may be "rrrwwwbbbbrbbbbwwwrrr".A palindrome is a word, phrase, or sequence that reads the same backwards as forwards. For example, "rggbwbggr", "b", "gg" are palindromes while "rgbb", "gbbgr" are not. Notice that an empty word, phrase, or sequence is palindrome.
4 0 1 1 1 8 1 9 3 0 0 0 0 1000000000 1000000000 1000000000 1000000000
No Yes Yes Yes
1 second
256 megabytes
['brute force', 'math', '*1000']
E. Boboniu and Banknote Collectiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNo matter what trouble you're in, don't be afraid, but face it with a smile.I've made another billion dollars! — BoboniuBoboniu has issued his currencies, named Bobo Yuan. Bobo Yuan (BBY) is a series of currencies. Boboniu gives each of them a positive integer identifier, such as BBY-1, BBY-2, etc.Boboniu has a BBY collection. His collection looks like a sequence. For example: We can use sequence a=[1,2,3,3,2,1,4,4,1] of length n=9 to denote it.Now Boboniu wants to fold his collection. You can imagine that Boboniu stick his collection to a long piece of paper and fold it between currencies: Boboniu will only fold the same identifier of currencies together. In other words, if a_i is folded over a_j (1\le i,j\le n), then a_i=a_j must hold. Boboniu doesn't care if you follow this rule in the process of folding. But once it is finished, the rule should be obeyed.A formal definition of fold is described in notes.According to the picture above, you can fold a two times. In fact, you can fold a=[1,2,3,3,2,1,4,4,1] at most two times. So the maximum number of folds of it is 2.As an international fan of Boboniu, you're asked to calculate the maximum number of folds. You're given a sequence a of length n, for each i (1\le i\le n), you need to calculate the maximum number of folds of [a_1,a_2,\ldots,a_i].InputThe first line contains an integer n (1\le n\le 10^5).The second line contains n integers a_1,a_2,\ldots,a_n (1\le a_i\le n).OutputPrint n integers. The i-th of them should be equal to the maximum number of folds of [a_1,a_2,\ldots,a_i].ExamplesInput 9 1 2 3 3 2 1 4 4 1 Output 0 0 0 1 1 1 1 2 2 Input 9 1 2 2 2 2 1 1 2 2 Output 0 0 1 2 3 3 4 4 5 Input 15 1 2 3 4 5 5 4 3 2 2 3 4 4 3 6 Output 0 0 0 0 0 1 1 1 1 2 2 2 3 3 0 Input 50 1 2 4 6 6 4 2 1 3 5 5 3 1 2 4 4 2 1 3 3 1 2 2 1 1 1 2 4 6 6 4 2 1 3 5 5 3 1 2 4 4 2 1 3 3 1 2 2 1 1 Output 0 0 0 0 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 5 5 6 7 3 3 3 4 4 4 4 3 3 4 4 4 4 4 5 5 5 5 6 6 6 7 7 8 NoteFormally, for a sequence a of length n, let's define the folding sequence as a sequence b of length n such that: b_i (1\le i\le n) is either 1 or -1. Let p(i)=[b_i=1]+\sum_{j=1}^{i-1}b_j. For all 1\le i<j\le n, if p(i)=p(j), then a_i should be equal to a_j. ([A] is the value of boolean expression A. i. e. [A]=1 if A is true, else [A]=0).Now we define the number of folds of b as f(b)=\sum_{i=1}^{n-1}[b_i\ne b_{i+1}].The maximum number of folds of a is F(a)=\max\{ f(b)\mid b \text{ is a folding sequence of }a \}.
9 1 2 3 3 2 1 4 4 1
0 0 0 1 1 1 1 2 2
1 second
256 megabytes
['strings', '*3500']
D. Boboniu and Jianghutime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSince Boboniu finished building his Jianghu, he has been doing Kungfu on these mountains every day. Boboniu designs a map for his n mountains. He uses n-1 roads to connect all n mountains. Every pair of mountains is connected via roads.For the i-th mountain, Boboniu estimated the tiredness of doing Kungfu on the top of it as t_i. He also estimated the height of each mountain as h_i.A path is a sequence of mountains M such that for each i (1 \le i < |M|), there exists a road between M_i and M_{i+1}. Boboniu would regard the path as a challenge if for each i (1\le i<|M|), h_{M_i}\le h_{M_{i+1}}.Boboniu wants to divide all n-1 roads into several challenges. Note that each road must appear in exactly one challenge, but a mountain may appear in several challenges. Boboniu wants to minimize the total tiredness to do all the challenges. The tiredness of a challenge M is the sum of tiredness of all mountains in it, i.e. \sum_{i=1}^{|M|}t_{M_i}. He asked you to find the minimum total tiredness. As a reward for your work, you'll become a guardian in his Jianghu.InputThe first line contains a single integer n (2 \le n \le 2 \cdot 10^5), denoting the number of the mountains.The second line contains n integers t_1, t_2, \ldots, t_n (1 \le t_i \le 10^6), denoting the tiredness for Boboniu to do Kungfu on each mountain.The third line contains n integers h_1, h_2, \ldots, h_n (1 \le h_i \le 10^6), denoting the height of each mountain.Each of the following n - 1 lines contains two integers u_i, v_i (1 \le u_i, v_i \le n, u_i \neq v_i), denoting the ends of the road. It's guaranteed that all mountains are connected via roads.OutputPrint one integer: the smallest sum of tiredness of all challenges.ExamplesInput 5 40 10 30 50 20 2 3 2 3 1 1 2 1 3 2 4 2 5 Output 160 Input 5 1000000 1 1 1 1 1000000 1 1 1 1 1 2 1 3 1 4 1 5 Output 4000004 Input 10 510916 760492 684704 32545 484888 933975 116895 77095 127679 989957 402815 705067 705067 705067 623759 103335 749243 138306 138306 844737 1 2 3 2 4 3 1 5 6 4 6 7 8 7 8 9 9 10 Output 6390572 NoteFor the first example: In the picture, the lighter a point is, the higher the mountain it represents. One of the best divisions is: Challenge 1: 3 \to 1 \to 2 Challenge 2: 5 \to 2 \to 4 The total tiredness of Boboniu is (30 + 40 + 10) + (20 + 10 + 50) = 160. It can be shown that this is the minimum total tiredness.
5 40 10 30 50 20 2 3 2 3 1 1 2 1 3 2 4 2 5
160
1 second
256 megabytes
['dp', 'greedy', 'sortings', 'trees', '*2800']
C. Boboniu and Stringtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBoboniu defines BN-string as a string s of characters 'B' and 'N'.You can perform the following operations on the BN-string s: Remove a character of s. Remove a substring "BN" or "NB" of s. Add a character 'B' or 'N' to the end of s. Add a string "BN" or "NB" to the end of s. Note that a string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Boboniu thinks that BN-strings s and t are similar if and only if: |s|=|t|. There exists a permutation p_1, p_2, \ldots, p_{|s|} such that for all i (1\le i\le |s|), s_{p_i}=t_i. Boboniu also defines \text{dist}(s,t), the distance between s and t, as the minimum number of operations that makes s similar to t.Now Boboniu gives you n non-empty BN-strings s_1,s_2,\ldots, s_n and asks you to find a non-empty BN-string t such that the maximum distance to string s is minimized, i.e. you need to minimize \max_{i=1}^n \text{dist}(s_i,t).InputThe first line contains a single integer n (1\le n\le 3\cdot 10^5).Each of the next n lines contains a string s_i (1\le |s_i| \le 5\cdot 10^5). It is guaranteed that s_i only contains 'B' and 'N'. The sum of |s_i| does not exceed 5\cdot 10^5.OutputIn the first line, print the minimum \max_{i=1}^n \text{dist}(s_i,t).In the second line, print the suitable t.If there are several possible t's, you can print any.ExamplesInput 3 B N BN Output 1 BN Input 10 N BBBBBB BNNNBBNBB NNNNBNBNNBNNNBBN NBNBN NNNNNN BNBNBNBBBBNNNNBBBBNNBBNBNBBNBBBBBBBB NNNNBN NBBBBBBBB NNNNNN Output 12 BBBBBBBBBBBBNNNNNNNNNNNN Input 8 NNN NNN BBNNBBBN NNNBNN B NNN NNNNBNN NNNNNNNNNNNNNNNBNNNNNNNBNB Output 12 BBBBNNNNNNNNNNNN Input 3 BNNNBNNNNBNBBNNNBBNNNNBBBBNNBBBBBBNBBBBBNBBBNNBBBNBNBBBN BBBNBBBBNNNNNBBNBBBNNNBB BBBBBBBBBBBBBBNBBBBBNBBBBBNBBBBNB Output 12 BBBBBBBBBBBBBBBBBBBBBBBBBBNNNNNNNNNNNN NoteIn the first example \text{dist(B,BN)}=\text{dist(N,BN)}=1, \text{dist(BN,BN)}=0. So the maximum distance is 1.
3 B N BN
1 BN
3 seconds
256 megabytes
['binary search', 'geometry', 'ternary search', '*2600']
B. Boboniu Walks on Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBoboniu has a directed graph with n vertices and m edges.The out-degree of each vertex is at most k.Each edge has an integer weight between 1 and m. No two edges have equal weights.Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,\ldots,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1\le c_i\le i) smallest weight among all edges outgoing from u.Now Boboniu asks you to calculate the number of tuples (c_1,c_2,\ldots,c_k) such that 1\le c_i\le i for all i (1\le i\le k). Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules. InputThe first line contains three integers n, m and k (2\le n\le 2\cdot 10^5, 2\le m\le \min(2\cdot 10^5,n(n-1) ), 1\le k\le 9).Each of the next m lines contains three integers u, v and w (1\le u,v\le n,u\ne v,1\le w\le m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself.It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight.OutputPrint one integer: the number of tuples.ExamplesInput 4 6 3 4 2 1 1 2 2 2 4 3 4 1 4 4 3 5 3 1 6 Output 2 Input 5 5 1 1 4 1 5 1 2 2 5 3 4 3 4 3 2 5 Output 1 Input 6 13 4 3 5 1 2 5 2 6 3 3 1 4 4 2 6 5 5 3 6 4 1 7 4 3 8 5 2 9 4 2 10 2 1 11 6 1 12 4 6 13 Output 1 NoteFor the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through. For the third example, there's only one tuple: (1,2,2,2). The out-degree of vertex u means the number of edges outgoing from u.
4 6 3 4 2 1 1 2 2 2 4 3 4 1 4 4 3 5 3 1 6
2
1 second
256 megabytes
['brute force', 'dfs and similar', 'graphs', 'hashing', '*2300']
A. Boboniu Chats with Dutime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHave you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.Du will chat in the group for n days. On the i-th day: If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, \cdots, \min(i+d,n)-th days. Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak.Du asked you to find the maximum total fun factor among all possible permutations of a.InputThe first line contains three integers n, d and m (1\le d\le n\le 10^5,0\le m\le 10^9).The next line contains n integers a_1, a_2, \ldots,a_n (0\le a_i\le 10^9).OutputPrint one integer: the maximum total fun factor among all permutations of a.ExamplesInput 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 NoteIn the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: Make fun of Boboniu with fun factor 15. Be muzzled. Be muzzled. Make fun of Boboniu with fun factor 10. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48.
5 2 11 8 10 15 23 5
48
1 second
256 megabytes
['dp', 'greedy', 'sortings', 'two pointers', '*1800']
E2. Twilight and Ancient Scroll (harder version)time limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem E with larger constraints.Twilight Sparkle has received a new task from Princess Celestia. This time she asked to decipher the ancient scroll containing important knowledge of pony origin.To hide the crucial information from evil eyes, pony elders cast a spell on the scroll. That spell adds exactly one letter in any place to each word it is cast on. To make the path to the knowledge more tangled elders chose some of words in the scroll and cast a spell on them.Twilight Sparkle knows that the elders admired the order in all things so the scroll original scroll contained words in lexicographically non-decreasing order. She is asked to delete one letter from some of the words of the scroll (to undo the spell) to get some version of the original scroll. Unfortunately, there may be more than one way to recover the ancient scroll. To not let the important knowledge slip by Twilight has to look through all variants of the original scroll and find the required one. To estimate the maximum time Twilight may spend on the work she needs to know the number of variants she has to look through. She asks you to find that number! Since that number can be very big, Twilight asks you to find it modulo 10^9+7.It may occur that princess Celestia has sent a wrong scroll so the answer may not exist.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.InputThe first line contains a single integer n (1 \le n \le 10^5): the number of words in the scroll. The i-th of the next n lines contains a string consisting of lowercase English letters: the i-th word in the scroll. The length of each word is at least one. The sum of lengths of words does not exceed 10^6.OutputPrint one integer: the number of ways to get a version of the original from the scroll modulo 10^9+7.ExamplesInput 3 abcd zaza ataka Output 4Input 4 dfs bfs sms mms Output 8Input 3 abc bcd a Output 0Input 6 lapochka kartyshka bigbabytape morgenshtern ssshhhiiittt queen Output 2028NoteNotice that the elders could have written an empty word (but they surely cast a spell on it so it holds a length 1 now).
3 abcd zaza ataka
4
1.5 seconds
256 megabytes
['dp', 'hashing', 'implementation', 'string suffix structures', 'strings', 'two pointers', '*3200']
E1. Twilight and Ancient Scroll (easier version)time limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem E with smaller constraints.Twilight Sparkle has received a new task from Princess Celestia. This time she asked to decipher the ancient scroll containing important knowledge of pony origin.To hide the crucial information from evil eyes, pony elders cast a spell on the scroll. That spell adds exactly one letter in any place to each word it is cast on. To make the path to the knowledge more tangled elders chose some of words in the scroll and cast a spell on them.Twilight Sparkle knows that the elders admired the order in all things so the scroll original scroll contained words in lexicographically non-decreasing order. She is asked to delete one letter from some of the words of the scroll (to undo the spell) to get some version of the original scroll. Unfortunately, there may be more than one way to recover the ancient scroll. To not let the important knowledge slip by Twilight has to look through all variants of the original scroll and find the required one. To estimate the maximum time Twilight may spend on the work she needs to know the number of variants she has to look through. She asks you to find that number! Since that number can be very big, Twilight asks you to find it modulo 10^9+7.It may occur that princess Celestia has sent a wrong scroll so the answer may not exist.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.InputThe first line contains a single integer n (1 \le n \le 1000): the number of words in the scroll. The i-th of the next n lines contains a string consisting of lowercase English letters: the i-th word in the scroll. The length of each word is more or equal than 1. The sum of lengths of words does not exceed 20000.OutputPrint one integer: the number of ways to get a version of the original from the scroll modulo 10^9+7.ExamplesInput 3 abcd zaza ataka Output 4 Input 4 dfs bfs sms mms Output 8 Input 3 abc bcd a Output 0 Input 6 lapochka kartyshka bigbabytape morgenshtern ssshhhiiittt queen Output 2028 NoteNotice that the elders could have written an empty word (but they surely cast a spell on it so it holds a length 1 now).
3 abcd zaza ataka
4
1.5 seconds
256 megabytes
['dp', 'hashing', 'implementation', 'string suffix structures', 'strings', '*2800']
D. Rarity and New Dresstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCarousel Boutique is busy again! Rarity has decided to visit the pony ball and she surely needs a new dress, because going out in the same dress several times is a sign of bad manners. First of all, she needs a dress pattern, which she is going to cut out from the rectangular piece of the multicolored fabric.The piece of the multicolored fabric consists of n \times m separate square scraps. Since Rarity likes dresses in style, a dress pattern must only include scraps sharing the same color. A dress pattern must be the square, and since Rarity is fond of rhombuses, the sides of a pattern must form a 45^{\circ} angle with sides of a piece of fabric (that way it will be resembling the traditional picture of a rhombus).Examples of proper dress patterns: Examples of improper dress patterns: The first one consists of multi-colored scraps, the second one goes beyond the bounds of the piece of fabric, the third one is not a square with sides forming a 45^{\circ} angle with sides of the piece of fabric.Rarity wonders how many ways to cut out a dress pattern that satisfies all the conditions that do exist. Please help her and satisfy her curiosity so she can continue working on her new masterpiece!InputThe first line contains two integers n and m (1 \le n, m \le 2000). Each of the next n lines contains m characters: lowercase English letters, the j-th of which corresponds to scrap in the current line and in the j-th column. Scraps having the same letter share the same color, scraps having different letters have different colors.OutputPrint a single integer: the number of ways to cut out a dress pattern to satisfy all of Rarity's conditions.ExamplesInput 3 3 aaa aaa aaa Output 10 Input 3 4 abab baba abab Output 12 Input 5 5 zbacg baaac aaaaa eaaad weadd Output 31 NoteIn the first example, all the dress patterns of size 1 and one of size 2 are satisfactory.In the second example, only the dress patterns of size 1 are satisfactory.
3 3 aaa aaa aaa
10
1 second
256 megabytes
['dfs and similar', 'dp', 'implementation', 'shortest paths', '*2100']
C. Pinkie Pie Eats Patty-cakestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!InputThe first line contains a single integer T (1 \le T \le 100): the number of bags for which you need to solve the problem.The first line of each bag description contains a single integer n (2 \le n \le 10^5): the number of patty-cakes in it. The second line of the bag description contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of n over all bags does not exceed 10^5.OutputFor each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.ExampleInput 4 7 1 7 1 6 4 4 6 8 1 1 4 6 4 6 4 7 3 3 3 3 6 2 5 2 3 1 4 Output 3 2 0 4 NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): 1, 6, 4, 7, 1, 6, 4 (in this way, the minimum distance is equal to 3).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): 1, 4, 6, 7, 4, 1, 6, 4 (in this way, the minimum distance is equal to 2).
4 7 1 7 1 6 4 4 6 8 1 1 4 6 4 6 4 7 3 3 3 3 6 2 5 2 3 1 4
3 2 0 4
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', 'sortings', '*1700']
B. Applejack and Storagestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has n planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: + x: the storehouse received a plank with length x - x: one plank with length x was removed from the storehouse (it is guaranteed that the storehouse had some planks with length x). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.InputThe first line contains a single integer n (1 \le n \le 10^5): the initial amount of planks at the company's storehouse, the second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^5): the lengths of the planks.The third line contains a single integer q (1 \le q \le 10^5): the number of events in the company. Each of the next q lines contains a description of the events in a given format: the type of the event (a symbol + or -) is given first, then goes the integer x (1 \le x \le 10^5).OutputAfter every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).ExampleInput 6 1 1 1 2 1 1 6 + 2 + 1 - 1 + 2 - 1 + 2 Output NO YES NO NO NO YES NoteAfter the second event Applejack can build a rectangular storage using planks with lengths 1, 2, 1, 2 and a square storage using planks with lengths 1, 1, 1, 1.After the sixth event Applejack can build a rectangular storage using planks with lengths 2, 2, 2, 2 and a square storage using planks with lengths 1, 1, 1, 1.
6 1 1 1 2 1 1 6 + 2 + 1 - 1 + 2 - 1 + 2
NO YES NO NO NO YES
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', 'implementation', '*1400']
A. Rainbow Dash, Fluttershy and Chess Coloringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with size 1\times1, Rainbow Dash has an infinite amount of light blue blocks, Fluttershy has an infinite amount of yellow blocks. The blocks are placed according to the following rule: each newly placed block must touch the built on the previous turns figure by a side (note that the outline borders of the grid are built initially). At each turn, one pony can place any number of blocks of her color according to the game rules.Rainbow and Fluttershy have found out that they can build patterns on the grid of the game that way. They have decided to start with something simple, so they made up their mind to place the blocks to form a chess coloring. Rainbow Dash is well-known for her speed, so she is interested in the minimum number of turns she and Fluttershy need to do to get a chess coloring, covering the whole grid with blocks. Please help her find that number!Since the ponies can play many times on different boards, Rainbow Dash asks you to find the minimum numbers of turns for several grids of the games.The chess coloring in two colors is the one in which each square is neighbor by side only with squares of different colors.InputThe first line contains a single integer T (1 \le T \le 100): the number of grids of the games. Each of the next T lines contains a single integer n (1 \le n \le 10^9): the size of the side of the grid of the game. OutputFor each grid of the game print the minimum number of turns required to build a chess coloring pattern out of blocks on it.ExampleInput 2 3 4 Output 2 3 NoteFor 3\times3 grid ponies can make two following moves:
2 3 4
2 3
1 second
256 megabytes
['greedy', 'math', '*800']
I. Kevin and Gridtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs Kevin is in BigMan's house, suddenly a trap sends him onto a grid with n rows and m columns.BigMan's trap is configured by two arrays: an array a_1,a_2,\ldots,a_n and an array b_1,b_2,\ldots,b_m.In the i-th row there is a heater which heats the row by a_i degrees, and in the j-th column there is a heater which heats the column by b_j degrees, so that the temperature of cell (i,j) is a_i+b_j.Fortunately, Kevin has a suit with one parameter x and two modes: heat resistance. In this mode suit can stand all temperatures greater or equal to x, but freezes as soon as reaches a cell with temperature less than x. cold resistance. In this mode suit can stand all temperatures less than x, but will burn as soon as reaches a cell with temperature at least x.Once Kevin lands on a cell the suit automatically turns to cold resistance mode if the cell has temperature less than x, or to heat resistance mode otherwise, and cannot change after that.We say that two cells are adjacent if they share an edge.Let a path be a sequence c_1,c_2,\ldots,c_k of cells such that c_i and c_{i+1} are adjacent for 1 \leq i \leq k-1.We say that two cells are connected if there is a path between the two cells consisting only of cells that Kevin can step on.A connected component is a maximal set of pairwise connected cells.We say that a connected component is good if Kevin can escape the grid starting from it  — when it contains at least one border cell of the grid, and that it's bad otherwise.To evaluate the situation, Kevin gives a score of 1 to each good component and a score of 2 for each bad component.The final score will be the difference between the total score of components with temperatures bigger than or equal to x and the score of components with temperatures smaller than x.There are q possible values of x that Kevin can use, and for each of them Kevin wants to know the final score.Help Kevin defeat BigMan!InputThe first line contains three integers n,m,q (1 \leq n,m,q \leq 10^5)  – the number of rows, columns, and the number of possible values for x respectively.The second line contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^5).The third line contains m integers b_1, b_2, \dots, b_m (1 \leq b_i \leq 10^5).Each of the next q lines contains one integer x (1 \leq x \leq 2 \cdot 10^5).OutputOutput q lines, in the i-th line output the answer for the i-th possible value of x from the input.ExamplesInput 5 5 1 1 3 2 3 1 1 3 2 3 1 5 Output -1 Input 3 3 2 1 2 2 2 1 2 3 4 Output 0 1 NoteIn the first example, the score for components with temperature smaller than 5 is 1+2, and the score for components with temperature at least 5 is 2. Thus, the final score is 2-3=-1.
5 5 1 1 3 2 3 1 1 3 2 3 1 5
-1
2 seconds
256 megabytes
['fft', 'graphs', 'math', '*3300']
H. ZS Shuffles Cardstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputzscoder has a deck of n+m custom-made cards, which consists of n cards labelled from 1 to n and m jokers. Since zscoder is lonely, he wants to play a game with himself using those cards. Initially, the deck is shuffled uniformly randomly and placed on the table. zscoder has a set S which is initially empty. Every second, zscoder draws the top card from the deck. If the card has a number x written on it, zscoder removes the card and adds x to the set S. If the card drawn is a joker, zscoder places all the cards back into the deck and reshuffles (uniformly randomly) the n+m cards to form a new deck (hence the new deck now contains all cards from 1 to n and the m jokers). Then, if S currently contains all the elements from 1 to n, the game ends. Shuffling the deck doesn't take time at all. What is the expected number of seconds before the game ends? We can show that the answer can be written in the form \frac{P}{Q} where P, Q are relatively prime integers and Q \neq 0 \bmod 998244353. Output the value of (P \cdot Q^{-1}) modulo 998244353.InputThe only line of the input contains two integers n and m (1 \le n, m \le 2 \cdot 10^{6}).OutputOutput a single integer, the value of (P \cdot Q^{-1}) modulo 998244353.ExamplesInput 2 1 Output 5 Input 3 2 Output 332748127 Input 14 9 Output 969862773 NoteFor the first sample, it can be proven that the expected time before the game ends is 5 seconds.For the second sample, it can be proven that the expected time before the game ends is \frac{28}{3} seconds.
2 1
5
2 seconds
512 megabytes
['combinatorics', 'dp', 'math', 'probabilities', '*3000']
G. Omkar and Piestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOmkar has a pie tray with k (2 \leq k \leq 20) spots. Each spot in the tray contains either a chocolate pie or a pumpkin pie. However, Omkar does not like the way that the pies are currently arranged, and has another ideal arrangement that he would prefer instead.To assist Omkar, n elves have gathered in a line to swap the pies in Omkar's tray. The j-th elf from the left is able to swap the pies at positions a_j and b_j in the tray.In order to get as close to his ideal arrangement as possible, Omkar may choose a contiguous subsegment of the elves and then pass his pie tray through the subsegment starting from the left. However, since the elves have gone to so much effort to gather in a line, they request that Omkar's chosen segment contain at least m (1 \leq m \leq n) elves.Formally, Omkar may choose two integers l and r satisfying 1 \leq l \leq r \leq n and r - l + 1 \geq m so that first the pies in positions a_l and b_l will be swapped, then the pies in positions a_{l + 1} and b_{l + 1} will be swapped, etc. until finally the pies in positions a_r and b_r are swapped.Help Omkar choose a segment of elves such that the amount of positions in Omkar's final arrangement that contain the same type of pie as in his ideal arrangement is the maximum possible. Note that since Omkar has a big imagination, it might be that the amounts of each type of pie in his original arrangement and in his ideal arrangement do not match.InputThe first line contains three integers n, m, and k (1 \leq m \leq n \leq 10^6 and 2 \leq k \leq 20)  — the number of elves, the minimum subsegment length, and the number of spots in Omkar's tray respectively. The second and third lines each contain a string of length k consisting of 0s and 1s that represent initial arrangement of pies and ideal arrangement of pies; the j-th character in each string is equal to 0 if the j-th spot in the arrangement contains a chocolate pie and is equal to 1 if the j-th spot in the arrangement contains a pumpkin pie. It is not guaranteed that the two strings have the same amount of 0s or the same amount of 1s.n lines follow. The j-th of these lines contains two integers a_j and b_j (1 \leq a_j, b_j \leq k, a_j \neq b_j) which indicate that the j-th elf from the left can swap the pies at positions a_j and b_j in the tray.OutputOutput two lines. The first line should contain a single integer s (0 \leq s \leq k) equal to the amount of positions that contain the same type of pie in Omkar's final arrangement and in Omkar's ideal arrangement; s should be the maximum possible. The second line should contain two integers l and r satisfying 1 \leq l \leq r \leq n and r - l + 1 \geq m, indicating that Omkar should pass his tray through the subsegment l, l + 1, \dots, r to achieve a final arrangement with s positions having the same type of pie as his ideal arrangement.If there are multiple answers you may output any of them.ExamplesInput 4 2 5 11000 00011 1 3 3 5 4 2 3 4 Output 5 1 3 Input 4 3 5 11000 00011 1 3 1 5 2 4 1 5 Output 3 1 4 NoteIn the first test case, the swaps will go like this: Swap 1 and 3: 11000 becomes 01100 Swap 3 and 5: 01100 becomes 01001 Swap 4 and 2: 01001 becomes 00011 The final arrangement is the same as the ideal arrangement 00011, so there are 5 positions with the same type of pie, which is optimal.In the second test case, the swaps will go like this: Swap 1 and 3: 11000 becomes 01100 Swap 1 and 5: 01100 becomes 01100 Swap 4 and 2: 01100 becomes 00110 Swap 1 and 5: 00110 becomes 00110 The final arrangement has 3 positions with the same type of pie as the ideal arrangement 00011, those being positions 1, 2, and 4. In this case the subsegment of elves (l, r) = (2, 3) is more optimal, but that subsegment is only length 2 and therefore does not satisfy the constraint that the subsegment be of length at least m = 3.
4 2 5 11000 00011 1 3 3 5 4 2 3 4
5 1 3
2 seconds
256 megabytes
['bitmasks', 'dfs and similar', 'dp', 'math', 'shortest paths', '*2900']
F. Omkar and Landslidetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOmkar is standing at the foot of Celeste mountain. The summit is n meters away from him, and he can see all of the mountains up to the summit, so for all 1 \leq j \leq n he knows that the height of the mountain at the point j meters away from himself is h_j meters. It turns out that for all j satisfying 1 \leq j \leq n - 1, h_j < h_{j + 1} (meaning that heights are strictly increasing).Suddenly, a landslide occurs! While the landslide is occurring, the following occurs: every minute, if h_j + 2 \leq h_{j + 1}, then one square meter of dirt will slide from position j + 1 to position j, so that h_{j + 1} is decreased by 1 and h_j is increased by 1. These changes occur simultaneously, so for example, if h_j + 2 \leq h_{j + 1} and h_{j + 1} + 2 \leq h_{j + 2} for some j, then h_j will be increased by 1, h_{j + 2} will be decreased by 1, and h_{j + 1} will be both increased and decreased by 1, meaning that in effect h_{j + 1} is unchanged during that minute.The landslide ends when there is no j such that h_j + 2 \leq h_{j + 1}. Help Omkar figure out what the values of h_1, \dots, h_n will be after the landslide ends. It can be proven that under the given constraints, the landslide will always end in finitely many minutes.Note that because of the large amount of input, it is recommended that your code uses fast IO.InputThe first line contains a single integer n (1 \leq n \leq 10^6). The second line contains n integers h_1, h_2, \dots, h_n satisfying 0 \leq h_1 < h_2 < \dots < h_n \leq 10^{12} — the heights.OutputOutput n integers, where the j-th integer is the value of h_j after the landslide has stopped.ExampleInput 4 2 6 7 8 Output 5 5 6 7 NoteInitially, the mountain has heights 2, 6, 7, 8.In the first minute, we have 2 + 2 \leq 6, so 2 increases to 3 and 6 decreases to 5, leaving 3, 5, 7, 8.In the second minute, we have 3 + 2 \leq 5 and 5 + 2 \leq 7, so 3 increases to 4, 5 is unchanged, and 7 decreases to 6, leaving 4, 5, 6, 8.In the third minute, we have 6 + 2 \leq 8, so 6 increases to 7 and 8 decreases to 7, leaving 4, 5, 7, 7.In the fourth minute, we have 5 + 2 \leq 7, so 5 increases to 6 and 7 decreases to 6, leaving 4, 6, 6, 7.In the fifth minute, we have 4 + 2 \leq 6, so 4 increases to 5 and 6 decreases to 5, leaving 5, 5, 6, 7.In the sixth minute, nothing else can change so the landslide stops and our answer is 5, 5, 6, 7.
4 2 6 7 8
5 5 6 7
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'data structures', 'greedy', 'math', '*2400']
E. Omkar and Ducktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Omkar has just come across a duck! The duck is walking on a grid with n rows and n columns (2 \leq n \leq 25) so that the grid contains a total of n^2 cells. Let's denote by (x, y) the cell in the x-th row from the top and the y-th column from the left. Right now, the duck is at the cell (1, 1) (the cell in the top left corner) and would like to reach the cell (n, n) (the cell in the bottom right corner) by moving either down 1 cell or to the right 1 cell each second.Since Omkar thinks ducks are fun, he wants to play a game with you based on the movement of the duck. First, for each cell (x, y) in the grid, you will tell Omkar a nonnegative integer a_{x,y} not exceeding 10^{16}, and Omkar will then put a_{x,y} uninteresting problems in the cell (x, y). After that, the duck will start their journey from (1, 1) to (n, n). For each cell (x, y) that the duck crosses during their journey (including the cells (1, 1) and (n, n)), the duck will eat the a_{x,y} uninteresting problems in that cell. Once the duck has completed their journey, Omkar will measure their mass to determine the total number k of uninteresting problems that the duck ate on their journey, and then tell you k.Your challenge, given k, is to exactly reproduce the duck's path, i. e. to tell Omkar precisely which cells the duck crossed on their journey. To be sure of your mastery of this game, Omkar will have the duck complete q different journeys (1 \leq q \leq 10^3). Note that all journeys are independent: at the beginning of each journey, the cell (x, y) will still contain a_{x,y} uninteresting tasks.InteractionThe interaction will begin with a line containing a single integer n (2 \leq n \leq 25), the amount of rows and columns in the grid. Read it.Your program should then print n lines. The x-th line should contain n integers a_{x,1}, a_{x,2}, \dotsc, a_{x,n} satisfying 0 \leq a_{x,y} \leq 10^{16}, where a_{x,y} is the amount of uninteresting problems Omkar should place in the cell (x, y).After that, you will first receive a single integer q, the amount of journeys that the duck will take. q queries will follow; each query will consist of a single line containing an integer k, the amount of uninteresting problems that the duck ate on that journey. After each query, given that you have determined that the duck visited the cells (x_1, y_1), (x_2, y_2), \dotsc, (x_{2n - 1}, y_{2n - 1}) in that order (it should always be true that (x_1, y_1) = (1, 1) and (x_{2n - 1}, y_{2n - 1}) = (n, n)), you should output 2n - 1 lines so that the j-th line contains the two integers x_j, y_j.Bear in mind that if the sum on your path is k, but your path is different from the actual hidden path, then your solution is still wrong!After printing each line do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack FormatTo hack, first output a line containing n and another line containing q. It must be true that 2 \leq n \leq 25 and 1 \leq q \leq 1000. Then, output the q journeys taken by the duck in the same format as described above: for each journey, given that the duck visited the cells (x_1, y_1), (x_2, y_2), \dotsc, (x_{2n - 1}, y_{2n - 1}) in that order, you should output 2n - 1 lines so that the j-th line contains the two integers x_j, y_j. It must be true that (x_1, y_1) = (1, 1) and (x_{2n - 1}, y_{2n - 1}) = (n, n). Additionally, for each j such that 2 \leq j \leq 2n - 1, it must be true that 1 \leq x_j, y_j \leq n and either (x_j, y_j) = (x_{j - 1} + 1, y_{j - 1}) or (x_j, y_j) = (x_{j - 1}, y_{j - 1} + 1).ExampleInput 4 3 23 26 27 Output 1 2 3 6 4 6 2 10 9 0 7 3 2 8 8 2 1 1 1 2 1 3 2 3 2 4 3 4 4 4 1 1 2 1 3 1 3 2 3 3 3 4 4 4 1 1 1 2 1 3 1 4 2 4 3 4 4 4 NoteThe duck's three journeys are illustrated below.1 + 2 + 3 + 2 + 10 + 3 + 2 = 23 1 + 4 + 9 + 0 + 7 + 3 + 2 = 26 1 + 2 + 3 + 6 + 10 + 3 + 2 = 27
4 3 23 26 27
1 2 3 6 4 6 2 10 9 0 7 3 2 8 8 2 1 1 1 2 1 3 2 3 2 4 3 4 4 4 1 1 2 1 3 1 3 2 3 3 3 4 4 4 1 1 1 2 1 3 1 4 2 4 3 4 4 4
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'interactive', 'math', '*2100']
D. Omkar and Bed Warstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOmkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are n players arranged in a circle, so that for all j such that 2 \leq j \leq n, player j - 1 is to the left of the player j, and player j is to the right of player j - 1. Additionally, player n is to the left of player 1, and player 1 is to the right of player n.Currently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either 0, 1, or 2 other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly 1 other player, then they should logically attack that player in response. If instead a player is being attacked by 0 or 2 other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players.Unfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the n players in the game to make them instead attack another player  — i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left. Omkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The descriptions of the test cases follows.The first line of each test case contains one integer n (3 \leq n \leq 2 \cdot 10^5)  — the amount of players (and therefore beds) in this game of Bed Wars.The second line of each test case contains a string s of length n. The j-th character of s is equal to L if the j-th player is attacking the player to their left, and R if the j-th player is attacking the player to their right.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output one integer: the minimum number of players Omkar needs to talk to to make it so that all players are acting logically according to Bed Wars strategy.It can be proven that it is always possible for Omkar to achieve this under the given constraints.ExampleInput 5 4 RLRL 6 LRRRRL 8 RLLRRRLL 12 LLLLRRLRRRLL 5 RRRRR Output 0 1 1 3 2 NoteIn the first test case, players 1 and 2 are attacking each other, and players 3 and 4 are attacking each other. Each player is being attacked by exactly 1 other player, and each player is attacking the player that is attacking them, so all players are already being logical according to Bed Wars strategy and Omkar does not need to talk to any of them, making the answer 0.In the second test case, not every player acts logically: for example, player 3 is attacked only by player 2, but doesn't attack him in response. Omkar can talk to player 3 to convert the attack arrangement to LRLRRL, in which you can see that all players are being logical according to Bed Wars strategy, making the answer 1.
5 4 RLRL 6 LRRRRL 8 RLLRRRLL 12 LLLLRRLRRRLL 5 RRRRR
0 1 1 3 2
2 seconds
256 megabytes
['dp', 'greedy', '*1700']
C. Omkar and Waterslidetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOmkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.Omkar currently has n supports arranged in a line, the i-th of which has height a_i. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In 1 operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add 1 to each of their heights. Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!An array b is a subsegment of an array c if b can be obtained from c by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.An array b_1, b_2, \dots, b_n is called nondecreasing if b_i\le b_{i+1} for every i from 1 to n-1.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 100). Description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 2 \cdot 10^5) — the number of supports Omkar has.The second line of each test case contains n integers a_{1},a_{2},...,a_{n} (0 \leq a_{i} \leq 10^9) — the heights of the supports.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the minimum number of operations Omkar needs to perform to make his supports able to support his waterslide.ExampleInput 3 4 5 3 2 5 5 1 2 3 5 3 3 1 1 1 Output 3 2 0 NoteThe subarray with which Omkar performs the operation is bolded.In the first test case:First operation:[5, 3, \textbf{2}, 5] \to [5, 3, \textbf{3}, 5]Second operation:[5, \textbf{3}, \textbf{3}, 5] \to [5, \textbf{4}, \textbf{4}, 5]Third operation:[5, \textbf{4}, \textbf{4}, 5] \to [5, \textbf{5}, \textbf{5}, 5]In the third test case, the array is already nondecreasing, so Omkar does 0 operations.
3 4 5 3 2 5 5 1 2 3 5 3 3 1 1 1
3 2 0
2 seconds
256 megabytes
['greedy', 'implementation', '*1200']
B. Omkar and Infinity Clocktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k operations with this array.Define one operation as the following: Set d to be the maximum value of your array. For every i from 1 to n, replace a_{i} with d-a_{i}. The goal is to predict the contents in the array after k operations. Please help Ray determine what the final sequence will look like!InputEach test contains multiple test cases. The first line contains the number of cases t (1 \le t \le 100). Description of the test cases follows.The first line of each test case contains two integers n and k (1 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 10^{18}) – the length of your array and the number of operations to perform.The second line of each test case contains n integers a_{1},a_{2},...,a_{n} (-10^9 \leq a_{i} \leq 10^9) – the initial contents of your array.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each case, print the final version of array a after k operations described above.ExampleInput 3 2 1 -199 192 5 19 5 -1 4 2 0 1 2 69 Output 391 0 0 6 1 3 5 0 NoteIn the first test case the array changes as follows:Initially, the array is [-199, 192]. d = 192.After the operation, the array becomes [d-(-199), d-192] = [391, 0].
3 2 1 -199 192 5 19 5 -1 4 2 0 1 2 69
391 0 0 6 1 3 5 0
2 seconds
256 megabytes
['implementation', 'math', '*800']
A. Omkar and Passwordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them with their sum. Formally, choose an index i such that 1 \leq i < n and a_{i} \neq a_{i+1}, delete both a_i and a_{i+1} from the array and put a_{i}+a_{i+1} in their place. For example, for array [7, 4, 3, 7] you can choose i = 2 and the array will become [7, 4+3, 7] = [7, 7, 7]. Note that in this array you can't apply this operation anymore.Notice that one operation will decrease the size of the password by 1. What is the shortest possible length of the password after some number (possibly 0) of operations?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the password.The second line of each test case contains n integers a_{1},a_{2},\dots,a_{n} (1 \leq a_{i} \leq 10^9) — the initial contents of your password.The sum of n over all test cases will not exceed 2 \cdot 10^5.OutputFor each password, print one integer: the shortest possible length of the password after some number of operations.ExampleInput 2 4 2 1 3 1 2 420 420 Output 1 2 NoteIn the first test case, you can do the following to achieve a length of 1:Pick i=2 to get [2, 4, 1]Pick i=1 to get [6, 1]Pick i=1 to get [7]In the second test case, you can't perform any operations because there is no valid i that satisfies the requirements mentioned above.
2 4 2 1 3 1 2 420 420
1 2
2 seconds
256 megabytes
['greedy', 'math', '*800']
E. Pairs of Pairstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a simple and connected undirected graph consisting of n nodes and m edges.Consider any way to pair some subset of these n nodes such that no node is present in more than one pair. This pairing is valid if for every pair of pairs, the induced subgraph containing all 4 nodes, two from each pair, has at most 2 edges (out of the 6 possible edges). More formally, for any two pairs, (a,b) and (c,d), the induced subgraph with nodes \{a,b,c,d\} should have at most 2 edges. Please note that the subgraph induced by a set of nodes contains nodes only from this set and edges which have both of its end points in this set.Now, do one of the following: Find a simple path consisting of at least \lceil \frac{n}{2} \rceil nodes. Here, a path is called simple if it does not visit any node multiple times. Find a valid pairing in which at least \lceil \frac{n}{2} \rceil nodes are paired. It can be shown that it is possible to find at least one of the two in every graph satisfying constraints from the statement. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). Description of the test cases follows.The first line of each test case contains 2 integers n, m (2 \le n \le 5\cdot 10^5, 1 \le m \le 10^6), denoting the number of nodes and edges, respectively. The next m lines each contain 2 integers u and v (1 \le u, v \le n, u \neq v), denoting that there is an undirected edge between nodes u and v in the given graph.It is guaranteed that the given graph is connected, and simple  — it does not contain multiple edges between the same pair of nodes, nor does it have any self-loops. It is guaranteed that the sum of n over all test cases does not exceed 5\cdot 10^5.It is guaranteed that the sum of m over all test cases does not exceed 10^6.OutputFor each test case, the output format is as follows. If you have found a pairing, in the first line output "PAIRING" (without quotes). Then, output k (\lceil \frac{n}{2} \rceil \le 2\cdot k \le n), the number of pairs in your pairing. Then, in each of the next k lines, output 2 integers a and b  — denoting that a and b are paired with each other. Note that the graph does not have to have an edge between a and b! This pairing has to be valid, and every node has to be a part of at most 1 pair. Otherwise, in the first line output "PATH" (without quotes). Then, output k (\lceil \frac{n}{2} \rceil \le k \le n), the number of nodes in your path. Then, in the second line, output k integers, v_1, v_2, \ldots, v_k, in the order in which they appear on the path. Formally, v_i and v_{i+1} should have an edge between them for every i (1 \le i < k). This path has to be simple, meaning no node should appear more than once. ExampleInput 4 6 5 1 4 2 5 3 6 1 5 3 5 6 5 1 4 2 5 3 6 1 5 3 5 12 14 1 2 2 3 3 4 4 1 1 5 1 12 2 6 2 7 3 8 3 9 4 10 4 11 2 4 1 3 12 14 1 2 2 3 3 4 4 1 1 5 1 12 2 6 2 7 3 8 3 9 4 10 4 11 2 4 1 3 Output PATH 4 1 5 3 6 PAIRING 2 1 6 2 4 PAIRING 3 1 8 2 5 4 10 PAIRING 4 1 7 2 9 3 11 4 5 NoteThe path outputted in the first case is the following. The pairing outputted in the second case is the following. Here is an invalid pairing for the same graph  — the subgraph \{1,3,4,5\} has 3 edges. Here is the pairing outputted in the third case. It's valid because — The subgraph \{1,8,2,5\} has edges (1,2) and (1,5). The subgraph \{1,8,4,10\} has edges (1,4) and (4,10). The subgraph \{4,10,2,5\} has edges (2,4) and (4,10). Here is the pairing outputted in the fourth case.
4 6 5 1 4 2 5 3 6 1 5 3 5 6 5 1 4 2 5 3 6 1 5 3 5 12 14 1 2 2 3 3 4 4 1 1 5 1 12 2 6 2 7 3 8 3 9 4 10 4 11 2 4 1 3 12 14 1 2 2 3 3 4 4 1 1 5 1 12 2 6 2 7 3 8 3 9 4 10 4 11 2 4 1 3
PATH 4 1 5 3 6 PAIRING 2 1 6 2 4 PAIRING 3 1 8 2 5 4 10 PAIRING 4 1 7 2 9 3 11 4 5
3 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'greedy', 'trees', '*2600']
D. 505time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA binary matrix is called good if every even length square sub-matrix has an odd number of ones. Given a binary matrix a consisting of n rows and m columns, determine the minimum number of cells you need to change to make it good, or report that there is no way to make it good at all. All the terms above have their usual meanings — refer to the Notes section for their formal definitions. InputThe first line of input contains two integers n and m (1 \leq n \leq m \leq 10^6 and n\cdot m \leq 10^6)  — the number of rows and columns in a, respectively. The following n lines each contain m characters, each of which is one of 0 and 1. If the j-th character on the i-th line is 1, then a_{i,j} = 1. Similarly, if the j-th character on the i-th line is 0, then a_{i,j} = 0.OutputOutput the minimum number of cells you need to change to make a good, or output -1 if it's not possible at all.ExamplesInput 3 3 101 001 110 Output 2Input 7 15 000100001010010 100111010110001 101101111100100 010000111111010 111010010100001 000011001111101 111111011010011 Output -1NoteIn the first case, changing a_{1,1} to 0 and a_{2,2} to 1 is enough. You can verify that there is no way to make the matrix in the second case good. Some definitions — A binary matrix is one in which every element is either 1 or 0. A sub-matrix is described by 4 parameters — r_1, r_2, c_1, and c_2; here, 1 \leq r_1 \leq r_2 \leq n and 1 \leq c_1 \leq c_2 \leq m. This sub-matrix contains all elements a_{i,j} that satisfy both r_1 \leq i \leq r_2 and c_1 \leq j \leq c_2. A sub-matrix is, further, called an even length square if r_2-r_1 = c_2-c_1 and r_2-r_1+1 is divisible by 2.
3 3 101 001 110
2
1 second
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'dp', 'greedy', 'implementation', '*2000']
C. Cyclic Permutations time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).Consider a permutation p of length n, we build a graph of size n using it as follows: For every 1 \leq i \leq n, find the largest j such that 1 \leq j < i and p_j > p_i, and add an undirected edge between node i and node j For every 1 \leq i \leq n, find the smallest j such that i < j \leq n and p_j > p_i, and add an undirected edge between node i and node j In cases where no such j exists, we make no edges. Also, note that we make edges between the corresponding indices, not the values at those indices.For clarity, consider as an example n = 4, and p = [3,1,4,2]; here, the edges of the graph are (1,3),(2,1),(2,3),(4,3).A permutation p is cyclic if the graph built using p has at least one simple cycle. Given n, find the number of cyclic permutations of length n. Since the number may be very large, output it modulo 10^9+7.Please refer to the Notes section for the formal definition of a simple cycleInputThe first and only line contains a single integer n (3 \le n \le 10^6).OutputOutput a single integer 0 \leq x < 10^9+7, the number of cyclic permutations of length n modulo 10^9+7.ExamplesInput 4 Output 16Input 583291 Output 135712853NoteThere are 16 cyclic permutations for n = 4. [4,2,1,3] is one such permutation, having a cycle of length four: 4 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 4.Nodes v_1, v_2, \ldots, v_k form a simple cycle if the following conditions hold: k \geq 3. v_i \neq v_j for any pair of indices i and j. (1 \leq i < j \leq k) v_i and v_{i+1} share an edge for all i (1 \leq i < k), and v_1 and v_k share an edge.
4
16
1 second
256 megabytes
['combinatorics', 'dp', 'graphs', 'math', '*1500']
B. Fix Youtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a conveyor belt represented using a grid consisting of n rows and m columns. The cell in the i-th row from the top and the j-th column from the left is labelled (i,j). Every cell, except (n,m), has a direction R (Right) or D (Down) assigned to it. If the cell (i,j) is assigned direction R, any luggage kept on that will move to the cell (i,j+1). Similarly, if the cell (i,j) is assigned direction D, any luggage kept on that will move to the cell (i+1,j). If at any moment, the luggage moves out of the grid, it is considered to be lost. There is a counter at the cell (n,m) from where all luggage is picked. A conveyor belt is called functional if and only if any luggage reaches the counter regardless of which cell it is placed in initially. More formally, for every cell (i,j), any luggage placed in this cell should eventually end up in the cell (n,m). This may not hold initially; you are, however, allowed to change the directions of some cells to make the conveyor belt functional. Please determine the minimum amount of cells you have to change.Please note that it is always possible to make any conveyor belt functional by changing the directions of some set of cells.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10). Description of the test cases follows.The first line of each test case contains two integers n, m (1 \le n \le 100, 1 \le m \le 100)  — the number of rows and columns, respectively.The following n lines each contain m characters. The j-th character in the i-th line, a_{i,j} is the initial direction of the cell (i, j). Please note that a_{n,m}= C.OutputFor each case, output in a new line the minimum number of cells that you have to change to make the conveyor belt functional. ExampleInput 4 3 3 RRD DDR RRC 1 4 DDDC 6 9 RDDDDDRRR RRDDRRDDD RRDRDRRDR DDDDRDDRR DRRDRDDDR DDRDRRDDC 1 1 C Output 1 3 9 0 NoteIn the first case, just changing the direction of (2,3) to D is enough.You can verify that the resulting belt is functional. For example, if we place any luggage at (2,2), it first moves to (3,2) and then to (3,3). In the second case, we have no option but to change the first 3 cells from D to R making the grid equal to RRRC.
4 3 3 RRD DDR RRC 1 4 DDDC 6 9 RDDDDDRRR RRDDRRDDD RRDRDRRDR DDDDRDDRR DRRDRDDDR DDRDRRDDC 1 1 C
1 3 9 0
1 second
256 megabytes
['brute force', 'greedy', 'implementation', '*800']
A. Suborraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).For a positive integer n, we call a permutation p of length n good if the following condition holds for every pair i and j (1 \le i \le j \le n) — (p_i \text{ OR } p_{i+1} \text{ OR } \ldots \text{ OR } p_{j-1} \text{ OR } p_{j}) \ge j-i+1, where \text{OR} denotes the bitwise OR operation. In other words, a permutation p is good if for every subarray of p, the \text{OR} of all elements in it is not less than the number of elements in that subarray. Given a positive integer n, output any good permutation of length n. We can show that for the given constraints such a permutation always exists.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first and only line of every test case contains a single integer n (1 \le n \le 100).OutputFor every test, output any good permutation of length n on a separate line. ExampleInput 3 1 3 7 Output 1 3 1 2 4 3 5 2 7 1 6 NoteFor n = 3, [3,1,2] is a good permutation. Some of the subarrays are listed below. 3\text{ OR }1 = 3 \geq 2 (i = 1,j = 2) 3\text{ OR }1\text{ OR }2 = 3 \geq 3 (i = 1,j = 3) 1\text{ OR }2 = 3 \geq 2 (i = 2,j = 3) 1 \geq 1 (i = 2,j = 2) Similarly, you can verify that [4,3,5,2,7,1,6] is also good.
3 1 3 7
1 3 1 2 4 3 5 2 7 1 6
1 second
256 megabytes
['constructive algorithms', 'math', '*800']
G. Directing Edgestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an undirected connected graph consisting of n vertices and m edges. k vertices of this graph are special.You have to direct each edge of this graph or leave it undirected. If you leave the i-th edge undirected, you pay w_i coins, and if you direct it, you don't have to pay for it.Let's call a vertex saturated if it is reachable from each special vertex along the edges of the graph (if an edge is undirected, it can be traversed in both directions). After you direct the edges of the graph (possibly leaving some of them undirected), you receive c_i coins for each saturated vertex i. Thus, your total profit can be calculated as \sum \limits_{i \in S} c_i - \sum \limits_{j \in U} w_j, where S is the set of saturated vertices, and U is the set of edges you leave undirected.For each vertex i, calculate the maximum possible profit you can get if you have to make the vertex i saturated.InputThe first line contains three integers n, m and k (2 \le n \le 3 \cdot 10^5, n - 1 \le m \le \min(3 \cdot 10^5, \frac{n(n-1)}{2}), 1 \le k \le n).The second line contains k pairwise distinct integers v_1, v_2, ..., v_k (1 \le v_i \le n) — the indices of the special vertices.The third line contains n integers c_1, c_2, ..., c_n (0 \le c_i \le 10^9).The fourth line contains m integers w_1, w_2, ..., w_m (0 \le w_i \le 10^9).Then m lines follow, the i-th line contains two integers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i) — the endpoints of the i-th edge.There is at most one edge between each pair of vertices.OutputPrint n integers, where the i-th integer is the maximum profit you can get if you have to make the vertex i saturated.ExamplesInput 3 2 2 1 3 11 1 5 10 10 1 2 2 3 Output 11 2 5 Input 4 4 4 1 2 3 4 1 5 7 8 100 100 100 100 1 2 2 3 3 4 1 4 Output 21 21 21 21 NoteConsider the first example: the best way to make vertex 1 saturated is to direct the edges as 2 \to 1, 3 \to 2; 1 is the only saturated vertex, so the answer is 11; the best way to make vertex 2 saturated is to leave the edge 1-2 undirected and direct the other edge as 3 \to 2; 1 and 2 are the saturated vertices, and the cost to leave the edge 1-2 undirected is 10, so the answer is 2; the best way to make vertex 3 saturated is to direct the edges as 2 \to 3, 1 \to 2; 3 is the only saturated vertex, so the answer is 5. The best course of action in the second example is to direct the edges along the cycle: 1 \to 2, 2 \to 3, 3 \to 4 and 4 \to 1. That way, all vertices are saturated.
3 2 2 1 3 11 1 5 10 10 1 2 2 3
11 2 5
4 seconds
512 megabytes
['dfs and similar', 'dp', 'graphs', 'trees', '*2800']
F. Bicolored Segmentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n segments [l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]. Each segment has one of two colors: the i-th segment's color is t_i.Let's call a pair of segments i and j bad if the following two conditions are met: t_i \ne t_j; the segments [l_i, r_i] and [l_j, r_j] intersect, embed or touch, i. e. there exists an integer x such that x \in [l_i, r_i] and x \in [l_j, r_j]. Calculate the maximum number of segments that can be selected from the given ones, so that there is no bad pair among the selected ones.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — number of segments.The next n lines contains three integers l_i, r_i, t_i (1 \le l_i \le r_i \le 10^9; t_i \in \{1, 2\}) — description of the i-th segment.OutputPrint the maximum number of segments that can be selected, so that there is no bad pair among the selected segments.ExamplesInput 3 1 3 1 4 6 2 2 5 1 Output 2 Input 5 5 8 1 1 3 2 3 4 2 6 6 1 2 10 2 Output 4 Input 7 19 20 1 13 15 2 6 11 2 4 10 1 14 17 1 13 13 2 5 9 1 Output 5
3 1 3 1 4 6 2 2 5 1
2
2 seconds
256 megabytes
['data structures', 'dp', 'graph matchings', 'sortings', '*2600']
E. Calendar Ambiguitytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland year consists of m months with d days each. Months are numbered from 1 to m. Berland week consists of w days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than w days.A pair (x, y) such that x < y is ambiguous if day x of month y is the same day of the week as day y of month x.Count the number of ambiguous pairs.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Each of the next t lines contains three integers m, d and w (1 \le m, d, w \le 10^9) — the number of months in a year, the number of days in a month and the number of days in a week.OutputPrint t integers — for each testcase output the number of pairs (x, y) such that x < y and day x of month y is the same day of the week as day y of month x.ExampleInput 5 6 7 4 10 7 12 12 30 7 1 1 1 3247834 10298779 625324 Output 6 9 5 0 116461800 NoteHere are the pairs for the first test case:
5 6 7 4 10 7 12 12 30 7 1 1 1 3247834 10298779 625324
6 9 5 0 116461800
2 seconds
256 megabytes
['math', 'number theory', '*2200']
D. Segment Intersectionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two lists of segments [al_1, ar_1], [al_2, ar_2], \dots, [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], \dots, [bl_n, br_n].Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].In one step, you can choose one segment (either from the first or from the second list) and extend it by 1. In other words, suppose you've chosen segment [x, y] then you can transform it either into [x - 1, y] or into [x, y + 1].Let's define a total intersection I as the sum of lengths of intersections of the corresponding pairs of segments, i.e. \sum\limits_{i=1}^{n}{\text{intersection_length}([al_i, ar_i], [bl_i, br_i])}. Empty intersection has length 0 and length of a segment [x, y] is equal to y - x.What is the minimum number of steps you need to make I greater or equal to k?InputThe first line contains the single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains two integers n and k (1 \le n \le 2 \cdot 10^5; 1 \le k \le 10^9) — the length of lists and the minimum required total intersection.The second line of each test case contains two integers l_1 and r_1 (1 \le l_1 \le r_1 \le 10^9) — the segment all [al_i, ar_i] are equal to initially.The third line of each test case contains two integers l_2 and r_2 (1 \le l_2 \le r_2 \le 10^9) — the segment all [bl_i, br_i] are equal to initially.It's guaranteed that the sum of n doesn't exceed 2 \cdot 10^5.OutputPrint t integers — one per test case. For each test case, print the minimum number of step you need to make I greater or equal to k.ExampleInput 3 3 5 1 2 3 4 2 1000000000 1 1 999999999 999999999 10 3 5 10 7 8 Output 7 2000000000 0 NoteIn the first test case, we can achieve total intersection 5, for example, using next strategy: make [al_1, ar_1] from [1, 2] to [1, 4] in 2 steps; make [al_2, ar_2] from [1, 2] to [1, 3] in 1 step; make [bl_1, br_1] from [3, 4] to [1, 4] in 2 steps; make [bl_2, br_2] from [3, 4] to [1, 4] in 2 steps. In result, I = \text{intersection_length}([al_1, ar_1], [bl_1, br_1]) + \text{intersection_length}([al_2, ar_2], [bl_2, br_2]) + \\ + \text{intersection_length}([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5In the second test case, we can make [al_1, ar_1] = [0, 1000000000] in 1000000000 steps and [bl_1, br_1] = [0, 1000000000] in 1000000000 steps.In the third test case, the total intersection I is already equal to 10 > 3, so we don't need to do any steps.
3 3 5 1 2 3 4 2 1000000000 1 1 999999999 999999999 10 3 5 10 7 8
7 2000000000 0
2 seconds
256 megabytes
['brute force', 'greedy', 'implementation', 'math', '*2100']
C. Good Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call left cyclic shift of some string t_1 t_2 t_3 \dots t_{n - 1} t_n as string t_2 t_3 \dots t_{n - 1} t_n t_1.Analogically, let's call right cyclic shift of string t as string t_n t_1 t_2 t_3 \dots t_{n - 1}.Let's say string t is good if its left cyclic shift is equal to its right cyclic shift.You are given string s which consists of digits 0–9.What is the minimum number of characters you need to erase from s to make it good?InputThe first line contains single integer t (1 \le t \le 1000) — the number of test cases.Next t lines contains test cases — one per line. The first and only line of each test case contains string s (2 \le |s| \le 2 \cdot 10^5). Each character s_i is digit 0–9.It's guaranteed that the total length of strings doesn't exceed 2 \cdot 10^5.OutputFor each test case, print the minimum number of characters you need to erase from s to make it good.ExampleInput 3 95831 100120013 252525252525 Output 3 5 0 NoteIn the first test case, you can erase any 3 characters, for example, the 1-st, the 3-rd, and the 4-th. You'll get string 51 and it is good.In the second test case, we can erase all characters except 0: the remaining string is 0000 and it's good.In the third test case, the given string s is already good.
3 95831 100120013 252525252525
3 5 0
2 seconds
256 megabytes
['brute force', 'dp', 'greedy', 'two pointers', '*1500']
B. Array Walktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots, a_n, consisting of n positive integers. Initially you are standing at index 1 and have a score equal to a_1. You can perform two kinds of moves: move right — go from your current index x to x+1 and add a_{x+1} to your score. This move can only be performed if x<n. move left — go from your current index x to x-1 and add a_{x-1} to your score. This move can only be performed if x>1. Also, you can't perform two or more moves to the left in a row. You want to perform exactly k moves. Also, there should be no more than z moves to the left among them.What is the maximum score you can achieve?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains three integers n, k and z (2 \le n \le 10^5, 1 \le k \le n - 1, 0 \le z \le min(5, k)) — the number of elements in the array, the total number of moves you should perform and the maximum number of moves to the left you can perform.The second line of each testcase contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^4) — the given array.The sum of n over all testcases does not exceed 3 \cdot 10^5.OutputPrint t integers — for each testcase output the maximum score you can achieve if you make exactly k moves in total, no more than z of them are to the left and there are no two or more moves to the left in a row.ExampleInput 4 5 4 0 1 5 4 3 2 5 4 1 1 5 4 3 2 5 4 4 10 20 30 40 50 10 7 3 4 6 8 2 9 9 7 4 10 9 Output 15 19 150 56 NoteIn the first testcase you are not allowed to move left at all. So you make four moves to the right and obtain the score a_1 + a_2 + a_3 + a_4 + a_5.In the second example you can move one time to the left. So we can follow these moves: right, right, left, right. The score will be a_1 + a_2 + a_3 + a_2 + a_3.In the third example you can move four times to the left but it's not optimal anyway, you can just move four times to the right and obtain the score a_1 + a_2 + a_3 + a_4 + a_5.
4 5 4 0 1 5 4 3 2 5 4 1 1 5 4 3 2 5 4 4 10 20 30 40 50 10 7 3 4 6 8 2 9 9 7 4 10 9
15 19 150 56
2 seconds
256 megabytes
['brute force', 'dp', 'greedy', '*1600']
A. LCM Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.You are given two integers l and r. Find two integers x and y such that l \le x < y \le r and l \le LCM(x, y) \le r.InputThe first line contains one integer t (1 \le t \le 10000) — the number of test cases.Each test case is represented by one line containing two integers l and r (1 \le l < r \le 10^9).OutputFor each test case, print two integers: if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1; otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them). ExampleInput 4 1 1337 13 69 2 4 88 89 Output 6 7 14 21 2 4 -1 -1
4 1 1337 13 69 2 4 88 89
6 7 14 21 2 4 -1 -1
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', 'number theory', '*800']
E. Uncle Bogdan and Projectionstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAfter returning to shore, uncle Bogdan usually visits the computer club "The Rock", to solve tasks in a pleasant company. One day, uncle Bogdan met his good old friend who told him one unusual task...There are n non-intersecting horizontal segments with ends in integers points on the plane with the standard cartesian coordinate system. All segments are strictly above the OX axis. You can choose an arbitrary vector (a, b), where b < 0 and coordinates are real numbers, and project all segments to OX axis along this vector. The projections shouldn't intersect but may touch each other.Find the minimum possible difference between x coordinate of the right end of the rightmost projection and x coordinate of the left end of the leftmost projection.InputThe first line contains the single integer n (1 \le n \le 2000) — the number of segments.The i-th of the next n lines contains three integers xl_i, xr_i and y_i (-10^6 \le xl_i < xr_i \le 10^6; 1 \le y_i \le 10^6) — coordinates of the corresponding segment.It's guaranteed that the segments don't intersect or touch.OutputPrint the minimum possible difference you can get.Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.Formally, if your answer is a and jury's answer is b then your answer will be considered correct if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}.ExamplesInput 3 1 6 2 4 6 4 4 6 6 Output 9.000000000 Input 3 2 5 1 4 6 4 7 8 2 Output 6.333333333 Input 2 1 3 1 4 7 1 Output 6.000000000 NoteIn the first example if we project segments along the vector (1, -1) then we get an answer 12-3=9 and (it can be proven) it is impossible to get less. It is optimal to project along the vector (1, -3) in the second example. The answer is 8\frac{2}{3}-2\frac{1}{3}=6\frac{1}{3}
3 1 6 2 4 6 4 4 6 6
9.000000000
4 seconds
512 megabytes
['data structures', 'geometry', 'sortings', '*2700']
D. Captain Flint and Treasuretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCaptain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined: Choose position i (1 \le i \le n); Add a_i to ans; If b_i \neq -1 then add a_i to a_{b_i}. What is the maximum ans you can get by performing the operation on each i (1 \le i \le n) exactly once?Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.InputThe first line contains the integer n (1 \le n \le 2 \cdot 10^5) — the length of arrays a and b.The second line contains n integers a_1, a_2, \ldots, a_n (−10^6 \le a_i \le 10^6).The third line contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le n or b_i = -1).Additional constraint: it's guaranteed that for any i (1 \le i \le n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, \ldots is not cyclic, in other words it will always end with -1.OutputIn the first line, print the maximum ans you can get.In the second line, print the order of operations: n different integers p_1, p_2, \ldots, p_n (1 \le p_i \le n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.ExamplesInput 3 1 2 3 2 3 -1 Output 10 1 2 3 Input 2 -1 100 2 -1 Output 99 2 1 Input 10 -10 -1 2 2 5 -2 -3 -4 2 -6 -1 -1 2 2 -1 5 5 7 7 9 Output -9 3 5 6 1 9 4 10 7 8 2
3 1 2 3 2 3 -1
10 1 2 3
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'graphs', 'greedy', 'implementation', 'trees', '*2000']
C. Uncle Bogdan and Country Happinesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputUncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are n cities and n−1 undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from 1 to n and the city 1 is a capital. In other words, the country has a tree structure.There are m citizens living in the country. A p_i people live in the i-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the i-th city calculates a happiness index h_i as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city i the happiness index will be equal exactly to h_i".InputThe first line contains a single integer t (1 \le t \le 10000) — the number of test cases.The first line of each test case contains two integers n and m (1 \le n \le 10^5; 0 \le m \le 10^9) — the number of cities and citizens.The second line of each test case contains n integers p_1, p_2, \ldots, p_{n} (0 \le p_i \le m; p_1 + p_2 + \ldots + p_{n} = m), where p_i is the number of people living in the i-th city.The third line contains n integers h_1, h_2, \ldots, h_{n} (-10^9 \le h_i \le 10^9), where h_i is the calculated happiness index of the i-th city.Next n − 1 lines contain description of the roads, one per line. Each line contains two integers x_i and y_i (1 \le x_i, y_i \le n; x_i \neq y_i), where x_i and y_i are cities connected by the i-th road.It's guaranteed that the sum of n from all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print YES, if the collected data is correct, or NO — otherwise. You can print characters in YES or NO in any case.ExamplesInput 2 7 4 1 0 1 1 0 1 0 4 0 0 -1 0 -1 0 1 2 1 3 1 4 3 5 3 6 3 7 5 11 1 2 5 2 1 -11 -2 -6 -2 -1 1 2 1 3 1 4 3 5 Output YES YES Input 2 4 4 1 1 1 1 4 1 -3 -1 1 2 1 3 1 4 3 13 3 3 7 13 1 4 1 2 1 3 Output NO NO NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city 1: he lives in the capital and is in good mood; a person from city 4: he visited cities 1 and 4, his mood was ruined between cities 1 and 4; a person from city 3: he visited cities 1 and 3 in good mood; a person from city 6: he visited cities 1, 3 and 6, his mood was ruined between cities 1 and 3; In total, h_1 = 4 - 0 = 4, h_2 = 0, h_3 = 1 - 1 = 0, h_4 = 0 - 1 = -1, h_5 = 0, h_6 = 0 - 1 = -1, h_7 = 0. The second case of the first test: All people have already started in bad mood in the capital — this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
2 7 4 1 0 1 1 0 1 0 4 0 0 -1 0 -1 0 1 2 1 3 1 4 3 5 3 6 3 7 5 11 1 2 5 2 1 -11 -2 -6 -2 -1 1 2 1 3 1 4 3 5
YES YES
2 seconds
256 megabytes
['dfs and similar', 'greedy', 'math', 'trees', '*1800']
B. Captain Flint and a Long Voyagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCaptain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.In the beginning, uncle Bogdan wrote on a board a positive integer x consisting of n digits. After that, he wiped out x and wrote integer k instead, which was the concatenation of binary representations of digits x consists of (without leading zeroes). For example, let x = 729, then k = 111101001 (since 7 = 111, 2 = 10, 9 = 1001).After some time, uncle Bogdan understood that he doesn't know what to do with k and asked Denis to help. Denis decided to wipe last n digits of k and named the new number as r.As a result, Denis proposed to find such integer x of length n that r (as number) is maximum possible. If there are multiple valid x then Denis is interested in the minimum one.All crew members, including captain Flint himself, easily solved the task. All, except cabin boy Kostya, who was too drunk to think straight. But what about you?Note: in this task, we compare integers (x or k) as numbers (despite what representations they are written in), so 729 < 1999 or 111 < 1000.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.Next t lines contain test cases — one per test case. The one and only line of each test case contains the single integer n (1 \le n \le 10^5) — the length of the integer x you need to find.It's guaranteed that the sum of n from all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print the minimum integer x of length n such that obtained by Denis number r is maximum possible.ExampleInput 2 1 3 Output 8 998 NoteIn the second test case (with n = 3), if uncle Bogdan had x = 998 then k = 100110011000. Denis (by wiping last n = 3 digits) will obtain r = 100110011.It can be proved that the 100110011 is the maximum possible r Denis can obtain and 998 is the minimum x to obtain it.
2 1 3
8 998
2 seconds
256 megabytes
['greedy', 'math', '*1000']
A. Captain Flint and Crew Recruitmenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDespite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.Recently, out of blue Captain Flint has been interested in math and even defined a new class of integers. Let's define a positive integer x as nearly prime if it can be represented as p \cdot q, where 1 < p < q and p and q are prime numbers. For example, integers 6 and 10 are nearly primes (since 2 \cdot 3 = 6 and 2 \cdot 5 = 10), but integers 1, 3, 4, 16, 17 or 44 are not.Captain Flint guessed an integer n and asked you: can you represent it as the sum of 4 different positive integers where at least 3 of them should be nearly prime.Uncle Bogdan easily solved the task and joined the crew. Can you do the same?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.Next t lines contain test cases — one per line. The first and only line of each test case contains the single integer n (1 \le n \le 2 \cdot 10^5) — the number Flint guessed.OutputFor each test case print: YES and 4 different positive integers such that at least 3 of them are nearly prime and their sum is equal to n (if there are multiple answers print any of them); NO if there is no way to represent n as the sum of 4 different positive integers where at least 3 of them are nearly prime. You can print each character of YES or NO in any case.ExampleInput 7 7 23 31 36 44 100 258 Output NO NO YES 14 10 6 1 YES 5 6 10 15 YES 6 7 10 21 YES 2 10 33 55 YES 10 21 221 6NoteIn the first and second test cases, it can be proven that there are no four different positive integers such that at least three of them are nearly prime.In the third test case, n=31=2 \cdot 7 + 2 \cdot 5 + 2 \cdot 3 + 1: integers 14, 10, 6 are nearly prime.In the fourth test case, n=36=5 + 2 \cdot 3 + 2 \cdot 5 + 3 \cdot 5: integers 6, 10, 15 are nearly prime.In the fifth test case, n=44=2 \cdot 3 + 7 + 2 \cdot 5 + 3 \cdot 7: integers 6, 10, 21 are nearly prime.In the sixth test case, n=100=2 + 2 \cdot 5 + 3 \cdot 11 + 5 \cdot 11: integers 10, 33, 55 are nearly prime.In the seventh test case, n=258=2 \cdot 5 + 3 \cdot 7 + 13 \cdot 17 + 2 \cdot 3: integers 10, 21, 221, 6 are nearly prime.
7 7 23 31 36 44 100 258
NO NO YES 14 10 6 1 YES 5 6 10 15 YES 6 7 10 21 YES 2 10 33 55 YES 10 21 221 6
1 second
256 megabytes
['brute force', 'greedy', 'math', 'number theory', '*800']
C. Virusestime limit per test0.75 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Committee for Research on Binary Viruses discovered a method of replication for a large family of viruses whose genetic codes are sequences of zeros and ones. Each virus originates from a single gene; for simplicity genes are denoted by integers from 0 to G - 1. At each moment in time a virus is a sequence of genes. When mutation occurs, one of the genes from the sequence is replaced by a certain sequence of genes, according to the mutation table. The virus stops mutating when it consists only of genes 0 and 1.For instance, for the following mutation table: 2 \to \langle 0\ 1 \rangle \\ 3 \to \langle 2\ 0\ 0\rangle\\ 3 \to \langle 1\ 3\rangle\\ 4 \to \langle 0\ 3\ 1\ 2\rangle\\ 5 \to \langle 2\ 1\rangle\\ 5 \to \langle 5\rangle a virus that initially consisted of a single gene 4, could have mutated as follows: \langle 4 \rangle \to \langle \underline{0\ 3\ 1\ 2} \rangle \to \langle 0\ \underline{2\ 0\ 0}\ 1\ 2 \rangle \to \langle 0\ \underline{0\ 1}\ 0\ 0\ 1\ 2 \rangle \to \langle 0\ 0\ 1\ 0\ 0\ 1\ \underline{0\ 1} \rangle or in another way: \langle 4 \rangle \to \langle \underline{0\ 3\ 1\ 2} \rangle \to \langle 0\ \underline{1\ 3}\ 1\ 2 \rangle \to \langle 0\ 1\ 3\ 1\ \underline{0\ 1} \rangle \to \langle 0\ 1\ \underline{2\ 0\ 0}\ 1\ 0\ 1 \rangle \to \langle 0\ 1\ \underline{0\ 1}\ 0\ 0\ 1\ 0\ 1 \rangle Viruses are detected by antibodies that identify the presence of specific continuous fragments of zeros and ones in the viruses' codes. For example, an antibody reacting to a fragment \langle 0\ 0\ 1\ 0\ 0 \rangle will detect a virus \langle 0\ 0\ 1\ 0\ 0\ 1\ 0\ 1 \rangle, but it will not detect a virus \langle 0\ 1\ 0\ 1\ 0\ 0\ 1\ 0\ 1 \rangle.For each gene from 2 to G-1, the scientists are wondering whether a given set of antibodies is enough to detect all viruses that can emerge through mutations from this gene. If not, they want to know the length of the shortest virus that cannot be detected.It may happen that sometimes scientists don't have any antibodies. Then of course no virus can be detected, so the scientists are only interested in the length of the shortest possible virus that can emerge from the gene mutations.InputThe first line of the input will contain three integers G, N and M (G > 2, N \geq G - 2, M \geq 0) specifying the number of genes, the number of rows in the mutation table, and the number of antibodies.The following N lines contain descriptions of rows of the mutation table; each line begins with two integers a and k (2 \leq a < G, k \geq 1), followed by a sequence of k integers b_1, b_2, \ldots, b_k (0 \leq b_i < G), that encode the row a \to \langle b_1\ b_2\ \ldots\ b_k \rangle The sum of all values k does not exceed 100. Every integer from 2 to G - 1 appears in the table as a at least once.The next M lines contain descriptions of the antibodies; each such line begins with an integer \ell (\ell \geq 1), followed by a sequence of \ell integers c_1, c_2, \ldots, c_\ell (0 \leq c_i \leq 1), describing the antibody. The sum of all values \ell does not exceed 50.OutputYour program needs to output exactly G - 2 lines, containing the answers for the subsequent genes from 2 to G - 1.If all viruses that can mutate from this single gene can be detected by the given set of antibodies, you need to print the word "YES". You also need to print this if there are no viruses that could originate from this gene (it can happen when the sequences never stop mutating).Otherwise you need to print the word "NO", followed by an integer denoting the minimal length of the undetectable virus. You can assume that for all the prepared input data this value will be smaller than 2^{63}.ScoringSubtasks: (11 points) No antibodies (M = 0) (14 points) N = G - 2 (25 points) One antibody (M = 1) (32 points) The sum of all values \ell does not exceed 10 (18 points) No further constraints ExampleInput 6 6 2 2 2 0 1 3 3 2 0 0 3 2 1 3 4 4 0 3 1 2 5 2 2 1 5 1 5 2 1 1 5 0 0 1 0 0 Output NO 2 NO 4 NO 9 YES
6 6 2 2 2 0 1 3 3 2 0 0 3 2 1 3 4 4 0 3 1 2 5 2 2 1 5 1 5 2 1 1 5 0 0 1 0 0
NO 2 NO 4 NO 9 YES
0.75 seconds
256 megabytes
['*special problem', 'dp', 'shortest paths', 'string suffix structures', '*2900']
B2. Village (Maximum)time limit per test0.75 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is split into two tasks. In this task, you are required to find the maximum possible answer. In the task Village (Minimum) you are required to find the minimum possible answer. Each task is worth 50 points.There are N houses in a certain village. A single villager lives in each of the houses. The houses are connected by roads. Each road connects two houses and is exactly 1 kilometer long. From each house it is possible to reach any other using one or several consecutive roads. In total there are N-1 roads in the village.One day all villagers decided to move to different houses — that is, after moving each house should again have a single villager living in it, but no villager should be living in the same house as before. We would like to know the largest possible total length in kilometers of the shortest paths between the old and the new houses for all villagers. Example village with seven houses For example, if there are seven houses connected by roads as shown on the figure, the largest total length is 18 km (this can be achieved by moving 1 \to 7, 2 \to 3, 3 \to 4, 4 \to 1, 5 \to 2, 6 \to 5, 7 \to 6).Write a program that finds the largest total length of the shortest paths in kilometers and an example assignment of the new houses to the villagers.InputThe first line contains an integer N (1 < N \le 10^5). Houses are numbered by consecutive integers 1, 2, \ldots, N.Then N-1 lines follow that describe the roads. Each line contains two integers a and b (1 \le a, b \le N, a \neq b) denoting that there is a road connecting houses a and b.OutputIn the first line output the largest total length of the shortest paths in kilometers.In the second line describe one valid assignment of the new houses with the largest total length: N space-separated distinct integers v_1, v_2, \ldots, v_N. For each i, v_i is the house number where villager from the house i should move (v_i \neq i). If there are several valid assignments, output any of those.ScoringSubtasks: (6 points) N \leq 10 (19 points) N \leq 1\,000 (25 points) No further constraints ExamplesInput 4 1 2 2 3 3 4 Output 8 4 3 2 1 Input 7 4 2 5 7 3 4 6 3 1 3 4 5 Output 18 2 7 4 1 3 5 6
4 1 2 2 3 3 4
8 4 3 2 1
0.75 seconds
256 megabytes
['*special problem', 'dfs and similar', 'trees', '*2500']
B1. Village (Minimum)time limit per test0.75 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is split into two tasks. In this task, you are required to find the minimum possible answer. In the task Village (Maximum) you are required to find the maximum possible answer. Each task is worth 50 points.There are N houses in a certain village. A single villager lives in each of the houses. The houses are connected by roads. Each road connects two houses and is exactly 1 kilometer long. From each house it is possible to reach any other using one or several consecutive roads. In total there are N-1 roads in the village.One day all villagers decided to move to different houses — that is, after moving each house should again have a single villager living in it, but no villager should be living in the same house as before. We would like to know the smallest possible total length in kilometers of the shortest paths between the old and the new houses for all villagers. Example village with seven houses For example, if there are seven houses connected by roads as shown on the figure, the smallest total length is 8 km (this can be achieved by moving 1 \to 6, 2 \to 4, 3 \to 1, 4 \to 2, 5 \to 7, 6 \to 3, 7 \to 5).Write a program that finds the smallest total length of the shortest paths in kilometers and an example assignment of the new houses to the villagers.InputThe first line contains an integer N (1 < N \le 10^5). Houses are numbered by consecutive integers 1, 2, \ldots, N.Then N-1 lines follow that describe the roads. Each line contains two integers a and b (1 \le a, b \le N, a \neq b) denoting that there is a road connecting houses a and b.OutputIn the first line output the smallest total length of the shortest paths in kilometers.In the second line describe one valid assignment of the new houses with the smallest total length: N space-separated distinct integers v_1, v_2, \ldots, v_N. For each i, v_i is the house number where the villager from the house i should move (v_i \neq i). If there are several valid assignments, output any of those.ScoringSubtasks: (6 points) N \leq 10 (19 points) N \leq 1\,000 (25 points) No further constraints ExamplesInput 4 1 2 2 3 3 4 Output 4 2 1 4 3 Input 7 4 2 5 7 3 4 6 3 1 3 4 5 Output 8 3 4 6 2 7 1 5
4 1 2 2 3 3 4
4 2 1 4 3
0.75 seconds
256 megabytes
['*special problem', 'dp', 'greedy', 'trees', '*2100']
A. Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph where each edge has one of two colors: black or red.Your task is to assign a real number to each node so that: for each black edge the sum of values at its endpoints is 1; for each red edge the sum of values at its endpoints is 2; the sum of the absolute values of all assigned numbers is the smallest possible. Otherwise, if it is not possible, report that there is no feasible assignment of the numbers.InputThe first line contains two integers N (1 \leq N \leq 100\,000) and M (0 \leq M \leq 200\,000): the number of nodes and the number of edges, respectively. The nodes are numbered by consecutive integers: 1, 2, \ldots, N.The next M lines describe the edges. Each line contains three integers a, b and c denoting that there is an edge between nodes a and b (1 \leq a, b \leq N) with color c (1 denotes black, 2 denotes red).OutputIf there is a solution, the first line should contain the word "YES" and the second line should contain N space-separated numbers. For each i (1 \le i \le N), the i-th number should be the number assigned to the node i.Output should be such that: the sum of the numbers at the endpoints of each edge differs from the precise value by less than 10^{-6}; the sum of the absolute values of all assigned numbers differs from the smallest possible by less than 10^{-6}. If there are several valid solutions, output any of them.If there is no solution, the only line should contain the word "NO".ScoringSubtasks: (5 points) N \leq 5, M \leq 14 (12 points) N \leq 100 (17 points) N \leq 1000 (24 points) N \leq 10\,000 (42 points) No further constraints ExamplesInput 4 4 1 2 1 2 3 2 1 3 2 3 4 1 Output YES 0.5 0.5 1.5 -0.5 Input 2 1 1 2 1 Output YES 0.3 0.7Input 3 2 1 2 2 2 3 2 Output YES 0 2 0 Input 3 4 1 2 2 2 2 1 2 1 1 1 2 2 Output NO NoteNote that in the second example the solution is not unique.
4 4 1 2 1 2 3 2 1 3 2 3 4 1
YES 0.5 0.5 1.5 -0.5
1 second
256 megabytes
['*special problem', 'binary search', 'dfs and similar', 'dp', 'math', 'ternary search', '*2100']
C. Jokertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJoker returns to Gotham City to execute another evil plan. In Gotham City, there are N street junctions (numbered from 1 to N) and M streets (numbered from 1 to M). Each street connects two distinct junctions, and two junctions are connected by at most one street.For his evil plan, Joker needs to use an odd number of streets that together form a cycle. That is, for a junction S and an even positive integer k, there is a sequence of junctions S, s_1, \ldots, s_k, S such that there are streets connecting (a) S and s_1, (b) s_k and S, and (c) s_{i-1} and s_i for each i = 2, \ldots, k.However, the police are controlling the streets of Gotham City. On each day i, they monitor a different subset of all streets with consecutive numbers j: l_i \leq j \leq r_i. These monitored streets cannot be a part of Joker's plan, of course. Unfortunately for the police, Joker has spies within the Gotham City Police Department; they tell him which streets are monitored on which day. Now Joker wants to find out, for some given number of days, whether he can execute his evil plan. On such a day there must be a cycle of streets, consisting of an odd number of streets which are not monitored on that day.InputThe first line of the input contains three integers N, M, and Q (1 \leq N, M, Q \leq 200\,000): the number of junctions, the number of streets, and the number of days to be investigated. The following M lines describe the streets. The j-th of these lines (1 \le j \le M) contains two junction numbers u and v (u \neq v), saying that street j connects these two junctions. It is guaranteed that any two junctions are connected by at most one street. The following Q lines contain two integers l_i and r_i, saying that all streets j with l_i \leq j \leq r_i are checked by the police on day i (1 \leq i \leq Q).OutputYour output is to contain Q lines. Line i (1 \leq i \leq Q) contains "YES" if Joker can execute his plan on day i, or "NO" otherwise.ScoringSubtasks: (6 points) 1 \leq N, M, Q \leq 200 (8 points) 1 \leq N, M, Q \leq 2\,000 (25 points) l_i = 1 for i = 1, \ldots, Q (10 points) l_i \leq 200 for i = 1, \ldots, Q (22 points) Q \leq 2\,000 (29 points) No further constraints ExampleInput 6 8 2 1 3 1 5 1 6 2 5 2 6 3 4 3 5 5 6 4 8 4 7 Output NO YES NoteThe graph in the example test:
6 8 2 1 3 1 5 1 6 2 5 2 6 3 4 3 5 5 6 4 8 4 7
NO YES
1 second
256 megabytes
['*special problem', 'bitmasks', 'data structures', 'divide and conquer', 'dsu', '*2800']
B. Mixturetime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSerge, the chef of the famous restaurant "Salt, Pepper & Garlic" is trying to obtain his first Michelin star. He has been informed that a secret expert plans to visit his restaurant this evening.Even though the expert's name hasn't been disclosed, Serge is certain he knows which dish from the menu will be ordered as well as what the taste preferences of the expert are. Namely, the expert requires an extremely precise proportion of salt, pepper and garlic powder in his dish.Serge keeps a set of bottles with mixtures of salt, pepper and garlic powder on a special shelf in the kitchen. For each bottle, he knows the exact amount of each of the ingredients in kilograms. Serge can combine any number of bottled mixtures (or just use one of them directly) to get a mixture of particular proportions needed for a certain dish.Luckily, the absolute amount of a mixture that needs to be added to a dish is so small that you can assume that the amounts in the bottles will always be sufficient. However, the numeric values describing the proportions may be quite large.Serge would like to know whether it is possible to obtain the expert's favourite mixture from the available bottles, and if so—what is the smallest possible number of bottles needed to achieve that.Furthermore, the set of bottles on the shelf may change over time as Serge receives new ones or lends his to other chefs. So he would like to answer this question after each such change.For example, assume that expert's favorite mixture is 1:1:1 and there are three bottles of mixtures on the shelf: \begin{array}{cccc} \hline \text{Mixture} & \text{Salt} & \text{Pepper} & \text{Garlic powder} \\ \hline 1 & 10 & 20 & 30 \\ 2 & 300 & 200 & 100 \\ 3 & 12 & 15 & 27 \\ \hline \end{array} Amount of ingredient in the bottle, kg To obtain the desired mixture it is enough to use an equivalent amount of mixtures from bottles 1 and 2. If bottle 2 is removed, then it is no longer possible to obtain it.Write a program that helps Serge to solve this task!InputThe first row contains three non-negative integers S_f, P_f and G_f (0 \leq S_f, P_f, G_f; 0 < S_f+P_f+G_f \leq 10^6) describing the amount of salt, pepper and garlic powder in the expert's favourite mixture. For any real \alpha>0, (\alpha{S_f}, \alpha{P_f}, \alpha{G_f}) also is an expert's favourite mixture.In the second row, there is a positive integer N (number of changes on the shelf, N \leq 100\,000). You should assume that initially the shelf is empty.Each of the next N rows describes a single change on the shelf: If a new bottle is added, the row contains capital letter A followed by three non-negative integers S_i, P_i and G_i (0 \leq S_i, P_i, G_i; 0 < S_i+P_i+G_i \leq 10^6) describing the amount of salt, pepper and garlic powder in the added bottle. Added bottles are numbered consecutively by unique integers starting from 1, that is, the i-th bottle corresponds to the i-th added bottle in the input data. If a particular bottle is removed from the shelf, the row contains capital letter R followed by the integer—the bottle number r_i. All values r_i in the removals are unique, r_i never exceeds total number of bottles added thus far. OutputOutput N rows. The j-th row (1 \leq j \leq N) should contain the number x_j, the smallest number of bottles needed to prepare a mixture with the expert's favourite proportions of salt, pepper and garlic powder using the bottles available after the first j changes on the shelf, or 0 if it is not possible.ScoringSubtasks: (13 points) N \leq 50, 0 < S_i+P_i+G_i \leq 10^2 (17 points) N \leq 500, 0 < S_i+P_i+G_i \leq 10^3 (30 points) N \leq 5000, 0 < S_i+P_i+G_i \leq 10^4 (40 points) No further constraints ExampleInput 1 2 3 6 A 5 6 7 A 3 10 17 R 1 A 15 18 21 A 5 10 15 R 3 Output 0 2 0 2 1 1 NotePay attention that in the example, bottles 1 and 3 contain the same proportions of salt, pepper and garlic powder.
1 2 3 6 A 5 6 7 A 3 10 17 R 1 A 15 18 21 A 5 10 15 R 3
0 2 0 2 1 1
2.5 seconds
256 megabytes
['*special problem', 'data structures', 'geometry', 'math', 'sortings', '*2900']
A. Colorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLinda likes to change her hair color from time to time, and would be pleased if her boyfriend Archie would notice the difference between the previous and the new color. Archie always comments on Linda's hair color if and only if he notices a difference — so Linda always knows whether Archie has spotted the difference or not.There is a new hair dye series in the market where all available colors are numbered by integers from 1 to N such that a smaller difference of the numerical values also means less visual difference.Linda assumes that for these series there should be some critical color difference C (1 \le C \le N) for which Archie will notice color difference between the current color \mathrm{color}_{\mathrm{new}} and the previous color \mathrm{color}_{\mathrm{prev}} if \left|\mathrm{color}_{\mathrm{new}} - \mathrm{color}_{\mathrm{prev}}\right| \ge C and will not if \left|\mathrm{color}_{\mathrm{new}} - \mathrm{color}_{\mathrm{prev}}\right| < C.Now she has bought N sets of hair dye from the new series — one for each of the colors from 1 to N, and is ready to set up an experiment. Linda will change her hair color on a regular basis and will observe Archie's reaction — whether he will notice the color change or not. Since for the proper dye each set should be used completely, each hair color can be obtained no more than once.Before the experiment, Linda was using a dye from a different series which is not compatible with the new one, so for the clearness of the experiment Archie's reaction to the first used color is meaningless.Her aim is to find the precise value of C in a limited number of dyes. Write a program which finds the value of C by experimenting with the given N colors and observing Archie's reactions to color changes.InteractionThis is an interactive task. In the beginning you are given a single integer T (1 \leq T \leq 100), the number of cases in the test.For each test case, the input first contains a single integer — the value of N (1 < N \le 10^{18}). The value of C is kept secret by the grading system.Then your program should make queries writing output in the following format: "? P", where P is an integer (1 \le P \le N) denoting the next color used. For each query the grading system gives an answer in the next line of the input. The answer is 1 if Archie notices the color difference between the last two colors and 0 otherwise. No two queries should have the same P value.When your program determines C, it should output its value in the following format: "= C". The grading system will not respond to this output and will proceed with the next test case.Your program may use at most 64 queries "?" for each test case to find the correct value of C.To establish proper communication between your program and the grading system, you should flush the output stream after each query. \begin{array}{ll} \text{Language} & \text{Command} \\ \hline \text{C++} & \texttt{std::cout }\texttt{<}\texttt{<}\texttt{ std::endl;} \\ \text{Java} & \texttt{System.out.flush();} \\ \text{Python} & \texttt{sys.stdout.flush()} \end{array} Flush commands Note that std::endl writes a newline and flushes the stream.It is possible to receive an "Output isn't correct" outcome even after printing a correct answer, if task constraints were violated during the communication. Violating the communication protocol itself may result in an "Execution killed" outcome.Submitting user tests requires specifying an input file with the testcase parameters. The format of the input file is "T" in the first line, and then "N C" on a single line for each of the T cases.ScoringSubtasks: (9 points) N \le 64 (13 points) N \le 125 (21 points) N \le 1000 (24 points) N \le 10^9 (33 points) No further constraints. ExampleInput 1 7 1 1 0 0 1 Output ? 2 ? 7 ? 4 ? 1 ? 5 = 4NoteComments to the example input line by line: N = 7. Answer to the first query is meaningless (can also be 0). C \leq 5. 3 < C \leq 5. It would be wise to check difference 4. However, this can not be done in the next query since 4 + 4 = 8 and 4 - 4 = 0 both are outside the allowed interval 1 \le P \le 7. 3 < C \leq 5. 3 < C \leq 4. Therefore, C = 4.
1 7 1 1 0 0 1
? 2 ? 7 ? 4 ? 1 ? 5 = 4
1 second
256 megabytes
['*special problem', 'binary search', 'constructive algorithms', 'interactive', '*2700']
G. Columns Swapstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a table a of size 2 \times n (i.e. two rows and n columns) consisting of integers from 1 to n.In one move, you can choose some column j (1 \le j \le n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once.Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that.You have to answer t independent test cases.Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter).InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, \dots, a_{1, n} (1 \le a_{1, i} \le n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, \dots, a_{2, n} (1 \le a_{2, i} \le n), where a_{2, i} is the i-th element of the second row of the table.It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, \dots, pos_k in the second line (1 \le pos_i \le n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any.ExampleInput 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1
6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2
0 2 2 3 1 1 2 3 4 2 3 4 -1
2 seconds
256 megabytes
['2-sat', 'dfs and similar', 'dsu', 'graphs', 'implementation', '*2300']
F. Removing Leavestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree (connected graph without cycles) consisting of n vertices. The tree is unrooted — it is just a connected undirected graph without cycles.In one move, you can choose exactly k leaves (leaf is such a vertex that is connected to only one another vertex) connected to the same vertex and remove them with edges incident to them. I.e. you choose such leaves u_1, u_2, \dots, u_k that there are edges (u_1, v), (u_2, v), \dots, (u_k, v) and remove these leaves and these edges.Your task is to find the maximum number of moves you can perform if you remove leaves optimally.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains two integers n and k (2 \le n \le 2 \cdot 10^5; 1 \le k < n) — the number of vertices in the tree and the number of leaves you remove in one move, respectively. The next n-1 lines describe edges. The i-th edge is represented as two integers x_i and y_i (1 \le x_i, y_i \le n), where x_i and y_i are vertices the i-th edge connects. It is guaranteed that the given set of edges forms a tree.It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer — the maximum number of moves you can perform if you remove leaves optimally.ExampleInput 4 8 3 1 2 1 5 7 6 6 8 3 1 6 4 6 1 10 3 1 2 1 10 2 3 1 5 1 6 2 4 7 10 10 9 8 10 7 2 3 1 4 5 3 6 7 4 1 2 1 4 5 1 1 2 2 3 4 3 5 3 Output 2 3 3 4 NoteThe picture corresponding to the first test case of the example:There you can remove vertices 2, 5 and 3 during the first move and vertices 1, 7 and 4 during the second move.The picture corresponding to the second test case of the example:There you can remove vertices 7, 8 and 9 during the first move, then vertices 5, 6 and 10 during the second move and vertices 1, 3 and 4 during the third move.The picture corresponding to the third test case of the example:There you can remove vertices 5 and 7 during the first move, then vertices 2 and 4 during the second move and vertices 1 and 6 during the third move.
4 8 3 1 2 1 5 7 6 6 8 3 1 6 4 6 1 10 3 1 2 1 10 2 3 1 5 1 6 2 4 7 10 10 9 8 10 7 2 3 1 4 5 3 6 7 4 1 2 1 4 5 1 1 2 2 3 4 3 5 3
2 3 3 4
2 seconds
256 megabytes
['data structures', 'greedy', 'implementation', 'trees', '*2300']
E. Directing Edgestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges.You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains two integers n and m (2 \le n \le 2 \cdot 10^5, 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})) — the number of vertices and the number of edges in the graph, respectively.The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i \in [0; 1], 1 \le x_i, y_i \le n) — the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)).It is guaranteed that both sum n and sum m do not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5; \sum m \le 2 \cdot 10^5).OutputFor each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any.ExampleInput 43 10 1 35 50 2 11 1 51 5 40 5 21 3 54 51 1 20 4 31 3 10 2 31 2 44 51 4 11 1 30 1 21 2 41 3 2Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO NoteExplanation of the second test case of the example:Explanation of the third test case of the example:
43 10 1 35 50 2 11 1 51 5 40 5 21 3 54 51 1 20 4 31 3 10 2 31 2 44 51 4 11 1 30 1 21 2 41 3 2
YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO
3 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', '*2000']
D. a-Good Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s[1 \dots n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k \ge 0.The string s[1 \dots n] is called c-good if at least one of the following three conditions is satisfied: The length of s is 1, and it consists of the character c (i.e. s_1=c); The length of s is greater than 1, the first half of the string consists of only the character c (i.e. s_1=s_2=\dots=s_{\frac{n}{2}}=c) and the second half of the string (i.e. the string s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n) is a (c+1)-good string; The length of s is greater than 1, the second half of the string consists of only the character c (i.e. s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c) and the first half of the string (i.e. the string s_1s_2 \dots s_{\frac{n}{2}}) is a (c+1)-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index i from 1 to n and replace s_i with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from s (i.e. c-good string for c= 'a'). It is guaranteed that the answer always exists.You have to answer t independent test cases.Another example of an 'a'-good string is as follows. Consider the string s = "cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string. InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 131~072) — the length of s. It is guaranteed that n = 2^k for some integer k \ge 0. The second line of the test case contains the string s consisting of n lowercase Latin letters.It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer — the minimum number of moves required to obtain an 'a'-good string from s (i.e. c-good string with c = 'a'). It is guaranteed that the answer exists.ExampleInput 6 8 bbdcaaaa 8 asdfghjk 8 ceaaaabb 8 bbaaddcc 1 z 2 ac Output 0 7 4 5 1 1
6 8 bbdcaaaa 8 asdfghjk 8 ceaaaabb 8 bbaaddcc 1 z 2 ac
0 7 4 5 1 1
2 seconds
256 megabytes
['bitmasks', 'brute force', 'divide and conquer', 'dp', 'implementation', '*1500']
C. Make It Goodtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, \dots, a_n] is a subarray consisting several first elements: the prefix of the array a of length k is the array [a_1, a_2, \dots, a_k] (0 \le k \le n).The array b of length m is called good, if you can obtain a non-decreasing array c (c_1 \le c_2 \le \dots \le c_{m}) from it, repeating the following operation m times (initially, c is empty): select either the first or the last element of b, remove it from b, and append it to the end of the array c. For example, if we do 4 operations: take b_1, then b_{m}, then b_{m-1} and at last b_2, then b becomes [b_3, b_4, \dots, b_{m-3}] and c =[b_1, b_{m}, b_{m-1}, b_2].Consider the following example: b = [1, 2, 3, 4, 4, 2, 1]. This array is good because we can obtain non-decreasing array c from it by the following sequence of operations: take the first element of b, so b = [2, 3, 4, 4, 2, 1], c = [1]; take the last element of b, so b = [2, 3, 4, 4, 2], c = [1, 1]; take the last element of b, so b = [2, 3, 4, 4], c = [1, 1, 2]; take the first element of b, so b = [3, 4, 4], c = [1, 1, 2, 2]; take the first element of b, so b = [4, 4], c = [1, 1, 2, 2, 3]; take the last element of b, so b = [4], c = [1, 1, 2, 2, 3, 4]; take the only element of b, so b = [], c = [1, 1, 2, 2, 3, 4, 4] — c is non-decreasing. Note that the array consisting of one element is good.Print the length of the shortest prefix of a to delete (erase), to make a to be a good array. Note that the required length can be 0.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the length of a. The second line of the test case 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.It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer: the length of the shortest prefix of elements you need to erase from a to make it a good array.ExampleInput 5 4 1 2 3 4 7 4 3 3 8 4 5 2 3 1 1 1 7 1 3 1 4 5 3 2 5 5 4 3 2 3 Output 0 4 0 2 3 NoteIn the first test case of the example, the array a is already good, so we don't need to erase any prefix.In the second test case of the example, the initial array a is not good. Let's erase first 4 elements of a, the result is [4, 5, 2]. The resulting array is good. You can prove that if you erase fewer number of first elements, the result will not be good.
5 4 1 2 3 4 7 4 3 3 8 4 5 2 3 1 1 1 7 1 3 1 4 5 3 2 5 5 4 3 2 3
0 4 0 2 3
1 second
256 megabytes
['greedy', '*1200']
B. Restore the Permutation by Mergertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not.There was a permutation p[1 \dots n]. It was merged with itself. In other words, let's take two instances of p and insert elements of the second p into the first maintaining relative order of elements. The result is a sequence of the length 2n.For example, if p=[3, 1, 2] some possible results are: [3, 1, 2, 3, 1, 2], [3, 3, 1, 1, 2, 2], [3, 1, 3, 1, 2, 2]. The following sequences are not possible results of a merging: [1, 3, 2, 1, 2, 3], [3, 1, 2, 3, 2, 1], [3, 3, 1, 2, 2, 1].For example, if p=[2, 1] the possible results are: [2, 2, 1, 1], [2, 1, 2, 1]. The following sequences are not possible results of a merging: [1, 1, 2, 2], [2, 1, 1, 2], [1, 2, 2, 1].Your task is to restore the permutation p by the given resulting sequence a. It is guaranteed that the answer exists and is unique.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 400) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 50) — the length of permutation. The second line of the test case contains 2n integers a_1, a_2, \dots, a_{2n} (1 \le a_i \le n), where a_i is the i-th element of a. It is guaranteed that the array a represents the result of merging of some permutation p with the same permutation p.OutputFor each test case, print the answer: n integers p_1, p_2, \dots, p_n (1 \le p_i \le n), representing the initial permutation. It is guaranteed that the answer exists and is unique.ExampleInput 5 2 1 1 2 2 4 1 3 1 4 3 4 2 2 5 1 2 1 2 3 4 3 5 4 5 3 1 2 3 1 2 3 4 2 3 2 4 1 3 4 1 Output 1 2 1 3 4 2 1 2 3 4 5 1 2 3 2 3 4 1
5 2 1 1 2 2 4 1 3 1 4 3 4 2 2 5 1 2 1 2 3 4 3 5 4 5 3 1 2 3 1 2 3 4 2 3 2 4 1 3 4 1
1 2 1 3 4 2 1 2 3 4 5 1 2 3 2 3 4 1
1 second
256 megabytes
['greedy', '*800']
A. Three Pairwise Maximumstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three positive (i.e. strictly greater than zero) integers x, y and z.Your task is to find positive integers a, b and c such that x = \max(a, b), y = \max(a, c) and z = \max(b, c), or determine that it is impossible to find such a, b and c.You have to answer t independent test cases. Print required a, b and c in any (arbitrary) order.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The only line of the test case contains three integers x, y, and z (1 \le x, y, z \le 10^9).OutputFor each test case, print the answer: "NO" in the only line of the output if a solution doesn't exist; or "YES" in the first line and any valid triple of positive integers a, b and c (1 \le a, b, c \le 10^9) in the second line. You can print a, b and c in any order. ExampleInput 5 3 2 3 100 100 100 50 49 49 10 30 20 1 1000000000 1000000000 Output YES 3 2 1 YES 100 100 100 NO NO YES 1 1 1000000000
5 3 2 3 100 100 100 50 49 49 10 30 20 1 1000000000 1000000000
YES 3 2 1 YES 100 100 100 NO NO YES 1 1 1000000000
1 second
256 megabytes
['math', '*800']
B2. Koa and the Beach (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.Koa the Koala is at the beach!The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.She measured the depth of the sea at 1, 2, \dots, n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 \le i \le n.Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way: For a total of k seconds, each second, tide increases all depths by 1. Then, for a total of k seconds, each second, tide decreases all depths by 1. This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).Formally, let's define 0-indexed array p = [0, 1, 2, \ldots, k - 2, k - 1, k, k - 1, k - 2, \ldots, 2, 1] of length 2k. At time t (0 \le t) depth at i meters from the shore equals d_i + p[t \bmod 2k] (t \bmod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding. At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 \le t) she is at x (0 \le x \le n) meters from the shore: In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1. As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 \le x \le n) meters from the shore at the moment t (for some integer t\ge 0), the depth of the sea at this point  — d_x + p[t \bmod 2k]  — can't exceed l. In other words, d_x + p[t \bmod 2k] \le l must hold always. Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there). Koa wants to know whether she can go from the shore to the island. Help her!InputThe first line of the input contains one integer t (1 \le t \le 10^4)  — the number of test cases. Description of the test cases follows.The first line of each test case contains three integers n, k and l (1 \le n \le 3 \cdot 10^5; 1 \le k \le 10^9; 1 \le l \le 10^9) — the number of meters of sea Koa measured and parameters k and l.The second line of each test case contains n integers d_1, d_2, \ldots, d_n (0 \le d_i \le 10^9)  — the depths of each meter of sea Koa measured.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case:Print Yes if Koa can get from the shore to the island, and No otherwise.You may print each letter in any case (upper or lower).ExampleInput 7 2 1 1 1 0 5 2 3 1 2 3 2 2 4 3 4 0 2 4 3 2 3 5 3 0 7 2 3 3 0 2 1 3 0 1 7 1 4 4 4 3 0 2 4 2 5 2 3 1 2 3 2 2 Output Yes No Yes Yes Yes No No NoteIn the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, \dots, n meters from the shore.In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution: Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i]. At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1. At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 \le 1. At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 \le 1. At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4. At t = 4 Koa is at x = 3 and she made it! We can show that in test case 2 Koa can't get to the island.
7 2 1 1 1 0 5 2 3 1 2 3 2 2 4 3 4 0 2 4 3 2 3 5 3 0 7 2 3 3 0 2 1 3 0 1 7 1 4 4 4 3 0 2 4 2 5 2 3 1 2 3 2 2
Yes No Yes Yes Yes No No
1 second
256 megabytes
['constructive algorithms', 'dp', 'greedy', 'implementation', '*2200']
B1. Koa and the Beach (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is on constraints. In this version constraints are lower. You can make hacks only if all versions of the problem are solved.Koa the Koala is at the beach!The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.She measured the depth of the sea at 1, 2, \dots, n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 \le i \le n.Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way: For a total of k seconds, each second, tide increases all depths by 1. Then, for a total of k seconds, each second, tide decreases all depths by 1. This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).Formally, let's define 0-indexed array p = [0, 1, 2, \ldots, k - 2, k - 1, k, k - 1, k - 2, \ldots, 2, 1] of length 2k. At time t (0 \le t) depth at i meters from the shore equals d_i + p[t \bmod 2k] (t \bmod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding. At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 \le t) she is at x (0 \le x \le n) meters from the shore: In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1. As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 \le x \le n) meters from the shore at the moment t (for some integer t\ge 0), the depth of the sea at this point  — d_x + p[t \bmod 2k]  — can't exceed l. In other words, d_x + p[t \bmod 2k] \le l must hold always. Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there). Koa wants to know whether she can go from the shore to the island. Help her!InputThe first line of the input contains one integer t (1 \le t \le 100)  — the number of test cases. Description of the test cases follows.The first line of each test case contains three integers n, k and l (1 \le n \le 100; 1 \le k \le 100; 1 \le l \le 100) — the number of meters of sea Koa measured and parameters k and l.The second line of each test case contains n integers d_1, d_2, \ldots, d_n (0 \le d_i \le 100)  — the depths of each meter of sea Koa measured.It is guaranteed that the sum of n over all test cases does not exceed 100.OutputFor each test case:Print Yes if Koa can get from the shore to the island, and No otherwise.You may print each letter in any case (upper or lower).ExampleInput 7 2 1 1 1 0 5 2 3 1 2 3 2 2 4 3 4 0 2 4 3 2 3 5 3 0 7 2 3 3 0 2 1 3 0 1 7 1 4 4 4 3 0 2 4 2 5 2 3 1 2 3 2 2 Output Yes No Yes Yes Yes No No NoteIn the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, \dots, n meters from the shore.In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution: Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i]. At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1. At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 \le 1. At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 \le 1. At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4. At t = 4 Koa is at x = 3 and she made it! We can show that in test case 2 Koa can't get to the island.
7 2 1 1 1 0 5 2 3 1 2 3 2 2 4 3 4 0 2 4 3 2 3 5 3 0 7 2 3 3 0 2 1 3 0 1 7 1 4 4 4 3 0 2 4 2 5 2 3 1 2 3 2 2
Yes No Yes Yes Yes No No
1 second
256 megabytes
['brute force', 'dp', 'greedy', '*1900']
A. Common Prefixestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe length of the longest common prefix of two strings s = s_1 s_2 \ldots s_n and t = t_1 t_2 \ldots t_m is defined as the maximum integer k (0 \le k \le min(n,m)) such that s_1 s_2 \ldots s_k equals t_1 t_2 \ldots t_k.Koa the Koala initially has n+1 strings s_1, s_2, \dots, s_{n+1}.For each i (1 \le i \le n) she calculated a_i — the length of the longest common prefix of s_i and s_{i+1}.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings s_1, s_2, \dots, s_{n+1} which would have generated numbers a_1, a_2, \dots, a_n. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints. InputEach test contains multiple test cases. The first line contains t (1 \le t \le 100) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 100) — the number of elements in the list a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 50) — the elements of a.It is guaranteed that the sum of n over all test cases does not exceed 100.OutputFor each test case:Output n+1 lines. In the i-th line print string s_i (1 \le |s_i| \le 200), consisting of lowercase Latin letters. Length of the longest common prefix of strings s_i and s_{i+1} has to be equal to a_i.If there are many answers print any. We can show that answer always exists for the given constraints.ExampleInput 4 4 1 2 4 2 2 5 3 3 1 3 1 3 0 0 0 Output aeren ari arousal around ari monogon monogamy monthly kevinvu kuroni kurioni korone anton loves adhoc problemsNoteIn the 1-st test case one of the possible answers is s = [aeren, ari, arousal, around, ari].Lengths of longest common prefixes are: Between \color{red}{a}eren and \color{red}{a}ri \rightarrow 1 Between \color{red}{ar}i and \color{red}{ar}ousal \rightarrow 2 Between \color{red}{arou}sal and \color{red}{arou}nd \rightarrow 4 Between \color{red}{ar}ound and \color{red}{ar}i \rightarrow 2
4 4 1 2 4 2 2 5 3 3 1 3 1 3 0 0 0
aeren ari arousal around ari monogon monogamy monthly kevinvu kuroni kurioni korone anton loves adhoc problems
1 second
256 megabytes
['constructive algorithms', 'greedy', 'strings', '*1200']
F. Special Edgestime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKoa the Koala has a directed graph G with n nodes and m edges. Each edge has a capacity associated with it. Exactly k edges of the graph, numbered from 1 to k, are special, such edges initially have a capacity equal to 0.Koa asks you q queries. In each query she gives you k integers w_1, w_2, \ldots, w_k. This means that capacity of the i-th special edge becomes w_i (and other capacities remain the same).Koa wonders: what is the maximum flow that goes from node 1 to node n after each such query?Help her!InputThe first line of the input contains four integers n, m, k, q (2 \le n \le 10^4, 1 \le m \le 10^4, 1 \le k \le \min(10, m), 1 \le q \le 2 \cdot 10^5) — the number of nodes, the number of edges, the number of special edges and the number of queries.Each of the next m lines contains three integers u, v, w (1 \le u, v \le n; 0 \le w \le 25) — the description of a directed edge from node u to node v with capacity w.Edges are numbered starting from 1 in the same order they are listed in the input. The first k edges are the special edges. It is guaranteed that w_i = 0 for all i with 1 \le i \le k.Each of the next q lines contains k integers w_1, w_2, \ldots, w_k (0 \le w_i \le 25)  — the description of the query. w_i denotes the capacity of i-th edge.OutputFor the i-th query, print one integer res_i  — the maximum flow that can be obtained from node 1 to node n given the i-th query's special edge weights.ExamplesInput 2 1 1 3 1 2 0 0 1 2 Output 0 1 2 Input 4 4 2 5 1 2 0 2 3 0 2 4 5 3 4 2 0 0 1 10 10 0 7 1 7 2 Output 0 1 5 6 7 NoteFor the second sample, the following images correspond to the first two queries (from left to right respectively). For each edge there is a pair flow/capacity denoting flow pushed through the edge and edge's capacity. The special edges are colored in red. As you can see in first query maximum flow from node 1 to node 4 equals 0 and in second query equals 1.
2 1 1 3 1 2 0 0 1 2
0 1 2
5 seconds
256 megabytes
['flows', 'graphs', '*3200']
E. Strange Operationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKoa the Koala has a binary string s of length n. Koa can perform no more than n-1 (possibly zero) operations of the following form:In one operation Koa selects positions i and i+1 for some i with 1 \le i < |s| and sets s_i to max(s_i, s_{i+1}). Then Koa deletes position i+1 from s (after the removal, the remaining parts are concatenated).Note that after every operation the length of s decreases by 1.How many different binary strings can Koa obtain by doing no more than n-1 (possibly zero) operations modulo 10^9+7 (1000000007)?InputThe only line of input contains binary string s (1 \le |s| \le 10^6). For all i (1 \le i \le |s|) s_i = 0 or s_i = 1.OutputOn a single line print the answer to the problem modulo 10^9+7 (1000000007).ExamplesInput 000 Output 3 Input 0101 Output 6 Input 0001111 Output 16 Input 00101100011100 Output 477 NoteIn the first sample Koa can obtain binary strings: 0, 00 and 000.In the second sample Koa can obtain binary strings: 1, 01, 11, 011, 101 and 0101. For example: to obtain 01 from 0101 Koa can operate as follows: 0101 \rightarrow 0(10)1 \rightarrow 011 \rightarrow 0(11) \rightarrow 01. to obtain 11 from 0101 Koa can operate as follows: 0101 \rightarrow (01)01 \rightarrow 101 \rightarrow 1(01) \rightarrow 11. Parentheses denote the two positions Koa selected in each operation.
000
3
1 second
256 megabytes
['combinatorics', 'data structures', 'dp', '*2800']
D. Rearrangetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKoa the Koala has a matrix A of n rows and m columns. Elements of this matrix are distinct integers from 1 to n \cdot m (each number from 1 to n \cdot m appears exactly once in the matrix).For any matrix M of n rows and m columns let's define the following: The i-th row of M is defined as R_i(M) = [ M_{i1}, M_{i2}, \ldots, M_{im} ] for all i (1 \le i \le n). The j-th column of M is defined as C_j(M) = [ M_{1j}, M_{2j}, \ldots, M_{nj} ] for all j (1 \le j \le m). Koa defines S(A) = (X, Y) as the spectrum of A, where X is the set of the maximum values in rows of A and Y is the set of the maximum values in columns of A.More formally: X = \{ \max(R_1(A)), \max(R_2(A)), \ldots, \max(R_n(A)) \} Y = \{ \max(C_1(A)), \max(C_2(A)), \ldots, \max(C_m(A)) \}Koa asks you to find some matrix A' of n rows and m columns, such that each number from 1 to n \cdot m appears exactly once in the matrix, and the following conditions hold: S(A') = S(A) R_i(A') is bitonic for all i (1 \le i \le n) C_j(A') is bitonic for all j (1 \le j \le m) An array t (t_1, t_2, \ldots, t_k) is called bitonic if it first increases and then decreases. More formally: t is bitonic if there exists some position p (1 \le p \le k) such that: t_1 < t_2 < \ldots < t_p > t_{p+1} > \ldots > t_k.Help Koa to find such matrix or to determine that it doesn't exist.InputThe first line of the input contains two integers n and m (1 \le n, m \le 250)  — the number of rows and columns of A.Each of the ollowing n lines contains m integers. The j-th integer in the i-th line denotes element A_{ij} (1 \le A_{ij} \le n \cdot m) of matrix A. It is guaranteed that every number from 1 to n \cdot m appears exactly once among elements of the matrix.OutputIf such matrix doesn't exist, print -1 on a single line.Otherwise, the output must consist of n lines, each one consisting of m space separated integers  — a description of A'.The j-th number in the i-th line represents the element A'_{ij}.Every integer from 1 to n \cdot m should appear exactly once in A', every row and column in A' must be bitonic and S(A) = S(A') must hold.If there are many answers print any.ExamplesInput 3 3 3 5 6 1 7 9 4 8 2 Output 9 5 1 7 8 2 3 6 4 Input 2 2 4 1 3 2 Output 4 1 3 2 Input 3 4 12 10 8 6 3 4 5 7 2 11 9 1 Output 12 8 6 1 10 11 9 2 3 4 5 7 NoteLet's analyze the first sample:For matrix A we have: Rows: R_1(A) = [3, 5, 6]; \max(R_1(A)) = 6 R_2(A) = [1, 7, 9]; \max(R_2(A)) = 9 R_3(A) = [4, 8, 2]; \max(R_3(A)) = 8 Columns: C_1(A) = [3, 1, 4]; \max(C_1(A)) = 4 C_2(A) = [5, 7, 8]; \max(C_2(A)) = 8 C_3(A) = [6, 9, 2]; \max(C_3(A)) = 9 X = \{ \max(R_1(A)), \max(R_2(A)), \max(R_3(A)) \} = \{ 6, 9, 8 \} Y = \{ \max(C_1(A)), \max(C_2(A)), \max(C_3(A)) \} = \{ 4, 8, 9 \} So S(A) = (X, Y) = (\{ 6, 9, 8 \}, \{ 4, 8, 9 \}) For matrix A' we have: Rows: R_1(A') = [9, 5, 1]; \max(R_1(A')) = 9 R_2(A') = [7, 8, 2]; \max(R_2(A')) = 8 R_3(A') = [3, 6, 4]; \max(R_3(A')) = 6 Columns: C_1(A') = [9, 7, 3]; \max(C_1(A')) = 9 C_2(A') = [5, 8, 6]; \max(C_2(A')) = 8 C_3(A') = [1, 2, 4]; \max(C_3(A')) = 4 Note that each of this arrays are bitonic. X = \{ \max(R_1(A')), \max(R_2(A')), \max(R_3(A')) \} = \{ 9, 8, 6 \} Y = \{ \max(C_1(A')), \max(C_2(A')), \max(C_3(A')) \} = \{ 9, 8, 4 \} So S(A') = (X, Y) = (\{ 9, 8, 6 \}, \{ 9, 8, 4 \})
3 3 3 5 6 1 7 9 4 8 2
9 5 1 7 8 2 3 6 4
1 second
256 megabytes
['brute force', 'constructive algorithms', 'graphs', 'greedy', 'sortings', '*2800']
C. String Transformation 2time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNote that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects can be any letter from the first 20 lowercase letters of English alphabet (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions p_1, p_2, \ldots, p_k (k \ge 1; 1 \le p_i \le n; p_i \neq p_j if i \neq j) of A such that A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). selects any letter y (from the first 20 lowercase letters in English alphabet). sets each letter in positions p_1, p_2, \ldots, p_k to letter y. More formally: for each i (1 \le i \le k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A.Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!InputEach test contains multiple test cases. The first line contains t (1 \le t \le 10) — the number of test cases. Description of the test cases follows.The first line of each test case contains one integer n (1 \le n \le 10^5) — the length of strings A and B.The second line of each test case contains string A (|A|=n).The third line of each test case contains string B (|B|=n).Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case:Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal.ExampleInput 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 3 3 2 4 Note In the 1-st test case Koa: selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b \rightarrow \color{blue}{bb}b). selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} \rightarrow b\color{blue}{cc}). In the 2-nd test case Koa: selects positions 1 and 4 and sets A_1 = A_4 = a (\color{red}{c}ab\color{red}{c} \rightarrow \color{blue}{a}ab\color{blue}{a}). selects positions 2 and 4 and sets A_2 = A_4 = b (a\color{red}{a}b\color{red}{a} \rightarrow a\color{blue}{b}b\color{blue}{b}). selects position 3 and sets A_3 = c (ab\color{red}{b}b \rightarrow ab\color{blue}{c}b). In the 3-rd test case Koa: selects position 1 and sets A_1 = t (\color{red}{a}bc \rightarrow \color{blue}{t}bc). selects position 2 and sets A_2 = s (t\color{red}{b}c \rightarrow t\color{blue}{s}c). selects position 3 and sets A_3 = r (ts\color{red}{c} \rightarrow ts\color{blue}{r}).
5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda
2 3 3 2 4
3 seconds
256 megabytes
['bitmasks', 'dp', 'graphs', 'trees', '*3100']
B. GameGametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKoa the Koala and her best friend want to play a game.The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts.Let's describe a move in the game: During his move, a player chooses any element of the array and removes it from this array, xor-ing it with the current score of the player. More formally: if the current score of the player is x and the chosen element is y, his new score will be x \oplus y. Here \oplus denotes bitwise XOR operation. Note that after a move element y is removed from a. The game ends when the array is empty. At the end of the game the winner is the player with the maximum score. If both players have the same score then it's a draw.If both players play optimally find out whether Koa will win, lose or draw the game.InputEach test contains multiple test cases. The first line contains t (1 \le t \le 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains the integer n (1 \le n \le 10^5) — the length of a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — elements of a.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case print: WIN if Koa will win the game. LOSE if Koa will lose the game. DRAW if the game ends in a draw. ExamplesInput 3 3 1 2 2 3 2 2 3 5 0 0 0 2 2 Output WIN LOSE DRAW Input 4 5 4 1 5 1 3 4 1 0 1 6 1 0 2 5 4 Output WIN WIN DRAW WIN NoteIn testcase 1 of the first sample we have:a = [1, 2, 2]. Here Koa chooses 1, other player has to choose 2, Koa chooses another 2. Score for Koa is 1 \oplus 2 = 3 and score for other player is 2 so Koa wins.
3 3 1 2 2 3 2 2 3 5 0 0 0 2 2
WIN LOSE DRAW
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'dp', 'games', 'greedy', 'math', '*1900']
A. String Transformation 1time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNote that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions p_1, p_2, \ldots, p_k (k \ge 1; 1 \le p_i \le n; p_i \neq p_j if i \neq j) of A such that A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). sets each letter in positions p_1, p_2, \ldots, p_k to letter y. More formally: for each i (1 \le i \le k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A.Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!InputEach test contains multiple test cases. The first line contains t (1 \le t \le 10) — the number of test cases. Description of the test cases follows.The first line of each test case contains one integer n (1 \le n \le 10^5) — the length of strings A and B.The second line of each test case contains string A (|A|=n).The third line of each test case contains string B (|B|=n).Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case:Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal.ExampleInput 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note In the 1-st test case Koa: selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b \rightarrow \color{blue}{bb}b). selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} \rightarrow b\color{blue}{cc}). In the 2-nd test case Koa has no way to make string A equal B. In the 3-rd test case Koa: selects position 1 and sets A_1 = t (\color{red}{a}bc \rightarrow \color{blue}{t}bc). selects position 2 and sets A_2 = s (t\color{red}{b}c \rightarrow t\color{blue}{s}c). selects position 3 and sets A_3 = r (ts\color{red}{c} \rightarrow ts\color{blue}{r}).
5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda
2 -1 3 2 -1
1 second
256 megabytes
['dsu', 'graphs', 'greedy', 'sortings', 'strings', 'trees', 'two pointers', '*1700']
B. Sequential Nimtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones.In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who cannot make a move (because all piles are empty) loses the game. If both players play optimally, determine the winner of the game.InputThe first line contains a single integer t (1\le t\le 1000)  — the number of test cases. Next 2t lines contain descriptions of test cases.The first line of each test case contains a single integer n (1\le n\le 10^5)  — the number of piles.The second line of each test case contains n integers a_1,\ldots,a_n (1\le a_i\le 10^9)  — a_i is equal to the number of stones in the i-th pile.It is guaranteed that the sum of n for all test cases does not exceed 10^5.OutputFor each test case, if the player who makes the first move will win, output "First". Otherwise, output "Second".ExampleInput 7 3 2 5 4 8 1 1 1 1 1 1 1 1 6 1 2 3 4 5 6 6 1 1 2 1 2 2 1 1000000000 5 1 2 2 1 1 3 1 1 1 Output First Second Second First First Second First NoteIn the first test case, the first player will win the game. His winning strategy is: The first player should take the stones from the first pile. He will take 1 stone. The numbers of stones in piles will be [1, 5, 4]. The second player should take the stones from the first pile. He will take 1 stone because he can't take any other number of stones. The numbers of stones in piles will be [0, 5, 4]. The first player should take the stones from the second pile because the first pile is empty. He will take 4 stones. The numbers of stones in piles will be [0, 1, 4]. The second player should take the stones from the second pile because the first pile is empty. He will take 1 stone because he can't take any other number of stones. The numbers of stones in piles will be [0, 0, 4]. The first player should take the stones from the third pile because the first and second piles are empty. He will take 4 stones. The numbers of stones in piles will be [0, 0, 0]. The second player will lose the game because all piles will be empty.
7 3 2 5 4 8 1 1 1 1 1 1 1 1 6 1 2 3 4 5 6 6 1 1 2 1 2 2 1 1000000000 5 1 2 2 1 1 3 1 1 1
First Second Second First First Second First
1 second
256 megabytes
['dp', 'games', '*1100']
A. Common Subsequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays of integers a_1,\ldots,a_n and b_1,\ldots,b_m.Your task is to find a non-empty array c_1,\ldots,c_k that is a subsequence of a_1,\ldots,a_n, and also a subsequence of b_1,\ldots,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero) elements. For example, [3,1] is a subsequence of [3,2,1] and [4,3,1], but not a subsequence of [1,3,3,7] and [3,10,4].InputThe first line contains a single integer t (1\le t\le 1000)  — the number of test cases. Next 3t lines contain descriptions of test cases.The first line of each test case contains two integers n and m (1\le n,m\le 1000)  — the lengths of the two arrays.The second line of each test case contains n integers a_1,\ldots,a_n (1\le a_i\le 1000)  — the elements of the first array.The third line of each test case contains m integers b_1,\ldots,b_m (1\le b_i\le 1000)  — the elements of the second array.It is guaranteed that the sum of n and the sum of m across all test cases does not exceed 1000 (\sum\limits_{i=1}^t n_i, \sum\limits_{i=1}^t m_i\le 1000).OutputFor each test case, output "YES" if a solution exists, or "NO" otherwise.If the answer is "YES", on the next line output an integer k (1\le k\le 1000)  — the length of the array, followed by k integers c_1,\ldots,c_k (1\le c_i\le 1000)  — the elements of the array.If there are multiple solutions with the smallest possible k, output any.ExampleInput 5 4 5 10 8 6 4 1 2 3 4 5 1 1 3 3 1 1 3 2 5 3 1000 2 2 2 3 3 1 5 5 5 1 2 3 4 5 1 2 3 4 5 Output YES 1 4 YES 1 3 NO YES 1 3 YES 1 2 NoteIn the first test case, [4] is a subsequence of [10, 8, 6, 4] and [1, 2, 3, 4, 5]. This array has length 1, it is the smallest possible length of a subsequence of both a and b.In the third test case, no non-empty subsequences of both [3] and [2] exist, so the answer is "NO".
5 4 5 10 8 6 4 1 2 3 4 5 1 1 3 3 1 1 3 2 5 3 1000 2 2 2 3 3 1 5 5 5 1 2 3 4 5 1 2 3 4 5
YES 1 4 YES 1 3 NO YES 1 3 YES 1 2
1 second
256 megabytes
['brute force', '*800']
E. Origamitime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter being discouraged by 13 time-limit-exceeded verdicts on an ugly geometry problem, you decided to take a relaxing break for arts and crafts.There is a piece of paper in the shape of a simple polygon with n vertices. The polygon may be non-convex, but we all know that proper origami paper has the property that any horizontal line intersects the boundary of the polygon in at most two points.If you fold the paper along the vertical line x=f, what will be the area of the resulting shape? When you fold, the part of the paper to the left of the line is symmetrically reflected on the right side. Your task is to answer q independent queries for values f_1,\ldots,f_q.InputThe first line contains two integers n, q (3\le n\le 10^5, 1\le q\le 10^5)  — the number of polygon vertices and queries, respectively.Each of the next n lines contains two integers x_i, y_i (|x_i|, |y_i|\le 10^5)  — the coordinates of the i-th point of the polygon. The polygon has an edge connecting each pair of adjacent points in the input, and also an edge between (x_1,y_1) and (x_n,y_n). It is guaranteed that the polygon is non-degenerate and that any horizontal line intersects the boundary of the polygon in at most two points. In particular, no boundary edge is strictly horizontal. Two adjacent sides may be collinear.Each of the next q lines contains a single integer f_i (\min\limits_{j=1}^n(x_j)< f_i< \max\limits_{j=1}^n(x_j))  — the x-coordinate of the i-th fold query. It is guaranteed that all f_i are distinct.OutputFor each query, output the area A_i of the paper if you fold it along the line x=f_i.Your answer is considered correct if its absolute or relative error does not exceed 10^{-4}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-4}.ExamplesInput 4 7 0 10 10 0 0 -10 -10 0 -9 -5 -1 0 1 5 9 Output 199.0000000000 175.0000000000 119.0000000000 100.0000000000 119.0000000000 175.0000000000 199.0000000000 Input 4 1 0 0 0 2 2 4 2 2 1 Output 3.0000000000 Input 9 4 0 -3 2 -2 -1 -1 0 4 2 5 1 6 -2 3 -1 1 -3 0 0 -2 -1 1 Output 11.1250000000 11.7500000000 10.3446969697 11.3333333333 NoteThe first test, with the fold f=-5: The second test, with the fold f=1: The third test, with the fold f=-1:
4 7 0 10 10 0 0 -10 -10 0 -9 -5 -1 0 1 5 9
199.0000000000 175.0000000000 119.0000000000 100.0000000000 119.0000000000 175.0000000000 199.0000000000
4 seconds
256 megabytes
['geometry', 'math', 'sortings', '*3300']
D. The Majestic Brown Tree Snaketime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an undirected tree of n vertices, connected by n-1 bidirectional edges. There is also a snake stuck inside of this tree. Its head is at vertex a and its tail is at vertex b. The snake's body occupies all vertices on the unique simple path between a and b.The snake wants to know if it can reverse itself  — that is, to move its head to where its tail started, and its tail to where its head started. Unfortunately, the snake's movements are restricted to the tree's structure.In an operation, the snake can move its head to an adjacent vertex not currently occupied by the snake. When it does this, the tail moves one vertex closer to the head, so that the length of the snake remains unchanged. Similarly, the snake can also move its tail to an adjacent vertex not currently occupied by the snake. When it does this, the head moves one unit closer to the tail. Let's denote a snake position by (h,t), where h is the index of the vertex with the snake's head, t is the index of the vertex with the snake's tail. This snake can reverse itself with the movements (4,7)\to (5,1)\to (4,2)\to (1, 3)\to (7,2)\to (8,1)\to (7,4). Determine if it is possible to reverse the snake with some sequence of operations.InputThe first line contains a single integer t (1\le t\le 100)  — the number of test cases. The next lines contain descriptions of test cases.The first line of each test case contains three integers n,a,b (2\le n\le 10^5,1\le a,b\le n,a\ne b).Each of the next n-1 lines contains two integers u_i,v_i (1\le u_i,v_i\le n,u_i\ne v_i), indicating an edge between vertices u_i and v_i. It is guaranteed that the given edges form a tree.It is guaranteed that the sum of n across all test cases does not exceed 10^5.OutputFor each test case, output "YES" if it is possible for the snake to reverse itself, or "NO" otherwise.ExampleInput 4 8 4 7 1 2 2 3 1 4 4 5 4 6 1 7 7 8 4 3 2 4 3 1 2 2 3 9 3 5 1 2 2 3 3 4 1 5 5 6 6 7 1 8 8 9 16 15 12 1 2 2 3 1 4 4 5 5 6 6 7 4 8 8 9 8 10 10 11 11 12 11 13 13 14 10 15 15 16 Output YES NO NO YES NoteThe first test case is pictured above.In the second test case, the tree is a path. We can show that the snake cannot reverse itself.In the third test case, we can show that the snake cannot reverse itself.In the fourth test case, an example solution is:(15,12)\to (16,11)\to (15,13)\to (10,14)\to (8,13)\to (4,11)\to (1,10)\to (2,8)\to (3,4)\to (2,5)\to (1,6)\to (4,7)\to (8,6)\to (10,5)\to (11,4)\to (13,8)\to (14,10)\to (13,15)\to (11,16)\to (12,15).
4 8 4 7 1 2 2 3 1 4 4 5 4 6 1 7 7 8 4 3 2 4 3 1 2 2 3 9 3 5 1 2 2 3 3 4 1 5 5 6 6 7 1 8 8 9 16 15 12 1 2 2 3 1 4 4 5 5 6 6 7 4 8 8 9 8 10 10 11 11 12 11 13 13 14 10 15 15 16
YES NO NO YES
1 second
256 megabytes
['dfs and similar', 'dp', 'greedy', 'trees', 'two pointers', '*3000']
C. Mastermindtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the game of Mastermind, there are two players  — Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive.When Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers x and y.The first integer x is the number of indices where Bob's guess correctly matches Alice's code. The second integer y is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, y is the maximum number of indices he could get correct.For example, suppose n=5, Alice's code is [3,1,6,1,2], and Bob's guess is [3,1,1,2,5]. At indices 1 and 2 colors are equal, while in the other indices they are not equal. So x=2. And the two codes have the four colors 1,1,2,3 in common, so y=4. Solid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. x is the number of solid lines, and y is the total number of lines. You are given Bob's guess and two values x and y. Can you find one possibility of Alice's code so that the values of x and y are correct?InputThe first line contains a single integer t (1\le t\le 1000)  — the number of test cases. Next 2t lines contain descriptions of test cases.The first line of each test case contains three integers n,x,y (1\le n\le 10^5, 0\le x\le y\le n)  — the length of the codes, and two values Alice responds with.The second line of each test case contains n integers b_1,\ldots,b_n (1\le b_i\le n+1)  — Bob's guess, where b_i is the i-th color of the guess.It is guaranteed that the sum of n across all test cases does not exceed 10^5.OutputFor each test case, on the first line, output "YES" if there is a solution, or "NO" if there is no possible secret code consistent with the described situation. You can print each character in any case (upper or lower).If the answer is "YES", on the next line output n integers a_1,\ldots,a_n (1\le a_i\le n+1)  — Alice's secret code, where a_i is the i-th color of the code.If there are multiple solutions, output any.ExampleInput 7 5 2 4 3 1 1 2 5 5 3 4 1 1 2 1 2 4 0 4 5 5 3 3 4 1 4 2 3 2 3 6 1 2 3 2 1 1 1 1 6 2 4 3 3 2 1 1 1 6 2 6 1 1 3 2 1 1 Output YES 3 1 6 1 2 YES 3 1 1 1 2 YES 3 3 5 5 NO YES 4 4 4 4 3 1 YES 3 1 3 1 7 7 YES 2 3 1 1 1 1 NoteThe first test case is described in the statement.In the second test case, x=3 because the colors are equal at indices 2,4,5. And y=4 because they share the colors 1,1,1,2.In the third test case, x=0 because there is no index where the colors are the same. But y=4 because they share the colors 3,3,5,5.In the fourth test case, it can be proved that no solution exists.
7 5 2 4 3 1 1 2 5 5 3 4 1 1 2 1 2 4 0 4 5 5 3 3 4 1 4 2 3 2 3 6 1 2 3 2 1 1 1 1 6 2 4 3 3 2 1 1 1 6 2 6 1 1 3 2 1 1
YES 3 1 6 1 2 YES 3 1 1 1 2 YES 3 3 5 5 NO YES 4 4 4 4 3 1 YES 3 1 3 1 7 7 YES 2 3 1 1 1 1
1 second
256 megabytes
['constructive algorithms', 'graph matchings', 'greedy', 'implementation', 'sortings', 'two pointers', '*2500']
B. Unmergetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet a and b be two arrays of lengths n and m, respectively, with no elements in common. We can define a new array \mathrm{merge}(a,b) of length n+m recursively as follows: If one of the arrays is empty, the result is the other array. That is, \mathrm{merge}(\emptyset,b)=b and \mathrm{merge}(a,\emptyset)=a. In particular, \mathrm{merge}(\emptyset,\emptyset)=\emptyset. If both arrays are non-empty, and a_1<b_1, then \mathrm{merge}(a,b)=[a_1]+\mathrm{merge}([a_2,\ldots,a_n],b). That is, we delete the first element a_1 of a, merge the remaining arrays, then add a_1 to the beginning of the result. If both arrays are non-empty, and a_1>b_1, then \mathrm{merge}(a,b)=[b_1]+\mathrm{merge}(a,[b_2,\ldots,b_m]). That is, we delete the first element b_1 of b, merge the remaining arrays, then add b_1 to the beginning of the result. This algorithm has the nice property that if a and b are sorted, then \mathrm{merge}(a,b) will also be sorted. For example, it is used as a subroutine in merge-sort. For this problem, however, we will consider the same procedure acting on non-sorted arrays as well. For example, if a=[3,1] and b=[2,4], then \mathrm{merge}(a,b)=[2,3,1,4].A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).There is a permutation p of length 2n. Determine if there exist two arrays a and b, each of length n and with no elements in common, so that p=\mathrm{merge}(a,b).InputThe first line contains a single integer t (1\le t\le 1000)  — the number of test cases. Next 2t lines contain descriptions of test cases. The first line of each test case contains a single integer n (1\le n\le 2000).The second line of each test case contains 2n integers p_1,\ldots,p_{2n} (1\le p_i\le 2n). It is guaranteed that p is a permutation.It is guaranteed that the sum of n across all test cases does not exceed 2000.OutputFor each test case, output "YES" if there exist arrays a, b, each of length n and with no common elements, so that p=\mathrm{merge}(a,b). Otherwise, output "NO".ExampleInput 6 2 2 3 1 4 2 3 1 2 4 4 3 2 6 1 5 7 8 4 3 1 2 3 4 5 6 4 6 1 3 7 4 5 8 2 6 4 3 2 5 1 11 9 12 8 6 10 7 Output YES NO YES YES NO NO NoteIn the first test case, [2,3,1,4]=\mathrm{merge}([3,1],[2,4]).In the second test case, we can show that [3,1,2,4] is not the merge of two arrays of length 2.In the third test case, [3,2,6,1,5,7,8,4]=\mathrm{merge}([3,2,8,4],[6,1,5,7]).In the fourth test case, [1,2,3,4,5,6]=\mathrm{merge}([1,3,6],[2,4,5]), for example.
6 2 2 3 1 4 2 3 1 2 4 4 3 2 6 1 5 7 8 4 3 1 2 3 4 5 6 4 6 1 3 7 4 5 8 2 6 4 3 2 5 1 11 9 12 8 6 10 7
YES NO YES YES NO NO
1 second
256 megabytes
['dp', '*1800']
A2. Prefix Flip (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In an operation, you select a prefix of a, and simultaneously invert the bits in the prefix (0 changes to 1 and 1 changes to 0) and reverse the order of the bits in the prefix.For example, if a=001011 and you select the prefix of length 3, it becomes 011011. Then if you select the entire string, it becomes 001001.Your task is to transform the string a into b in at most 2n operations. It can be proved that it is always possible.InputThe first line contains a single integer t (1\le t\le 1000)  — the number of test cases. Next 3t lines contain descriptions of test cases.The first line of each test case contains a single integer n (1\le n\le 10^5)  — the length of the binary strings.The next two lines contain two binary strings a and b of length n.It is guaranteed that the sum of n across all test cases does not exceed 10^5.OutputFor each test case, output an integer k (0\le k\le 2n), followed by k integers p_1,\ldots,p_k (1\le p_i\le n). Here k is the number of operations you use and p_i is the length of the prefix you flip in the i-th operation.ExampleInput 5 2 01 10 5 01011 11100 2 01 01 10 0110011011 1000110100 1 0 1 Output 3 1 2 1 6 5 2 5 3 1 2 0 9 4 1 2 10 4 1 2 1 5 1 1 NoteIn the first test case, we have 01\to 11\to 00\to 10.In the second test case, we have 01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100.In the third test case, the strings are already the same. Another solution is to flip the prefix of length 2, which will leave a unchanged.
5 2 01 10 5 01011 11100 2 01 01 10 0110011011 1000110100 1 0 1
3 1 2 1 6 5 2 5 3 1 2 0 9 4 1 2 10 4 1 2 1 5 1 1
1 second
256 megabytes
['constructive algorithms', 'data structures', 'implementation', 'strings', 'two pointers', '*1700']
A1. Prefix Flip (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In an operation, you select a prefix of a, and simultaneously invert the bits in the prefix (0 changes to 1 and 1 changes to 0) and reverse the order of the bits in the prefix.For example, if a=001011 and you select the prefix of length 3, it becomes 011011. Then if you select the entire string, it becomes 001001.Your task is to transform the string a into b in at most 3n operations. It can be proved that it is always possible.InputThe first line contains a single integer t (1\le t\le 1000)  — the number of test cases. Next 3t lines contain descriptions of test cases.The first line of each test case contains a single integer n (1\le n\le 1000)  — the length of the binary strings.The next two lines contain two binary strings a and b of length n.It is guaranteed that the sum of n across all test cases does not exceed 1000.OutputFor each test case, output an integer k (0\le k\le 3n), followed by k integers p_1,\ldots,p_k (1\le p_i\le n). Here k is the number of operations you use and p_i is the length of the prefix you flip in the i-th operation.ExampleInput 5 2 01 10 5 01011 11100 2 01 01 10 0110011011 1000110100 1 0 1 Output 3 1 2 1 6 5 2 5 3 1 2 0 9 4 1 2 10 4 1 2 1 5 1 1 NoteIn the first test case, we have 01\to 11\to 00\to 10.In the second test case, we have 01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100.In the third test case, the strings are already the same. Another solution is to flip the prefix of length 2, which will leave a unchanged.
5 2 01 10 5 01011 11100 2 01 01 10 0110011011 1000110100 1 0 1
3 1 2 1 6 5 2 5 3 1 2 0 9 4 1 2 10 4 1 2 1 5 1 1
1 second
256 megabytes
['constructive algorithms', 'data structures', 'strings', '*1300']
G. Circular Dungeontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are creating a level for a video game. The level consists of n rooms placed in a circle. The rooms are numbered 1 through n. Each room contains exactly one exit: completing the j-th room allows you to go the (j+1)-th room (and completing the n-th room allows you to go the 1-st room).You are given the description of the multiset of n chests: the i-th chest has treasure value c_i.Each chest can be of one of two types: regular chest — when a player enters a room with this chest, he grabs the treasure and proceeds to the next room; mimic chest — when a player enters a room with this chest, the chest eats him alive, and he loses. The player starts in a random room with each room having an equal probability of being chosen. The players earnings is equal to the total value of treasure chests he'd collected before he lost.You are allowed to choose the order the chests go into the rooms. For each k from 1 to n place the chests into the rooms in such a way that: each room contains exactly one chest; exactly k chests are mimics; the expected value of players earnings is minimum possible. Please note that for each k the placement is chosen independently.It can be shown that it is in the form of \frac{P}{Q} where P and Q are non-negative integers and Q \ne 0. Report the values of P \cdot Q^{-1} \pmod {998244353}.InputThe first contains a single integer n (2 \le n \le 3 \cdot 10^5) — the number of rooms and the number of chests.The second line contains n integers c_1, c_2, \dots, c_n (1 \le c_i \le 10^6) — the treasure values of each chest.OutputPrint n integers — the k -th value should be equal to the minimum possible expected value of players earnings if the chests are placed into the rooms in some order and exactly k of the chests are mimics.It can be shown that it is in the form of \frac{P}{Q} where P and Q are non-negative integers and Q \ne 0. Report the values of P \cdot Q^{-1} \pmod {998244353}.ExamplesInput 2 1 2 Output 499122177 0 Input 8 10 4 3 6 5 10 7 5 Output 499122193 249561095 249561092 873463811 499122178 124780545 623902721 0 NoteIn the first example the exact values of minimum expected values are: \frac 1 2, \frac 0 2.In the second example the exact values of minimum expected values are: \frac{132} 8, \frac{54} 8, \frac{30} 8, \frac{17} 8, \frac{12} 8, \frac 7 8, \frac 3 8, \frac 0 8.
2 1 2
499122177 0
2 seconds
256 megabytes
['greedy', 'math', 'probabilities', '*2600']
F. Strange Additiontime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet a and b be some non-negative integers. Let's define strange addition of a and b as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers 3248 and 908: You are given a string c, consisting of n digits from 0 to 9. You are also given m updates of form: x~d — replace the digit at the x-th position of c with a digit d. Note that string c might have leading zeros at any point of time.After each update print the number of pairs (a, b) such that both a and b are non-negative integers and the result of a strange addition of a and b is equal to c.Note that the numbers of pairs can be quite large, so print them modulo 998244353.InputThe first line contains two integers n and m (1 \le n, m \le 5 \cdot 10^5) — the length of the number c and the number of updates.The second line contains a string c, consisting of exactly n digits from 0 to 9.Each of the next m lines contains two integers x and d (1 \le x \le n, 0 \le d \le 9) — the descriptions of updates.OutputPrint m integers — the i-th value should be equal to the number of pairs (a, b) such that both a and b are non-negative integers and the result of a strange addition of a and b is equal to c after i updates are applied.Note that the numbers of pairs can be quite large, so print them modulo 998244353.ExampleInput 2 3 14 2 4 2 1 1 0 Output 15 12 2 NoteAfter the first update c is equal to 14. The pairs that sum up to 14 are: (0, 14), (1, 13), (2, 12), (3, 11), (4, 10), (5, 9), (6, 8), (7, 7), (8, 6), (9, 5), (10, 4), (11, 3), (12, 2), (13, 1), (14, 0).After the second update c is equal to 11.After the third update c is equal to 01.
2 3 14 2 4 2 1 1 0
15 12 2
5 seconds
256 megabytes
['data structures', 'dp', 'matrices', '*2600']
E. Merging Towerstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have a set of n discs, the i-th disc has radius i. Initially, these discs are split among m towers: each tower contains at least one disc, and the discs in each tower are sorted in descending order of their radii from bottom to top.You would like to assemble one tower containing all of those discs. To do so, you may choose two different towers i and j (each containing at least one disc), take several (possibly all) top discs from the tower i and put them on top of the tower j in the same order, as long as the top disc of tower j is bigger than each of the discs you move. You may perform this operation any number of times.For example, if you have two towers containing discs [6, 4, 2, 1] and [8, 7, 5, 3] (in order from bottom to top), there are only two possible operations: move disc 1 from the first tower to the second tower, so the towers are [6, 4, 2] and [8, 7, 5, 3, 1]; move discs [2, 1] from the first tower to the second tower, so the towers are [6, 4] and [8, 7, 5, 3, 2, 1]. Let the difficulty of some set of towers be the minimum number of operations required to assemble one tower containing all of the discs. For example, the difficulty of the set of towers [[3, 1], [2]] is 2: you may move the disc 1 to the second tower, and then move both discs from the second tower to the first tower.You are given m - 1 queries. Each query is denoted by two numbers a_i and b_i, and means "merge the towers a_i and b_i" (that is, take all discs from these two towers and assemble a new tower containing all of them in descending order of their radii from top to bottom). The resulting tower gets index a_i.For each k \in [0, m - 1], calculate the difficulty of the set of towers after the first k queries are performed.InputThe first line of the input contains two integers n and m (2 \le m \le n \le 2 \cdot 10^5) — the number of discs and the number of towers, respectively.The second line contains n integers t_1, t_2, ..., t_n (1 \le t_i \le m), where t_i is the index of the tower disc i belongs to. Each value from 1 to m appears in this sequence at least once.Then m - 1 lines follow, denoting the queries. Each query is represented by two integers a_i and b_i (1 \le a_i, b_i \le m, a_i \ne b_i), meaning that, during the i-th query, the towers with indices a_i and b_i are merged (a_i and b_i are chosen in such a way that these towers exist before the i-th query).OutputPrint m integers. The k-th integer (0-indexed) should be equal to the difficulty of the set of towers after the first k queries are performed.ExampleInput 7 4 1 2 3 3 1 4 3 3 1 2 3 2 4 Output 5 4 2 0 NoteThe towers in the example are: before the queries: [[5, 1], [2], [7, 4, 3], [6]]; after the first query: [[2], [7, 5, 4, 3, 1], [6]]; after the second query: [[7, 5, 4, 3, 2, 1], [6]]; after the third query, there is only one tower: [7, 6, 5, 4, 3, 2, 1].
7 4 1 2 3 3 1 4 3 3 1 2 3 2 4
5 4 2 0
2 seconds
512 megabytes
['data structures', 'dsu', 'implementation', 'trees', '*2300']
D. Berserk And Fireballtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n warriors in a row. The power of the i-th warrior is a_i. All powers are pairwise distinct.You have two types of spells which you may cast: Fireball: you spend x mana and destroy exactly k consecutive warriors; Berserk: you spend y mana, choose two consecutive warriors, and the warrior with greater power destroys the warrior with smaller power. For example, let the powers of warriors be [2, 3, 7, 8, 11, 5, 4], and k = 3. If you cast Berserk on warriors with powers 8 and 11, the resulting sequence of powers becomes [2, 3, 7, 11, 5, 4]. Then, for example, if you cast Fireball on consecutive warriors with powers [7, 11, 5], the resulting sequence of powers becomes [2, 3, 4].You want to turn the current sequence of warriors powers a_1, a_2, \dots, a_n into b_1, b_2, \dots, b_m. Calculate the minimum amount of mana you need to spend on it.InputThe first line contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the length of sequence a and the length of sequence b respectively.The second line contains three integers x, k, y (1 \le x, y, \le 10^9; 1 \le k \le n) — the cost of fireball, the range of fireball and the cost of berserk respectively.The third line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n). It is guaranteed that all integers a_i are pairwise distinct.The fourth line contains m integers b_1, b_2, \dots, b_m (1 \le b_i \le n). It is guaranteed that all integers b_i are pairwise distinct.OutputPrint the minimum amount of mana for turning the sequnce a_1, a_2, \dots, a_n into b_1, b_2, \dots, b_m, or -1 if it is impossible.ExamplesInput 5 2 5 2 3 3 1 4 5 2 3 5 Output 8 Input 4 4 5 1 4 4 3 1 2 2 4 3 1 Output -1 Input 4 4 2 1 11 1 3 2 4 1 3 2 4 Output 0
5 2 5 2 3 3 1 4 5 2 3 5
8
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', 'two pointers', '*2000']
C. Create The Teamstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n programmers that you want to split into several non-empty teams. The skill of the i-th programmer is a_i. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team must be at least x.Each programmer should belong to at most one team. Some programmers may be left without a team.Calculate the maximum number of teams that you can assemble.InputThe first line contains the integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains two integers n and x (1 \le n \le 10^5; 1 \le x \le 10^9) — the number of programmers and the restriction of team skill respectively.The second line of each test case contains n integers a_1, a_2, \dots , a_n (1 \le a_i \le 10^9), where a_i is the skill of the i-th programmer.The sum of n over all inputs does not exceed 10^5.OutputFor each test case print one integer — the maximum number of teams that you can assemble. ExampleInput 3 5 10 7 11 2 9 5 4 8 2 4 2 3 4 11 1 3 3 7 Output 2 1 0
3 5 10 7 11 2 9 5 4 8 2 4 2 3 4 11 1 3 3 7
2 1 0
2 seconds
256 megabytes
['brute force', 'dp', 'greedy', 'implementation', 'sortings', '*1400']
B. Universal Solutiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string s = s_1 s_2 \dots s_{n} of length n where each letter is either R, S or P.While initializing, the bot is choosing a starting index pos (1 \le pos \le n), and then it can play any number of rounds. In the first round, he chooses "Rock", "Scissors" or "Paper" based on the value of s_{pos}: if s_{pos} is equal to R the bot chooses "Rock"; if s_{pos} is equal to S the bot chooses "Scissors"; if s_{pos} is equal to P the bot chooses "Paper"; In the second round, the bot's choice is based on the value of s_{pos + 1}. In the third round — on s_{pos + 2} and so on. After s_n the bot returns to s_1 and continues his game.You plan to play n rounds and you've already figured out the string s but still don't know what is the starting index pos. But since the bot's tactic is so boring, you've decided to find n choices to each round to maximize the average number of wins.In other words, let's suggest your choices are c_1 c_2 \dots c_n and if the bot starts from index pos then you'll win in win(pos) rounds. Find c_1 c_2 \dots c_n such that \frac{win(1) + win(2) + \dots + win(n)}{n} is maximum possible.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.Next t lines contain test cases — one per line. The first and only line of each test case contains string s = s_1 s_2 \dots s_{n} (1 \le n \le 2 \cdot 10^5; s_i \in \{\text{R}, \text{S}, \text{P}\}) — the string of the bot.It's guaranteed that the total length of all strings in one test doesn't exceed 2 \cdot 10^5.OutputFor each test case, print n choices c_1 c_2 \dots c_n to maximize the average number of wins. Print them in the same manner as the string s.If there are multiple optimal answers, print any of them.ExampleInput 3 RRRR RSP S Output PPPP RSP RNoteIn the first test case, the bot (wherever it starts) will always choose "Rock", so we can always choose "Paper". So, in any case, we will win all n = 4 rounds, so the average is also equal to 4.In the second test case: if bot will start from pos = 1, then (s_1, c_1) is draw, (s_2, c_2) is draw and (s_3, c_3) is draw, so win(1) = 0; if bot will start from pos = 2, then (s_2, c_1) is win, (s_3, c_2) is win and (s_1, c_3) is win, so win(2) = 3; if bot will start from pos = 3, then (s_3, c_1) is lose, (s_1, c_2) is lose and (s_2, c_3) is lose, so win(3) = 0; The average is equal to \frac{0 + 3 + 0}{3} = 1 and it can be proven that it's the maximum possible average.A picture from Wikipedia explaining "Rock paper scissors" game:
3 RRRR RSP S
PPPP RSP R
2 seconds
256 megabytes
['greedy', '*1400']
A. Three Indicestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p_1, p_2, \dots, p_n. Recall that sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.Find three indices i, j and k such that: 1 \le i < j < k \le n; p_i < p_j and p_j > p_k. Or say that there are no such indices.InputThe first line contains a single integer T (1 \le T \le 200) — the number of test cases.Next 2T lines contain test cases — two lines per test case. The first line of each test case contains the single integer n (3 \le n \le 1000) — the length of the permutation p.The second line contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n; p_i \neq p_j if i \neq j) — the permutation p.OutputFor each test case: if there are such indices i, j and k, print YES (case insensitive) and the indices themselves; if there are no such indices, print NO (case insensitive). If there are multiple valid triples of indices, print any of them.ExampleInput 3 4 2 1 4 3 6 4 6 1 2 5 3 5 5 3 1 2 4 Output YES 2 3 4 YES 3 5 6 NO
3 4 2 1 4 3 6 4 6 1 2 5 3 5 5 3 1 2 4
YES 2 3 4 YES 3 5 6 NO
2 seconds
256 megabytes
['brute force', 'data structures', '*900']
F2. Chess Strikes Back (hard version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputNote that the difference between easy and hard versions is that in hard version unavailable cells can become available again and in easy version can't. You can make hacks only if all versions are solved.Ildar and Ivan are tired of chess, but they really like the chessboard, so they invented a new game. The field is a chessboard 2n \times 2m: it has 2n rows, 2m columns, and the cell in row i and column j is colored white if i+j is even, and is colored black otherwise.The game proceeds as follows: Ildar marks some of the white cells of the chessboard as unavailable, and asks Ivan to place n \times m kings on the remaining white cells in such way, so that there are no kings attacking each other. A king can attack another king if they are located in the adjacent cells, sharing an edge or a corner.Ildar would like to explore different combinations of cells. Initially all cells are marked as available, and then he has q queries. In each query he either marks a cell as unavailable, or marks the previously unavailable cell as available. After each query he would like to know whether it is possible to place the kings on the available cells in a desired way. Please help him!InputThe first line of input contains three integers n, m, q (1 \leq n, m, q \leq 200\,000) — the size of the board and the number of queries.q lines follow, each of them contains a description of a query: two integers i and j, denoting a white cell on the board (1 \leq i \leq 2n, 1 \leq j \leq 2m, i + j is even). If the cell (i, j) was available before the query, then it becomes unavailable. Otherwise, if the cell was unavailable, it becomes available.OutputOutput q lines, i-th line should contain answer for a board after i queries of Ildar. This line should contain "YES" if it is possible to place the kings on the available cells in the desired way, or "NO" otherwise.ExamplesInput 1 3 3 1 1 1 5 2 4 Output YES YES NO Input 3 2 10 4 2 6 4 1 3 4 2 6 4 2 2 2 4 1 3 4 4 3 1 Output YES YES NO NO YES YES NO YES YES NO NoteIn the first example case after the second query only cells (1, 1) and (1, 5) are unavailable. Then Ivan can place three kings on cells (2, 2), (2, 4) and (2, 6).After the third query three cells (1, 1), (1, 5) and (2, 4) are unavailable, so there remain only 3 available cells: (2, 2), (1, 3) and (2, 6). Ivan can not put 3 kings on those cells, because kings on cells (2, 2) and (1, 3) attack each other, since these cells share a corner.
1 3 3 1 1 1 5 2 4
YES YES NO
2 seconds
512 megabytes
['data structures', 'divide and conquer', '*2800']
F1. Chess Strikes Back (easy version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputNote that the difference between easy and hard versions is that in hard version unavailable cells can become available again and in easy version can't. You can make hacks only if all versions are solved.Ildar and Ivan are tired of chess, but they really like the chessboard, so they invented a new game. The field is a chessboard 2n \times 2m: it has 2n rows, 2m columns, and the cell in row i and column j is colored white if i+j is even, and is colored black otherwise.The game proceeds as follows: Ildar marks some of the white cells of the chessboard as unavailable, and asks Ivan to place n \times m kings on the remaining white cells in such way, so that there are no kings attacking each other. A king can attack another king if they are located in the adjacent cells, sharing an edge or a corner.Ildar would like to explore different combinations of cells. Initially all cells are marked as available, and then he has q queries. In each query he marks a cell as unavailable. After each query he would like to know whether it is possible to place the kings on the available cells in a desired way. Please help him!InputThe first line of input contains three integers n, m, q (1 \leq n, m, q \leq 200\,000) — the size of the board and the number of queries.q lines follow, each of them contains a description of a query: two integers i and j, denoting a white cell (i, j) on the board (1 \leq i \leq 2n, 1 \leq j \leq 2m, i + j is even) that becomes unavailable. It's guaranteed, that each cell (i, j) appears in input at most once.OutputOutput q lines, i-th line should contain answer for a board after i queries of Ildar. This line should contain "YES" if it is possible to place the kings on the available cells in the desired way, or "NO" otherwise.ExamplesInput 1 3 3 1 1 1 5 2 4 Output YES YES NO Input 3 2 7 4 2 6 4 1 3 2 2 2 4 4 4 3 1 Output YES YES NO NO NO NO NO NoteIn the first example case after the second query only cells (1, 1) and (1, 5) are unavailable. Then Ivan can place three kings on cells (2, 2), (2, 4) and (2, 6).After the third query three cells (1, 1), (1, 5) and (2, 4) are unavailable, so there remain only 3 available cells: (2, 2), (1, 3) and (2, 6). Ivan can not put 3 kings on those cells, because kings on cells (2, 2) and (1, 3) attack each other, since these cells share a corner.
1 3 3 1 1 1 5 2 4
YES YES NO
2 seconds
512 megabytes
['binary search', 'data structures', '*2700']
E. Inverse Genealogytime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputIvan is fond of genealogy. Currently he is studying a particular genealogical structure, which consists of some people. In this structure every person has either both parents specified, or none. Additionally, each person has exactly one child, except for one special person, who does not have any children. The people in this structure are conveniently numbered from 1 to n, and s_i denotes the child of the person i (and s_i = 0 for exactly one person who does not have any children).We say that a is an ancestor of b if either a = b, or a has a child, who is an ancestor of b. That is a is an ancestor for a, s_a, s_{s_a}, etc.We say that person i is imbalanced in case this person has both parents specified, and the total number of ancestors of one of the parents is at least double the other. Ivan counted the number of imbalanced people in the structure, and got k people in total. However, he is not sure whether he computed it correctly, and would like to check if there is at least one construction with n people that have k imbalanced people in total. Please help him to find one such construction, or determine if it does not exist.InputThe input contains two integers n and k (1 \leq n \leq 100\,000, 0 \leq k \leq n), the total number of people and the number of imbalanced people.OutputIf there are no constructions with n people and k imbalanced people, output NO.Otherwise output YES on the first line, and then n integers s_1, s_2, \ldots, s_n (0 \leq s_i \leq n), which describes the construction and specify the child of each node (or 0, if the person does not have any children).ExamplesInput 3 0 Output YES 0 1 1 Input 5 1 Output YES 0 1 1 3 3 Input 3 2 Output NO NoteIn the first example case one can have a construction with 3 people, where 1 person has 2 parents.In the second example case one can use the following construction: Only person 1 is imbalanced, because one of their parents has 1 ancestor in total, and the other parent has 3 ancestors.
3 0
YES 0 1 1
1 second
512 megabytes
['constructive algorithms', 'divide and conquer', 'dp', 'math', 'trees', '*2800']
D. New Passenger Tramstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are many freight trains departing from Kirnes planet every day. One day on that planet consists of h hours, and each hour consists of m minutes, where m is an even number. Currently, there are n freight trains, and they depart every day at the same time: i-th train departs at h_i hours and m_i minutes.The government decided to add passenger trams as well: they plan to add a regular tram service with half-hour intervals. It means that the first tram of the day must depart at 0 hours and t minutes, where 0 \le t < {m \over 2}, the second tram departs m \over 2 minutes after the first one and so on. This schedule allows exactly two passenger trams per hour, which is a great improvement.To allow passengers to board the tram safely, the tram must arrive k minutes before. During the time when passengers are boarding the tram, no freight train can depart from the planet. However, freight trains are allowed to depart at the very moment when the boarding starts, as well as at the moment when the passenger tram departs. Note that, if the first passenger tram departs at 0 hours and t minutes, where t < k, then the freight trains can not depart during the last k - t minutes of the day. A schematic picture of the correct way to run passenger trams. Here h=2 (therefore, the number of passenger trams is 2h=4), the number of freight trains is n=6. The passenger trams are marked in red (note that the spaces between them are the same). The freight trains are marked in blue. Time segments of length k before each passenger tram are highlighted in red. Note that there are no freight trains inside these segments. Unfortunately, it might not be possible to satisfy the requirements of the government without canceling some of the freight trains. Please help the government find the optimal value of t to minimize the number of canceled freight trains in case all passenger trams depart according to schedule.InputThe first line of input contains four integers n, h, m, k (1 \le n \le 100\,000, 1 \le h \le 10^9, 2 \le m \le 10^9, m is even, 1 \le k \le {m \over 2}) — the number of freight trains per day, the number of hours and minutes on the planet, and the boarding time for each passenger tram.n lines follow, each contains two integers h_i and m_i (0 \le h_i < h, 0 \le m_i < m) — the time when i-th freight train departs. It is guaranteed that no freight trains depart at the same time.OutputThe first line of output should contain two integers: the minimum number of trains that need to be canceled, and the optimal starting time t. Second line of output should contain freight trains that need to be canceled.ExamplesInput 2 24 60 15 16 0 17 15 Output 0 0 Input 2 24 60 16 16 0 17 15 Output 1 0 2 NoteIn the first test case of the example the first tram can depart at 0 hours and 0 minutes. Then the freight train at 16 hours and 0 minutes can depart at the same time as the passenger tram, and the freight train at 17 hours and 15 minutes can depart at the same time as the boarding starts for the upcoming passenger tram.In the second test case of the example it is not possible to design the passenger tram schedule without cancelling any of the freight trains: if t \in [1, 15], then the freight train at 16 hours and 0 minutes is not able to depart (since boarding time is 16 minutes). If t = 0 or t \in [16, 29], then the freight train departing at 17 hours 15 minutes is not able to depart. However, if the second freight train is canceled, one can choose t = 0. Another possible option is to cancel the first train and choose t = 13.
2 24 60 15 16 0 17 15
0 0
2 seconds
512 megabytes
['binary search', 'brute force', 'data structures', 'sortings', 'two pointers', '*2300']
C. Choosing flowerstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputVladimir would like to prepare a present for his wife: they have an anniversary! He decided to buy her exactly n flowers.Vladimir went to a flower shop, and he was amazed to see that there are m types of flowers being sold there, and there is unlimited supply of flowers of each type. Vladimir wants to choose flowers to maximize the happiness of his wife. He knows that after receiving the first flower of the i-th type happiness of his wife increases by a_i and after receiving each consecutive flower of this type her happiness increases by b_i. That is, if among the chosen flowers there are x_i > 0 flowers of type i, his wife gets a_i + (x_i - 1) \cdot b_i additional happiness (and if there are no flowers of type i, she gets nothing for this particular type).Please help Vladimir to choose exactly n flowers to maximize the total happiness of his wife.InputThe first line contains the only integer t (1 \leq t \leq 10\,000), the number of test cases. It is followed by t descriptions of the test cases.Each test case description starts with two integers n and m (1 \le n \le 10^9, 1 \le m \le 100\,000), the number of flowers Vladimir needs to choose and the number of types of available flowers.The following m lines describe the types of flowers: each line contains integers a_i and b_i (0 \le a_i, b_i \le 10^9) for i-th available type of flowers.The test cases are separated by a blank line. It is guaranteed that the sum of values m among all test cases does not exceed 100\,000.OutputFor each test case output a single integer: the maximum total happiness of Vladimir's wife after choosing exactly n flowers optimally.ExampleInput 2 4 3 5 0 1 4 2 2 5 3 5 2 4 2 3 1 Output 14 16 NoteIn the first example case Vladimir can pick 1 flower of the first type and 3 flowers of the second type, in this case the total happiness equals 5 + (1 + 2 \cdot 4) = 14.In the second example Vladimir can pick 2 flowers of the first type, 2 flowers of the second type, and 1 flower of the third type, in this case the total happiness equals (5 + 1 \cdot 2) + (4 + 1 \cdot 2) + 3 = 16.
2 4 3 5 0 1 4 2 2 5 3 5 2 4 2 3 1
14 16
1 second
512 megabytes
['binary search', 'brute force', 'data structures', 'dfs and similar', 'dp', 'greedy', 'sortings', 'two pointers', '*2000']
B. Dubious Cyrptotime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputPasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l \leq a,b,c \leq r, and then he computes the encrypted value m = n \cdot a + b - c.Unfortunately, an adversary intercepted the values l, r and m. Is it possible to recover the original values of a, b and c from this information? More formally, you are asked to find any values of a, b and c such that a, b and c are integers, l \leq a, b, c \leq r, there exists a strictly positive integer n, such that n \cdot a + b - c = m. InputThe first line contains the only integer t (1 \leq t \leq 20) — the number of test cases. The following t lines describe one test case each.Each test case consists of three integers l, r and m (1 \leq l \leq r \leq 500\,000, 1 \leq m \leq 10^{10}). The numbers are such that the answer to the problem exists.OutputFor each test case output three integers a, b and c such that, l \leq a, b, c \leq r and there exists a strictly positive integer n such that n \cdot a + b - c = m. It is guaranteed that there is at least one possible solution, and you can output any possible combination if there are multiple solutions.ExampleInput 2 4 6 13 2 3 1 Output 4 6 5 2 2 3 NoteIn the first example n = 3 is possible, then n \cdot 4 + 6 - 5 = 13 = m. Other possible solutions include: a = 4, b = 5, c = 4 (when n = 3); a = 5, b = 4, c = 6 (when n = 3); a = 6, b = 6, c = 5 (when n = 2); a = 6, b = 5, c = 4 (when n = 2).In the second example the only possible case is n = 1: in this case n \cdot 2 + 2 - 3 = 1 = m. Note that, n = 0 is not possible, since in that case n is not a strictly positive integer.
2 4 6 13 2 3 1
4 6 5 2 2 3
1 second
512 megabytes
['binary search', 'brute force', 'math', 'number theory', '*1500']
A. Acacius and Stringtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputAcacius is studying strings theory. Today he came with the following problem.You are given a string s of length n consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once?Each question mark should be replaced with exactly one lowercase English letter. For example, string "a?b?c" can be transformed into strings "aabbc" and "azbzc", but can't be transformed into strings "aabc", "a?bbc" and "babbc".Occurrence of a string t of length m in the string s of length n as a substring is a index i (1 \leq i \leq n - m + 1) such that string s[i..i+m-1] consisting of m consecutive symbols of s starting from i-th equals to string t. For example string "ababa" has two occurrences of a string "aba" as a substring with i = 1 and i = 3, but there are no occurrences of a string "aba" in the string "acba" as a substring.Please help Acacius to check if it is possible to replace all question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once.InputFirst line of input contains an integer T (1 \leq T \leq 5000), number of test cases. T pairs of lines with test case descriptions follow.The first line of a test case description contains a single integer n (7 \leq n \leq 50), length of a string s.The second line of a test case description contains string s of length n consisting of lowercase English letters and question marks.OutputFor each test case output an answer for it.In case if there is no way to replace question marks in string s with a lowercase English letters in such a way that there is exactly one occurrence of a string "abacaba" in the resulting string as a substring output "No".Otherwise output "Yes" and in the next line output a resulting string consisting of n lowercase English letters. If there are multiple possible strings, output any.You may print every letter in "Yes" and "No" in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answer).ExampleInput 6 7 abacaba 7 ??????? 11 aba?abacaba 11 abacaba?aba 15 asdf???f???qwer 11 abacabacaba Output Yes abacaba Yes abacaba Yes abadabacaba Yes abacabadaba No No NoteIn first example there is exactly one occurrence of a string "abacaba" in the string "abacaba" as a substring.In second example seven question marks can be replaced with any seven lowercase English letters and with "abacaba" in particular.In sixth example there are two occurrences of a string "abacaba" as a substring.
6 7 abacaba 7 ??????? 11 aba?abacaba 11 abacaba?aba 15 asdf???f???qwer 11 abacabacaba
Yes abacaba Yes abacaba Yes abadabacaba Yes abacabadaba No No
1 second
512 megabytes
['brute force', 'implementation', 'strings', '*1500']
I. Cubic Latticetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA cubic lattice L in 3-dimensional euclidean space is a set of points defined in the following way: L=\{u \cdot \vec r_1 + v \cdot \vec r_2 + w \cdot \vec r_3\}_{u, v, w \in \mathbb Z} Where \vec r_1, \vec r_2, \vec r_3 \in \mathbb{Z}^3 are some integer vectors such that: \vec r_1, \vec r_2 and \vec r_3 are pairwise orthogonal: \vec r_1 \cdot \vec r_2 = \vec r_1 \cdot \vec r_3 = \vec r_2 \cdot \vec r_3 = 0 Where \vec a \cdot \vec b is a dot product of vectors \vec a and \vec b. \vec r_1, \vec r_2 and \vec r_3 all have the same length: |\vec r_1| = |\vec r_2| = |\vec r_3| = r You're given a set A=\{\vec a_1, \vec a_2, \dots, \vec a_n\} of integer points, i-th point has coordinates a_i=(x_i;y_i;z_i). Let g_i=\gcd(x_i,y_i,z_i). It is guaranteed that \gcd(g_1,g_2,\dots,g_n)=1.You have to find a cubic lattice L such that A \subset L and r is the maximum possible.InputFirst line contains single integer n (1 \leq n \leq 10^4) — the number of points in A.The i-th of the following n lines contains integers x_i, y_i, z_i (0 < x_i^2 + y_i^2 + z_i^2 \leq 10^{16}) — coordinates of the i-th point.It is guaranteed that \gcd(g_1,g_2,\dots,g_n)=1 where g_i=\gcd(x_i,y_i,z_i).OutputIn first line output a single integer r^2, the square of maximum possible r.In following 3 lines output coordinates of vectors \vec r_1, \vec r_2 and \vec r_3 respectively.If there are multiple possible answers, output any.ExamplesInput 2 1 2 3 1 2 1 Output 1 1 0 0 0 1 0 0 0 1 Input 1 1 2 2 Output 9 2 -2 1 1 2 2 -2 -1 2 Input 1 2 5 5 Output 9 -1 2 2 2 -1 2 2 2 -1
2 1 2 3 1 2 1
1 1 0 0 0 1 0 0 0 1
4 seconds
256 megabytes
['geometry', 'math', 'matrices', 'number theory', '*3500']
H. Set Mergingtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation a_1, a_2, \dots, a_n of numbers from 1 to n. Also, you have n sets S_1,S_2,\dots, S_n, where S_i=\{a_i\}. Lastly, you have a variable cnt, representing the current number of sets. Initially, cnt = n.We define two kinds of functions on sets:f(S)=\min\limits_{u\in S} u;g(S)=\max\limits_{u\in S} u.You can obtain a new set by merging two sets A and B, if they satisfy g(A)<f(B) (Notice that the old sets do not disappear).Formally, you can perform the following sequence of operations:cnt\gets cnt+1;S_{cnt}=S_u\cup S_v, you are free to choose u and v for which 1\le u, v < cnt and which satisfy g(S_u)<f(S_v).You are required to obtain some specific sets.There are q requirements, each of which contains two integers l_i,r_i, which means that there must exist a set S_{k_i} (k_i is the ID of the set, you should determine it) which equals \{a_u\mid l_i\leq u\leq r_i\}, which is, the set consisting of all a_i with indices between l_i and r_i.In the end you must ensure that cnt\leq 2.2\times 10^6. Note that you don't have to minimize cnt. It is guaranteed that a solution under given constraints exists.InputThe first line contains two integers n,q (1\leq n \leq 2^{12},1 \leq q \leq 2^{16})  — the length of the permutation and the number of needed sets correspondently.The next line consists of n integers a_1,a_2,\cdots, a_n (1\leq a_i\leq n, a_i are pairwise distinct)  — given permutation.i-th of the next q lines contains two integers l_i,r_i (1\leq l_i\leq r_i\leq n), describing a requirement of the i-th set.OutputIt is guaranteed that a solution under given constraints exists.The first line should contain one integer cnt_E (n\leq cnt_E\leq 2.2\times 10^6), representing the number of sets after all operations.cnt_E-n lines must follow, each line should contain two integers u, v (1\leq u, v\leq cnt', where cnt' is the value of cnt before this operation), meaning that you choose S_u, S_v and perform a merging operation. In an operation, g(S_u)<f(S_v) must be satisfied.The last line should contain q integers k_1,k_2,\cdots,k_q (1\leq k_i\leq cnt_E), representing that set S_{k_i} is the ith required set.Please notice the large amount of output.ExamplesInput 3 2 1 3 2 2 3 1 3 Output 6 3 2 1 3 5 2 4 6 Input 2 4 2 1 1 2 1 2 1 2 1 1 Output 5 2 1 2 1 2 1 5 3 3 1NoteIn the first sample:We have S_1=\{1\},S_2=\{3\},S_3=\{2\} initially.In the first operation, because g(S_3)=2<f(S_2)=3, we can merge S_3,S_2 into S_4=\{2,3\}.In the second operation, because g(S_1)=1<f(S_3)=2, we can merge S_1,S_3 into S_5=\{1,2\}.In the third operation, because g(S_5)=2<f(S_2)=3, we can merge S_5,S_2 into S_6=\{1,2,3\}.For the first requirement, S_4=\{2,3\}=\{a_2,a_3\}, satisfies it, thus k_1=4.For the second requirement, S_6=\{1,2,3\}=\{a_1,a_2,a_3\}, satisfies it, thus k_2=6Notice that unused sets, identical sets, outputting the same set multiple times, and using sets that are present initially are all allowed.
3 2 1 3 2 2 3 1 3
6 3 2 1 3 5 2 4 6
4 seconds
256 megabytes
['constructive algorithms', 'divide and conquer', '*3300']
G. Tree Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation: Choose three vertices a, b, and c such that b is adjacent to both a and c. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c. Delete the edge connecting a and b and add the edge connecting a and c. As an example, consider the following tree: The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5: It can be proven that after each operation, the resulting graph is still a tree.Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.InputThe first line contains an integer n (3 \le n \le 2 \cdot 10^5)  — the number of vertices in the tree.The i-th of the following n - 1 lines contains two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \neq v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.OutputPrint a single integer  — the minimum number of operations needed to transform the tree into a star.It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.ExamplesInput 6 4 5 2 6 3 2 1 2 2 4 Output 1 Input 4 2 4 4 1 3 4 Output 0 NoteThe first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed.
6 4 5 2 6 3 2 1 2 2 4
1
1 second
256 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'graph matchings', 'graphs', 'trees', '*2800']
F. Integer Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Anton and Harris are playing a game to decide which of them is the king of problemsetting.There are three piles of stones, initially containing a, b, and c stones, where a, b, and c are distinct positive integers. On each turn of the game, the following sequence of events takes place: The first player chooses a positive integer y and provides it to the second player. The second player adds y stones to one of the piles, with the condition that he cannot choose the same pile in two consecutive turns. The second player loses if, at any point, two of the piles contain the same number of stones. The first player loses if 1000 turns have passed without the second player losing.Feeling confident in his skills, Anton decided to let Harris choose whether he wants to go first or second. Help Harris defeat Anton and become the king of problemsetting!InputThe first line of input contains three distinct positive integers a, b, and c (1 \le a, b, c \le 10^9)  — the initial number of stones in piles 1, 2, and 3 respectively.InteractionThe interaction begins by reading the integers a, b and c.After reading the integers, print a single line containing either "First" or "Second", denoting who you want to play as (as first or second correspondently).On each turn, the first player (either you or the judge) must print a positive integer y (1 \le y \le 10^{12}).Then, the second player must print 1, 2, or 3, indicating which pile should have y stones added to it. From the second turn onwards, the pile that the second player chooses must be different from the pile that they chose on the previous turn.If you are playing as Second and complete 1000 turns without losing, or if you are playing as First and the judge has determined that it cannot make a move without losing, the interactor will print 0 and will finish interaction. This means that your program is correct for this test case, and you should exit immediately.If you are playing as First and complete 1000 turns without winning, or if you are playing as Second and print a move that makes two piles have the same number of stones, or if you output an invalid move as either player, the interactor will print -1 and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing something do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. In this problem, hacks are disabled.ExampleInput 5 2 6 3 0Output First 2 3 NoteIn the sample input, the piles initially have 5, 2, and 6 stones. Harris decides to go first and provides the number 2 to Anton. Anton adds 2 stones to the third pile, which results in 5, 2, and 8.In the next turn, Harris chooses 3. Note that Anton cannot add the stones to the third pile since he chose the third pile in the previous turn. Anton realizes that he has no valid moves left and reluctantly recognizes Harris as the king.
5 2 6 3 0
First 2 3
1 second
256 megabytes
['constructive algorithms', 'games', 'interactive', 'math', '*2600']
E. Inversion SwapSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMadeline has an array a of n integers. A pair (u, v) of integers forms an inversion in a if: 1 \le u < v \le n. a_u > a_v. Madeline recently found a magical paper, which allows her to write two indices u and v and swap the values a_u and a_v. Being bored, she decided to write a list of pairs (u_i, v_i) with the following conditions: all the pairs in the list are distinct and form an inversion in a. all the pairs that form an inversion in a are in the list. Starting from the given array, if you swap the values at indices u_1 and v_1, then the values at indices u_2 and v_2 and so on, then after all pairs are processed, the array a will be sorted in non-decreasing order. Construct such a list or determine that no such list exists. If there are multiple possible answers, you may find any of them.InputThe first line of the input contains a single integer n (1 \le n \le 1000) — the length of the array.Next line contains n integers a_1,a_2,...,a_n (1 \le a_i \le 10^9)  — elements of the array.OutputPrint -1 if no such list exists. Otherwise in the first line you should print a single integer m (0 \le m \le \dfrac{n(n-1)}{2}) — number of pairs in the list.The i-th of the following m lines should contain two integers u_i, v_i (1 \le u_i < v_i\le n).If there are multiple possible answers, you may find any of them.ExamplesInput 3 3 1 2 Output 2 1 3 1 2 Input 4 1 8 1 6 Output 2 2 4 2 3 Input 5 1 1 1 2 2 Output 0 NoteIn the first sample test case the array will change in this order [3,1,2] \rightarrow [2,1,3] \rightarrow [1,2,3].In the second sample test case it will be [1,8,1,6] \rightarrow [1,6,1,8] \rightarrow [1,1,6,8].In the third sample test case the array is already sorted.
3 3 1 2
2 1 3 1 2
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'sortings', '*2500']
D. Replace by MEXtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array of n integers between 0 and n inclusive.In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation).For example, if the current array is [0, 2, 2, 1, 4], you can choose the second element and replace it by the MEX of the present elements  — 3. Array will become [0, 3, 2, 1, 4].You must make the array non-decreasing, using at most 2n operations.It can be proven that it is always possible. Please note that you do not have to minimize the number of operations. If there are many solutions, you can print any of them. –An array b[1 \ldots n] is non-decreasing if and only if b_1 \le b_2 \le \ldots \le b_n.The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance: The MEX of [2, 2, 1] is 0, because 0 does not belong to the array. The MEX of [3, 1, 0, 1] is 2, because 0 and 1 belong to the array, but 2 does not. The MEX of [0, 3, 1, 2] is 4 because 0, 1, 2 and 3 belong to the array, but 4 does not. It's worth mentioning that the MEX of an array of length n is always between 0 and n inclusive.InputThe first line contains a single integer t (1 \le t \le 200) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (3 \le n \le 1000) — length of the array.The second line of each test case contains n integers a_1, \ldots, a_n (0 \le a_i \le n) — elements of the array. Note that they don't have to be distinct.It is guaranteed that the sum of n over all test cases doesn't exceed 1000.OutputFor each test case, you must output two lines:The first line must contain a single integer k (0 \le k \le 2n)  — the number of operations you perform.The second line must contain k integers x_1, \ldots, x_k (1 \le x_i \le n), where x_i is the index chosen for the i-th operation.If there are many solutions, you can find any of them. Please remember that it is not required to minimize k.ExampleInput 5 3 2 2 3 3 2 1 0 7 0 7 3 1 3 7 7 9 2 0 1 1 2 4 4 2 0 9 8 4 7 6 1 2 3 0 5 Output 0 2 3 1 4 2 5 5 4 11 3 8 9 7 8 5 9 6 4 1 2 10 1 8 1 9 5 2 4 6 3 7 NoteIn the first test case, the array is already non-decreasing (2 \le 2 \le 3).Explanation of the second test case (the element modified by each operation is colored in red): a = [2, 1, 0] ; the initial MEX is 3. a = [2, 1, \color{red}{3}] ; the new MEX is 0. a = [\color{red}{0}, 1, 3] ; the new MEX is 2. The final array is non-decreasing: 0 \le 1 \le 3. Explanation of the third test case: a = [0, 7, 3, 1, 3, 7, 7] ; the initial MEX is 2. a = [0, \color{red}{2}, 3, 1, 3, 7, 7] ; the new MEX is 4. a = [0, 2, 3, 1, \color{red}{4}, 7, 7] ; the new MEX is 5. a = [0, 2, 3, 1, \color{red}{5}, 7, 7] ; the new MEX is 4. a = [0, 2, 3, \color{red}{4}, 5, 7, 7] ; the new MEX is 1. The final array is non-decreasing: 0 \le 2 \le 3 \le 4 \le 5 \le 7 \le 7.
5 3 2 2 3 3 2 1 0 7 0 7 3 1 3 7 7 9 2 0 1 1 2 4 4 2 0 9 8 4 7 6 1 2 3 0 5
0 2 3 1 4 2 5 5 4 11 3 8 9 7 8 5 9 6 4 1 2 10 1 8 1 9 5 2 4 6 3 7
1 second
256 megabytes
['brute force', 'constructive algorithms', 'sortings', '*1900']
C. Element Exterminationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n, which initially is a permutation of numbers from 1 to n. In one operation, you can choose an index i (1 \leq i < n) such that a_i < a_{i + 1}, and remove either a_i or a_{i + 1} from the array (after the removal, the remaining parts are concatenated). For example, if you have the array [1, 3, 2], you can choose i = 1 (since a_1 = 1 < a_2 = 3), then either remove a_1 which gives the new array [3, 2], or remove a_2 which gives the new array [1, 2].Is it possible to make the length of this array equal to 1 with these operations?InputThe first line contains a single integer t (1 \leq t \leq 2 \cdot 10^4)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2 \leq n \leq 3 \cdot 10^5)  — the length of the array.The second line of each test case contains n integers a_1, a_2, ..., a_n (1 \leq a_i \leq n, a_i are pairwise distinct) — elements of the array.It is guaranteed that the sum of n over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case, output on a single line the word "YES" if it is possible to reduce the array to a single element using the aforementioned operation, or "NO" if it is impossible to do so.ExampleInput 4 3 1 2 3 4 3 1 2 4 3 2 3 1 6 2 4 6 1 3 5 Output YES YES NO YES NoteFor the first two test cases and the fourth test case, we can operate as follow (the bolded elements are the pair chosen for that operation):[\text{1}, \textbf{2}, \textbf{3}] \rightarrow [\textbf{1}, \textbf{2}] \rightarrow [\text{1}][\text{3}, \textbf{1}, \textbf{2}, \text{4}] \rightarrow [\text{3}, \textbf{1}, \textbf{4}] \rightarrow [\textbf{3}, \textbf{4}] \rightarrow [\text{4}][\textbf{2}, \textbf{4}, \text{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\textbf{4}, \textbf{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\text{4}, \text{1}, \textbf{3}, \textbf{5}] \rightarrow [\text{4}, \textbf{1}, \textbf{5}] \rightarrow [\textbf{4}, \textbf{5}] \rightarrow [\text{4}]
4 3 1 2 3 4 3 1 2 4 3 2 3 1 6 2 4 6 1 3 5
YES YES NO YES
1 second
256 megabytes
['constructive algorithms', 'data structures', 'greedy', '*1400']
B. Neighbor Gridtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a grid with n rows and m columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number k > 0 written on it, then exactly k of its neighboring cells have a number greater than 0 written on them. Note that if the number in the cell is 0, there is no such restriction on neighboring cells.You are allowed to take any number in the grid and increase it by 1. You may apply this operation as many times as you want, to any numbers you want. Perform some operations (possibly zero) to make the grid good, or say that it is impossible. If there are multiple possible answers, you may find any of them.Two cells are considered to be neighboring if they have a common edge.InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 5000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and m (2 \le n, m \le 300)  — the number of rows and columns, respectively.The following n lines contain m integers each, the j-th element in the i-th line a_{i, j} is the number written in the j-th cell of the i-th row (0 \le a_{i, j} \le 10^9).It is guaranteed that the sum of n \cdot m over all test cases does not exceed 10^5.OutputIf it is impossible to obtain a good grid, print a single line containing "NO".Otherwise, print a single line containing "YES", followed by n lines each containing m integers, which describe the final state of the grid. This final grid should be obtainable from the initial one by applying some operations (possibly zero).If there are multiple possible answers, you may print any of them.ExampleInput 5 3 4 0 0 0 0 0 1 0 0 0 0 0 0 2 2 3 0 0 0 2 2 0 0 0 0 2 3 0 0 0 0 4 0 4 4 0 0 0 0 0 2 0 1 0 0 0 0 0 0 0 0 Output YES 0 0 0 0 0 1 1 0 0 0 0 0 NO YES 0 0 0 0 NO YES 0 1 0 0 1 4 2 1 0 2 0 0 1 3 1 0 NoteIn the first test case, we can obtain the resulting grid by increasing the number in row 2, column 3 once. Both of the cells that contain 1 have exactly one neighbor that is greater than zero, so the grid is good. Many other solutions exist, such as the grid 0\;1\;0\;0 0\;2\;1\;0 0\;0\;0\;0 All of them are accepted as valid answers.In the second test case, it is impossible to make the grid good.In the third test case, notice that no cell has a number greater than zero on it, so the grid is automatically good.
5 3 4 0 0 0 0 0 1 0 0 0 0 0 0 2 2 3 0 0 0 2 2 0 0 0 0 2 3 0 0 0 0 4 0 4 4 0 0 0 0 0 2 0 1 0 0 0 0 0 0 0 0
YES 0 0 0 0 0 1 1 0 0 0 0 0 NO YES 0 0 0 0 NO YES 0 1 0 0 1 4 2 1 0 2 0 0 1 3 1 0
1 second
256 megabytes
['constructive algorithms', 'greedy', '*1200']
A. Sign Flippingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers a_1, a_2, \dots, a_n, where n is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold: At least \frac{n - 1}{2} of the adjacent differences a_{i + 1} - a_i for i = 1, 2, \dots, n - 1 are greater than or equal to 0. At least \frac{n - 1}{2} of the adjacent differences a_{i + 1} - a_i for i = 1, 2, \dots, n - 1 are less than or equal to 0. Find any valid way to flip the signs. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 500)  — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (3 \le n \le 99, n is odd)  — the number of integers given to you.The second line of each test case contains n integers a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9)  — the numbers themselves.It is guaranteed that the sum of n over all test cases does not exceed 10000.OutputFor each test case, print n integers b_1, b_2, \dots, b_n, corresponding to the integers after flipping signs. b_i has to be equal to either a_i or -a_i, and of the adjacent differences b_{i + 1} - b_i for i = 1, \dots, n - 1, at least \frac{n - 1}{2} should be non-negative and at least \frac{n - 1}{2} should be non-positive.It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.ExampleInput 5 3 -2 4 3 5 1 1 1 1 1 5 -2 4 7 -6 4 9 9 7 -4 -2 1 -3 9 -4 -5 9 -4 1 9 4 8 9 5 1 -9 Output -2 -4 3 1 1 1 1 1 -2 -4 7 -6 4 -9 -7 -4 2 1 -3 -9 -4 -5 4 -1 -9 -4 -8 -9 -5 -1 9 NoteIn the first test case, the difference (-4) - (-2) = -2 is non-positive, while the difference 3 - (-4) = 7 is non-negative.In the second test case, we don't have to flip any signs. All 4 differences are equal to 0, which is both non-positive and non-negative.In the third test case, 7 - (-4) and 4 - (-6) are non-negative, while (-4) - (-2) and (-6) - 7 are non-positive.
5 3 -2 4 3 5 1 1 1 1 1 5 -2 4 7 -6 4 9 9 7 -4 -2 1 -3 9 -4 -5 9 -4 1 9 4 8 9 5 1 -9
-2 -4 3 1 1 1 1 1 -2 -4 7 -6 4 -9 -7 -4 2 1 -3 -9 -4 -5 4 -1 -9 -4 -8 -9 -5 -1 9
1 second
256 megabytes
['constructive algorithms', 'math', '*1100']
F. Cyclic Shifts Sortingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers.In one move, you can choose some index i (1 \le i \le n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (3 \le n \le 500) — the length of a. The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 500), where a_i is the i-th element a.It is guaranteed that the sum of n does not exceed 500.OutputFor each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, \dots, idx_{ans} (1 \le idx_i \le n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations.ExampleInput 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4
5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4
0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'implementation', 'sortings', '*2400']
E2. Reading Books (hard version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEasy and hard versions are actually different problems, so read statements of both problems completely and carefully.Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read exactly m books before all entertainments. Alice and Bob will read each book together to end this exercise faster.There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not).So they need to choose exactly m books from the given n books in such a way that: Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; the total reading time of these m books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set.Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.InputThe first line of the input contains three integers n, m and k (1 \le k \le m \le n \le 2 \cdot 10^5).The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 \le t_i \le 10^4, 0 \le a_i, b_i \le 1), where: t_i — the amount of time required for reading the i-th book; a_i equals 1 if Alice likes the i-th book and 0 otherwise; b_i equals 1 if Bob likes the i-th book and 0 otherwise. OutputIf there is no solution, print only one integer -1.If the solution exists, print T in the first line — the minimum total reading time of the suitable set of books. In the second line print m distinct integers from 1 to n in any order — indices of books which are in the set you found.If there are several answers, print any of them.ExamplesInput6 3 16 0 011 1 09 0 121 1 110 1 08 0 1Output246 5 1 Input6 3 26 0 011 1 09 0 121 1 110 1 08 0 1Output394 6 5
Input6 3 16 0 011 1 09 0 121 1 110 1 08 0 1
Output246 5 1
3 seconds
256 megabytes
['data structures', 'greedy', 'implementation', 'sortings', 'ternary search', 'two pointers', '*2500']
E1. Reading Books (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEasy and hard versions are actually different problems, so read statements of both problems completely and carefully.Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster.There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not).So they need to choose some books from the given n books in such a way that: Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set.Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.InputThe first line of the input contains two integers n and k (1 \le k \le n \le 2 \cdot 10^5).The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 \le t_i \le 10^4, 0 \le a_i, b_i \le 1), where: t_i — the amount of time required for reading the i-th book; a_i equals 1 if Alice likes the i-th book and 0 otherwise; b_i equals 1 if Bob likes the i-th book and 0 otherwise. OutputIf there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books.ExamplesInput8 47 1 12 1 14 0 18 1 11 0 11 1 11 0 13 0 0Output18Input5 26 0 09 0 01 0 12 1 15 1 0Output8Input5 33 0 02 1 03 1 05 0 13 0 1Output-1
Input8 47 1 12 1 14 0 18 1 11 0 11 1 11 0 13 0 0
Output18
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', '*1600']